Do you like my tutorials?

Then consider supporting me on Ko-fi

Talking about iOS and Javascript.

As you all know, the iPhone has an accelerometer which can help you to detect phone movements and tilts.

With javascript’s devicemotion event you can add a listener to your iPhone browser and have your x, y and z acceleration values ready to be used in your scripts.

Before we see any script, let’s see what these acceleration values mean: if you place your iPhone on a table, that’s what you can get:

X: roll, that is the rotation around the vertical axis, from the home button to the earpiece.

Y: pitch, that is the rotation around the horizontal axis.

Z: yaw… no… surprise! It’s not the yaw, it’s just a face up/face down detection. This means you can toss your iPhone in the air and play “head or tail” just like you are used to do with coins.

(warning: tossing your iPhone in the air can cause damage to the phone itself and injuries to nearby people)

Even more interesting, with the iPhone in your hand you can determine where is the “sky”, that is the iPhone highest point, just combining X and Y values and some trigonometry. Useful if you are buried under an avalanche.

(warning: getting buried under an avalanche may reduce life expectancy)

So this is what you can do with a little jQuery Mobile script and a touch of HTML5 canvas:

This is the code:

 
 
 
     
      
     

     
     
     
     
         
	
	
 
 

Accelerometer

The core lies at line 15 (the listener) and 20 (getting acceleration data).

You can see it in action pointing your iPhone browser at this link:

http://emanueleferonato.com/stuff/iaccelerometer/

or using this QRCode:

And that’s it!

Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.