(AS3) Accelerometer on AIR SDK

Posted: April 19, 2011 in Android, Flash / Actionscript 3, Game Programming, Programming
Tags: , ,

In this article i want to share a simple way to use accelerometer on AIR SDK. Since we’re using AIR SDK, you can deploy your application in Anroid or IPhone. But the code that i want to share is actually intended to be deployed on Android (since i don’t have IPhone device) :p

First we need to import several libraries :

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

This is the MovieClip that will be moved by accelerometer

private var haro:HaroSymbol;

An variable of accelerometer

private var accel:Accelerometer;

Two variables that will store tilt factor in x an y axis

private var targetX:Number = 0;
private var targetY:Number = 0;

I have an function to setup accelerometer and the movie clip, if the device supports accelerometer, we’ll instantiate accel variable, add listener of accelerometer update event to accel variable, setup the MovieClip at the middle of the screen, and add a listener ENTER_FRAME

private function setup():void

	if ( Accelerometer.isSupported )
		accel = new Accelerometer();
		accel.addEventListener( AccelerometerEvent.UPDATE, onAccelUpdate );

		haro = new HaroSymbol();
		haro.x = xSize / 2;
		haro.y = ySize / 2;

		addEventListener(Event.ENTER_FRAME, moveHaro);

This is onAccelUpdate function, targetX and targetY will store the accelaration of x and y axis (multiplied by 50, if you want the object to move faster of slower, simply change this constant)

protected function onAccelUpdate( event:AccelerometerEvent ):void
	targetX = event.accelerationX * 50;
	targetY = event.accelerationY * 50;

Function to move the MovieClip

protected function moveHaro(event:Event):void
	haro.x -= targetX;
	haro.y += targetY;

You can download the full source code at the link below…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s