Search code examples
actionscript-3accelerometer

AS3 - Detect moving direction based on accelerometer


The code below moves a movieclip based on the accelerometer. How to detect in which direction it moves or if it stands still?

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

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

 my_acc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);
 function onAccUpdate(e:AccelerometerEvent):void{

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


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


}

Solution

  • You get the real acceleration vector with

    Sqrt(accelerationX^2 + accelerationY^2)
    

    Then, you get the direction in degrees with

    Cos^-1 (accelerationX / realAcceleration)
    

    Try the following:

    var accVector = Math.sqrt(Math.pow(e.accelerationX,2) +
                              Math.pow(e.accelerationY,2))
    
    var direction = Math.acos(e.accelerationX / accVector)
    

    and note that you get direction in radians!

    If you want deegrees: var directionDeg = direction * 180/Math.PI

    If your accelerationY is negative, you need to change the sign of directionDeg and (if you want) add 360 to always get a positive number.