Sample Game - Using Device Sensors in your Web Applications

Sample Game - Using Device Sensors in your Web Applications

Tizen devices have built-in sensors to measure the device motion, orientation and many more. The sample game application helps understanding the use of device acceleration sensors in your web applications using the W3C DeviceOrientation Event API. The game is simple, the shooter shoots the planes and every successful shot adds a point to his score. The shooter can move in left and right direction i.e on X-axis depending on the device movement. When the user moves the device on X-axis, the acceleration is calculated and the shooter is moved accordingly in the desired direction.

The acceleration sensor measures changes in velocity. It can also be used to determine orientation. The acceleration sensor measures the device's acceleration vector in 3 axes relative to its body frame. The acceleration sensor provides 3 components of acceleration (X, Y, Z), as the following figure illustrates.

Application features,

  • Acceleration sensor to move the object on device movement
  • Canvas to draw the objects of the game
  • LocalStorage for persistent data to record the game high score

Handling Acceleration Event

You might need to add the listener to the window object to detect the device motion events as below,

window.addEventListener("devicemotion", function(e) {
    }, true);

And then define the deviceMotionCallbackHandler handler function, which is triggered on device motion event with the X and Y-axis (only X-axis handled in our case) values of the accelerationIncludingGravity attribute. The same attribute value is used to calculate the new shooter position. To avoid the shooter object going off the screen (when the values increase), the values are adjusted accordingly with the screen width.

function deviceMotionCallbackHandler(e) {		
		 //Calculate the acceleration due to gravity
      ax = e.accelerationIncludingGravity.x * 5;
      vx = vx + ax;
      vx = vx * 0.98;

      px = parseInt(Math.round(px + (vx / 20)));
      // Bound Check
      if (px <= 0) {
      	   px = 0;
      	   vx = -vx;
      if (px >= document.documentElement.clientWidth - 100) {
             px = document.documentElement.clientWidth - 100;
             vx = -vx;
      shooter.x = px;         
	} // deviceMotionCallbackHandler ends	

Rest of the game logic is self explanatory. You can find the source code of the sample application attached at the bottom of this article.


Development Environment:

Tizen SDK Version : 2.2.1

Build id : 20130927-1459

File attachments: