Using The Accelerometer Sensor in ActionScript 3

By Blue_Chi | Flash CS5 | AS3 | Beginner

You can track the rotation of a mobilde device by using the accelerometer sensor on it. Techniques making use of the accelerometer may be used to rotate the screen when the device is rotated or to control an object in a game by rotating the phone. Interacting with your smart phone by rotating it around has now become a common feature in many mobile applications, ActionScript 3.0 makes it very easy to add such functionality to any application you develop by using the Accelerometer Class.

This tutorial will teach you the basics on how to use the Accelerometer Class and how to control and object on stage by using it. This is a beginner tutorial that only assumes that you know the basics of AS3 Variables and Classes, and AS3 Event Handling.

You should note that the Accelerometer Class is currently only available for AIR 2, Flash Player 10.1, Flash Lite 4, and iPhone Flash apps. On Android phones you will only be using this feature if the phone runs Flash Player 10.1.

 

Preparing the Stage and Graphical Elements

At the time of writing this tutorial, Flash CS5 does not support testing accelerometer capabilities for Flash iPhone applications inside the authoring tools or even Device Central. Everything mentioned here can be applied directly in a Flash iPhone application (you can even copy and paste the code), but we will be creating a generic Flash movie and not an iPhone application so that we can test our project in Device Central during the project.

Start off by launching Flash CS5 and going through File>New, from here select Adobe Device Central as the type. This will allow us to select a template from a mobile device to work with.

AS3 Accelerometer - New Device Central

Here select one of the Flash Player 10.1 generic devices. I selected the one with 320x480 screen, once you are ready click on Create on the lower right corner of the screen, and should take you back to Flash CS5.

AS3 Accelerometer - New From Device Central

Our movie is now in the right format and in the right size. We will create an object to manipulate with our accelerometer and a text field to display the status. Use the Oval Tool to draw a circle in the center of the stage. Select this circle and go through Modify>Convert to Symbol to convert it to a MovieClip Symbol. It is easier to manipulate objects if they are converted into a symbol. Now while still having the circle selected, access the Properties Inspector and set the Instance Name of the circle to my_dot.

AS3 Accelerometer Flash Tutorial

Instance names help us refer to objects using ActionScript.

 

That circle will be moved around using the accelerometer later, we need to have a text field to show the status of what is happening. Grab the Text Tool and draw a small text field at the top of of the stage, then access the Properties Inspector, change the font to _sans, and set the instance name to my_txt.

AS3 Accelerometer Tutorial - Text Field

Our graphical elements are now ready, we will use ActionScript next to move them around.

Accelerometer Class

It is time to start using our accelerometer using ActionScript, our code will have two primary tasks, the first is to detect whether the device displaying the movie has accelerometer capabilities, and the second is move an object around by rotating the device. Lets do that, right-click the only frame you have on the timeline and select Actions to open up the Actions panel.

To start off, before you can use the accelerometer in any way, you have to import its ActionScript classes into the project. To do that we use the import command, type the following to do it:

import flash.sensors.Accelerometer;
import flash.events.AccelerometerEvent;

Using the Accelerometer Class is identical to that of any AS3 Class, we have to create an instance of the class by using the new keyword and store this object inside a variable:

import flash.sensors.Accelerometer;
import flash.events.AccelerometerEvent;

var my_acc:Accelerometer = new Accelerometer();
You can learn about AS3 Variables and Classes by reviewing our tutorial on this topic.


We now have an instance of the Accelerometer Class at our disposal.

Detecting Accelerometer Capability

If you make a Flash project that will be available publically you should always make your movie check if the device running the movie has accelerometer capabilities before attempting to use it. This way you can have display a message saying that the accelerometer is not support or use a conditional to execute alternative code in this situation.

To check for accelerometer is support you need to retrieve the .isSupported property of the Accelerometer class. The value of this property is true if it is supported, and false if it is not supported.

We are going to retrieve this value and display on our text field this way:

import flash.sensors.Accelerometer;
import flash.events.AccelerometerEvent;

var my_acc:Accelerometer = new Accelerometer();

my_txt.text = "Acc support is "+Accelerometer.isSupported;
You can learn more about working with Text Fields by reviewing our tutorial on this topic.
This is one of the few situations where we use a Class directly instead of using its instance to retrieve information.

You can now test your movie at this stage. Go through Control>Test Movie and make sure that in Device Central is checked. Then go again through Control>Test Movie>Test to see your movie played in the emulator.

AS3 Accelerometer Flash Tutorial

The value shown is true, devices that do not support the accelerometer would display false. If your project is intended to be of general application you should have code in place to deal with what happens if the accelerometer is not supported - this however is beyond the scope of this tutorial.

Tracking Accelerometer Changes

Tracking accelerometer changes requires doing the following:

  1. Registering for the Accelerometer UPDATE event.
  2. Creating a listener function to be triggered through this event.
  3. Retrieve the various acceleration properties through the listener function.

We are going to do this step by step. First we need to register for AccelerometerEvent.UPDATE which gets constantly updated to check for changes in the rotation of the device. We will register this event with a listener function onAccUpdate which we will create in a bit.

import flash.sensors.Accelerometer;
import flash.events.AccelerometerEvent;

var my_acc:Accelerometer = new Accelerometer();

my_txt.text = "Acc support is "+Accelerometer.isSupported;

my_acc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);

We will now create the onAccUpdate() function which will retrieve the acceleration values of the device by retrieving these properties from the AccelerometerEvent property. There are three acceleration properties:

  • accelerationX
  • accelerationY
  • accelerationZ

Each of these properties will retrieve a value between 1 and -1 indicating the direction at which the device has been rotated. Most applications will require using two of these axes at a time. We will start by displaying the value of acceleration in the output window without having it do anything with our object.

import flash.sensors.Accelerometer;
import flash.events.AccelerometerEvent;

var my_acc:Accelerometer = new Accelerometer();

my_txt.text = "Acc support is "+Accelerometer.isSupported;

my_acc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);
function onAccUpdate(e:AccelerometerEvent):void{
trace("X axis = "+e.accelerationX);
trace("Y axis = "+e.accelerationY);
trace("Z axis = "+e.accelerationZ);
}

Test your movie now in Device Central, you can emulate acceleration movement by accessing the Accelerometer Panel by going through Window>Flash>Accelerometer. The panel should appear in the corner of the window.

AS3 Accelerometer Flash Device Central

The panel has a radio button option above for Flat or Upright placement, which let you either control the x and y axes, or the x and z axes depending on the nature of your program. You can use your mouse to rotate your phone around, you should play with both Flat and Upright to see the difference in movement and get a feel of which axis relates to which motion.

You should be able to see that the Output in both Flash and Device Central will show you the changes in the value of the axes as you move your phone around in the emulator.

AS3 Accelerometer Flash Tutorial - Output Panel

The value of each of these axes as you can see extends from -1 to 1 depending on the way the device is rotated. You can use these properties in any way you wish as they are readily available in a numeric format. For the purpose of this tutorial we need to move the object placed on the stage while having the device held flat. To do this we need to use two axes only, the x and the y. Each of these acceleration axes will move the object along the corresponding axis on the stage.

Doing this is easily, we will simply modify the location of the object my_dot by updating its x and y property. The value of the acceleration value is tiny, so we are going to multiply it by 10 to make its effect visible. We are then going to adding it to the value of these property. Update your existing code this way to see the trick in action:

import flash.sensors.Accelerometer;
import flash.events.AccelerometerEvent;

var my_acc:Accelerometer = new Accelerometer();

my_txt.text = "Acc support is "+Accelerometer.isSupported;

my_acc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);
function onAccUpdate(e:AccelerometerEvent):void{
my_dot.x -= (e.accelerationX*10);
my_dot.y += (e.accelerationY*10);
}
We had to subtract the value of the x property and add that of the y property in order to make the motion seem predictable. Switching any of these signs will make the object move in the opposite direction.

Test your movie now and move the phone around using the accelerometer panel, you should the dot moving around!

As you have seen, it is pretty easy to use the accelerometer, however, you will have to do additional work to make sure that your movie does not break easily, so in this example, we have to make sure that the object does not leave the stage and disappears! We can do that by using a number of conditionals.

import flash.sensors.Accelerometer;
import flash.events.AccelerometerEvent;

var my_acc:Accelerometer = new Accelerometer();

my_txt.text = "Acc support is "+Accelerometer.isSupported;

my_acc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);
function onAccUpdate(e:AccelerometerEvent):void{
my_dot.x -= (e.accelerationX*10);
my_dot.y += (e.accelerationY*10);

if (my_dot.x < 0) {
my_dot.x = 0;
} else if (my_dot.x > stage.stageWidth) {
my_dot.x = stage.stageWidth;
}

if (my_dot.y < 0) {
my_dot.y = 0;
} else if (my_dot.y > stage.stageHeight)
{ my_dot.y = stage.stageHeight;
}

}
You can learn more about AS3 Conditionals by reviewing our tutorial on this topic.

Modifying the Frequency of the Updates

In our example we have used the default update rate at which the accelerometer will tell us of the values of acceleration, depending on the nature of your application, this speed might be too slow or fast for you. You configure how often the updates are triggered by using the setRequestedUpdateInterval() method. For example. If we want our object to move more smoothly we can request having an update every 50 milliseconds this way:

import flash.sensors.Accelerometer;
import flash.events.AccelerometerEvent;

var my_acc:Accelerometer = new Accelerometer();
my_acc.setRequestedUpdateInterval(50);

my_txt.text = "Acc support is "+Accelerometer.isSupported;

my_acc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);
function onAccUpdate(e:AccelerometerEvent):void{
my_dot.x -= (e.accelerationX*10);
my_dot.y += (e.accelerationY*10);

if (my_dot.x < 0) {
my_dot.x = 0;
} else if (my_dot.x > stage.stageWidth) {
my_dot.x = stage.stageWidth;
}

if (my_dot.y < 0) {
my_dot.y = 0;
} else if (my_dot.y > stage.stageHeight)
{ my_dot.y = stage.stageHeight;
}

}

You should be aware that higher request rates would would consume the devices battery quicker than slower ones.

This concludes our tutorial, you can download the end result source file from this link. If you have any questions feel free to post them at the Republic of Code Forum. We would love to see anything cool you make, so feel free to share that with us as well!

- End of Tutorial