Simple Accelerometer Example

I’m adding some custom accelerometer/orientation behavior to the iReverse game I’m working on, so I threw together a simple test app to output accelerometer data. I figured I’d post the code in case anyone else was working on something similar.

Code and screenshot below:

package
{
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.events.AccelerometerEvent;
    import flash.events.Event;
    import flash.sensors.Accelerometer;
    import flash.text.TextField;
    import flash.text.TextFormat;

    public class AccelerometerTest extends Sprite
    {
        private var textFormat:TextFormat;
        private var output:TextField;
        private var accelerometer:Accelerometer;

            public function AccelerometerTest()
            {
                super();
                this.stage.scaleMode = StageScaleMode.NO_SCALE;
                this.stage.align = StageAlign.TOP_LEFT;

                this.textFormat = new TextFormat();
                this.textFormat.color = 0x000000;
                this.textFormat.font = "Helvetica";
                this.textFormat.size = 20;

                this.output = new TextField();
                this.output.defaultTextFormat = this.textFormat;

                this.stage.addEventListener(Event.RESIZE, doLayout);

                this.accelerometer = new Accelerometer();
                accelerometer.addEventListener(AccelerometerEvent.UPDATE, onAccelerometerUpdate);
            }

            private function doLayout(e:Event):void
            {
                this.output.width = this.stage.stageWidth;
                this.output.height = this.stage.stageHeight;
                this.output.x = 0;
                this.output.y = 0;
                this.addChild(this.output);
            }

            private function onAccelerometerUpdate(e:AccelerometerEvent):void
            {
                var str:String = "x: " + e.accelerationX;
                str += "\ny: " + e.accelerationY;
                str += "\nz: " + e.accelerationZ;
                this.output.text = str;
            }
    }
}