Basic Movement Using Accelerometer Sensor in Flash CS5 - Most of mobile devices which using Android OS, Symbian^3 and Symbian Anna OS, BlackBerry PlayBook OS and iOS has accelerometer sensor. And I think playing game in those devices with accelerometer sensor is more fun :)

The good news is ActionScript 3 support accelerometer sensor. Nokia devices that using Symbian^3 and Symbian Anna OS like Nokia N8 and Nokia X7 are Flash Lite 4 enabled. With Flash Lite 4 in Nokia device, we can use accelerometer sensor to moving object in game. We can also use accelerometer sensor in Adobe AIR app in Android, PlayBook OS and iOS.

Here is basic object movement using accelerometer sensor with ActionScript 3 :

  1. Create a MovieClip with instance name circle in Layer 1.

    Accelerometer in Flash Lite 4

  2. Double click the MovieClip and then make two label called “left” and “right”. Make sure that the circle object in “left” label is different with circle object in “right” label.

    Left

    Accelerometer in AIR 2.6

    Right

    Accelerometer sensor in Flash to iPhone

  3. In Layer 3 Frame 1, don’t forget to put ActionScript stop(); function.
  4. Back to root timeline. In Layer 2, write the ActionScript like this :
    import flash.sensors.Accelerometer;
    import flash.events.AccelerometerEvent;
    import flash.events.Event;

    var acc:Accelerometer = new Accelerometer();
    var tx:int = 0;
    var speed:int = 8;

    function update(e:AccelerometerEvent):void
    {
    tx = e.accelerationX * 20;
    }

    function loop(e:Event):void
    {
    if(tx < 0){
    e.currentTarget.x -= speed;
    e.currentTarget.gotoAndStop('left');
    }else if(tx > 0){
    e.currentTarget.x += speed;
    e.currentTarget.gotoAndStop(’right’);
    }else{
    e.currentTarget.x += 0;
    }
    }

    acc.addEventListener(AccelerometerEvent.UPDATE, update);
    circle.addEventListener(Event.ENTER_FRAME, loop);
  5. You can test this swf file using Adobe Device Central or you can test direct in to your device like Nokia phone, Android phone, PlayBook and iPhone. Ofcourse you need to package it into .sis (Nokia), .apk (Android), .ipa (iPhone), .bar (PlayBook).

    Device Central

    Accelerometer ActionScript 3 Tutorial