How to Use Accelerometer in AS3 AIR

49 / 100

Question in Mind:

How to control a car with Accelerometer sensor in ActionScript 3 (AS3)?
How to read Accelerometer sensor property with ActionScript 3 (AS3)?
How to test Accelerometer with AS3 in iOS And Android Devices?

Solution:

  • Step 1 – Open Adobe Flash then create a new document using File > New… > from “General” Tab select “AIR for iOS” or “AIR for Android” then click “OK” button.
  • Step 2 – Create a Movie Clip on document stage Then set a instance name “car”.
  • Step 3 – Copy this script and past it to your selected timeline frame then publish it on a selected device using USB debuging. Then test it, hope you will enjoy!
//Import Library
import flash.sensors.Accelerometer;
import flash.events.Event;

//Variables
var accelX:Number;
var accelY:Number;
var fl_Accelerometer:Accelerometer = new Accelerometer();

//Get Accelerometer Property
fl_Accelerometer.addEventListener(AccelerometerEvent.UPDATE, fl_AccelerometerUpdateHandler);
//Move Object 
this.car.addEventListener(Event.ENTER_FRAME, moveCar);

//Get Accelerometer Movement
function fl_AccelerometerUpdateHandler(event:AccelerometerEvent):void
{
    accelX = event.accelerationX;
    accelY = event.accelerationY;
}

//Control Car with Accelerometer
function moveCar(evt:Event){
    this.car.x -= accelX*30;
    this.car.y += accelY*30;
//Limit platform	
    if(this.car.x > (480-this.car.width/2)){
        this.car.x = 480-this.car.width/2;
    }
    if(this.car.x < (0+this.car.width/2)){
        this.car.x = 0+this.car.width/2;
    }
}

Note: AS3 Accelerometer is supported only on smart mobile devices where Accelerometer sensor available.

Technical Info:
Package: flash.sensors
Class: public class Accelerometer
Inheritance: Accelerometer > EventDispatcher > Object
Language Version: ActionScript 3.0
Runtime Versions: AIR 2, Flash Player 10.1, Flash Lite 4

Incoming Searches:  as3 accelerometer, accelerometer flash

Comments

comments