0

I'd like someone to help me convert this code from using a keyboard to using an android device accelerometer. So if the device is tilted to Y axis the application should respond back making the object move forward and if the device is tilted to X axis or -X axis the application should rotate the object to left or right.

Can anyone help?

My code:

package com.asgamer.directionalmovement
{

import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import com.senocular.utils.KeyObject;
import flash.ui.Keyboard;

public class Ship extends MovieClip
{

    private var key:KeyObject;
    private var speed:Number = 0.3;
    private var rotateSpeed:Number = 5;
    private var vx:Number = 0;
    private var vy:Number = 0;
    private var friction:Number = 0.95;

    public function Ship () : void
    {
        key = new KeyObject(stage);
        addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
    }

    public function loop(e:Event) : void
    {

        if (key.isDown(Keyboard.UP))
        {
            vy += Math.sin(degreesToRadians(rotation)) * speed;
            vx += Math.cos(degreesToRadians(rotation)) * speed;
        } else {
            vy *= friction;
            vx *= friction;
        }

        if (key.isDown(Keyboard.RIGHT))
            rotation += rotateSpeed;
        else if (key.isDown(Keyboard.LEFT))
            rotation -= rotateSpeed;

        if (key.isDown(Keyboard.SPACE))
            stage.addChild(new Laser(x, y, rotation));

        y += vy;
        x += vx;

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

        if (y > stage.stageHeight)
            y = 0;
        else if (y < 0)
            y = stage.stageHeight;
    }

    public function degreesToRadians(degrees:Number) : Number
    {
        return degrees * Math.PI / 180;
    }

}

}

4

2 回答 2

0

您可以使用 e.accelerationX,e.accelerationY 和 e.accelerationX :

import flash.sensors.Accelerometer; 
import flash.events.AccelerometerEvent;
var my_acc:Accelerometer
if(Accelerometer.isSupported)
  initAcc();
else
trace("Accelerometer is not Supported")

function initAcc():void
{
var my_acc:Accelerometer = new Accelerometer();
//setting the update interval
my_acc.setRequestedUpdateInterval(50);

//catch the update event
my_acc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);

}
function onAccUpdate(e:AccelerometerEvent):void{
//you can use the e.accelerationX,e.accelerationY AND e.accelerationX

myObject.x -= (e.accelerationX*10);
myObject.y += (e.accelerationY*10); 

}
于 2013-04-04T18:17:48.863 回答
0

您可以使用 dispatchEvent 方法,编辑 Event 的属性,例如类型和加速度。我没有安卓设备,所以不能说下面的代码会 100% 工作。

var ev:AccelerometerEvent = new AccelerometerEvent(AccelerometerEvent.UPDATE);
ev.accelerationX = yourKeyboardAccelerationX;
ev.accelerationX = yourKeyboardAccelerationY;
dispatchEvent(ev);
于 2013-04-04T10:25:57.207 回答