Free Accelerometer Tutorial with Actionscript 3, Flash CS5 and Device Central

Here’s a relatively short tutorial on using the new Accelerometer code in Actionscript 3 to create a simple tilt game where a ball potentially falls into a hole. This could be ported out to either the iPhone or Android, or any touch enabled device that Flash Player 10.1 runs on. Example files for this tutorial can be found at… cartoonsmart.com/​vimeo/​accelerometer_examples.zip

The fun-on-a-bun part of the Accelerometer code has been pasted below…

import flash.sensors.Accelerometer;

import flash.events.AccelerometerEvent;

var theAcc:Accelerometer = new Accelerometer();

theAcc.setRequestedUpdateInterval( 50 );
if (Accelerometer.isSupported == true) {

trace (“yep, it has that functionality”);

theAcc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);

}else {

// do something different for the entire app

}

function onAccUpdate( e:AccelerometerEvent ):void {

//trace ( e.accelerationX );

//trace ( e.accelerationY );

ball.x -= ( e.accelerationX * 10);

ball.y += ( e.accelerationY * 10);

if ( ball.x < 0 ) {

ball.x = 0;

} else if (ball.x > stage.stageWidth ) {

ball.x = stage.stageWidth;

}

if ( ball.y < 0 ) {

ball.y = 0;

} else if (ball.y > stage.stageHeight ) {

ball.y = stage.stageHeight;

}

} //closes the onAccUpdate function

//more code is in the example files

4 thoughts on “Free Accelerometer Tutorial with Actionscript 3, Flash CS5 and Device Central

  1. It could be I am mistaken, but CS4 does not carry the option of testing the movie on Device Central from the Control -> Test movie on the menu. Since my Flash CS4 runs stable, and CS5 was unstable on my system, I am taking my time before upgrading. The tutorial is very good, as usual.

  2. Alex says:

    Can u add code that put an obstacle on the floor that if the ball hits it it cant continue???

    thanks that wud rock!

  3. Alex says:

    also if possible make it so 4 obstacles appear randomly each time you get it in hole starts over… the obstacles change positions… this would be great possible???

Leave a comment