Accessing the Accelerometer in a Windows 8 Metro Style App using HTML and JavaScript

Overview

I have recently been coding a Windows 8 Metro Style App using the new Windows 8 Release Preview bits and Visual Studio Express 2012 RC.  The app is going to be a retro shooter that takes advantage of HTML5 Canvas for the main game engine and then several Windows 8 Metro Style App Features.  Rather then wait for the game to be completely finished I figured I would start sharing some of my development experiences here on my blog.

One of the first ideas I had was for a “Gravity Pulse” power that would be granted upon earning a predefined a amount of points (1,500 pts being the default).  Every time the user gains these amount of points a custom sound file will be played and then the screen will display a message to shake the device.  If the user shakes the device within a predefined amount of time all ships on the screen will blow up. 

Gravity Pulse - Shake the Screen!

 

The language I chose to use was HTML and JavaScript but this example could just have easily been done in C++/XAML or C#/XAML.  The code needed to access the accelerometer was very small and I was impressed just how easy it was to add to my game.

Declaration and Initialization

I start out by defining three local class variables I will use to access the sensor itself and default values for the polling interval.

 //accelerometer
    var accelerometer;
    var intervalId = 0;
    var getReadingInterval = 0;

Once the DOM of the default.js page has been loaded I call a custom function (named initialize).

 //If Document fully loaded than begin processing
    document.addEventListener("DOMContentLoaded", initialize, false);

Inside of initialize I set up all of my ships, the coordinate system for the gameboard and other important details.  There is a function I have created that will handle the accelerometer instance called initAccel.

 //Set up accelerometer for shake events
       initAccel();
 //Init Accelerometer
 function initAccel() {
     accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();
     if (accelerometer) {
         // Choose a report interval supported by the sensor
         var minimumReportInterval = accelerometer.minimumReportInterval;
         var reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 16;
         accelerometer.reportInterval = reportInterval;
         getReadingInterval = reportInterval * 2; // double the interval for display (to reduce CPU usage)
         
     } else {
        displayError("No accelerometer found");
     }
 }

The initAccel function assigns the default accelerometer (through the magic of WinRT) to the class variable accelerometer and if it finds a device it sets up the reporting interval properties.  Reporting interval is how often we will receive new sensor readings from the accelerometer so it is important to pick a value that won’t kill our cpu.

 

Handling the Accelerometer Readings

Always remember accessing the sensor (as in any other devices) will cause cpu load and drain your battery.  I am careful to only turn the sensor on when the user hits the predefined amount of points and then I shut it off until the next gravity pulse becomes available.  Fortunately this is easy to do in JavaScript by controlling the eventListener.  If the accelerometer object has an eventListener assigned to it it will be actively polling for new data. 

The function I use to check for an in progress Gravity Pulse is called updateScore.  This is where I start listening to accelerometer readings by assigning an eventListener for “shake events” as well as updating the screen and playing a wav file (more on playing sounds and external libraries to come)

 //update player score
     function updateScore(points) {
  
         score += points;
         scoreGravity += points;
         txtScore.innerHTML = "  Score: " + score;
  
         if (scoreGravity === GRAVITY_WAVE_PTS_REQ) {
             accelerometer.addEventListener("shaken", onShakenAccel);
             txtScore.innerHTML = " > SHAKE THAT SCREEN <";
             scoreGravity = 0;
             SoundJS.play("pulse", SoundJS.INTERRUPT_ANY);
         }
  
         //new level
         lvlNextPts = (lvlCurrent + 1) * LEVEL_PTS_REQ;
         if (score >= lvlNextPts) {
             lvlCurrent++;
             txtLevel.innerHTML = "Level: " + lvlCurrent;
             lvlDifficulty = LEVEL_SPEED_INCREASE * lvlCurrent;
  
             SoundJS.play("newlevel",SoundJS.INTERUPT_ANY);
  
         }
  
  
     }

When a user shakes the Windows 8 tablet enough to register a “shake” event the onShakenAccel eventHandler is called and the following code invoked:

 

 //Accelerometer has been shaken and now we need to grant the bonus power
  function onShakenAccel(event) {
       //Stop Listening to Accelerometer
      accelerometer.removeEventListener("shaken", onShakenAccel);
  
      //Gravity Wave Power - Destroy all ships
      gravityWave();
     
  }

 

You will notice the first thing I do is remove the eventListener which will effectively turn off the Accelerometer Sensor and then I call a custom function to blow up the on screen ships.

 

Conclusion

That’s it!  By adding a few eventListeners and a call into the WinRT Windows.Device.Sensors namespace my game has full accelerometer support!  Hopefully this post will help you get started in adding sensor support in your own Metro Style Apps.  As Always - if you are currently working on a Windows 8 app I would love to hear about it!

You may also want to check out my previous Windows 8 Metro Style Development Tips: