Accelerometer, compass and keep screen awake #

Sensors #

sys.sensors provides accelerometer and compass access. Desktop builds report unavailable. Android uses native sensors. Web uses browser device motion and orientation APIs when available.

main.js
// Start sensors only when the platform reports support.
if (sys.sensors.isAvailable()) {
  // Activate accelerometer and compass polling.
  sys.sensors.start();
}

// Read sensor state once per frame.
function frame() {
  // Get the latest accelerometer sample, if any.
  const accel = sys.sensors.getAccel();
  // Update tilt state only when a sample exists.
  if (accel) {
    // Store horizontal tilt.
    state.tiltX = accel.x;
    // Store vertical tilt.
    state.tiltY = accel.y;
  }

  // Get the latest compass sample, if any.
  const compass = sys.sensors.getCompass();
  // Update heading only when a compass sample exists.
  if (compass) {
    // Store heading in degrees.
    state.heading = compass.heading;
  }

  // Render the current sensor-driven state.
  draw();
  // Continue the frame loop.
  sys.animation.requestFrame(frame);
}

Accelerometer values include gravity. Compass heading is a simplified two-dimensional bearing and assumes the device is held flat.

Keeping the screen awake #

Some apps should keep the screen on while active: timers, instruments, kiosks, games during play, and monitoring tools.

main.js
// Keep the display awake while the active experience needs it.
sys.device.keepScreenOn(true);

Call keepScreenOn(false) when the app returns to a menu or state that no longer needs it. Desktop toggles the SDL screensaver. Android toggles FLAG_KEEP_SCREEN_ON. Web uses the Screen Wake Lock API when the browser allows it.

Platform notes #

Sensors and wake locks depend on platform permissions or linked backends. Use capability checks and clear UI states.