Using the Accelerometer
Many modern smartphones come equiped with an accelerometer - a device that measures acceleration forces. It is the accelerometer in an iPhone or Android device, for instance, that senses orientation changes when you tilt your phone from portrait (taller-than-wide) to landscape (wider-than-tall) mode.
To illustrate the use of the accelerometer, let's write a simple game for the Jazz Calendar site: users are asked to tilt their iPhone to move the blue note into the sax at lower right:
We test whether
window.ondevicemotion = function(event) gets the current state of the phone, with
event.accelerationIncludingGravity.y exposing the x and y components of acceleration.
setInterval function runs every 10 milliseconds, updating the CSS absolute position of the
#note image. Physics 101 gives us velocity from acceleration and position from velocity; we update the CSS position of the
#note image each time, checking to make sure it stays within the
#yes div layer. We display the x and y position each time, along with a "You win!" message if the
#code image lands on the sax. The Angry Birds folks probably aren't worried about our game competing with their franchise, but it illustrates the concept nicely. And thanks to the folks at menscher.com for the idea.