如何在闪光灯的旋转方向上移动物体?

时间:2016-04-04 10:23:20

标签: actionscript-3 flash

我有一辆“车”,必须沿着它旋转的方向移动。 现在它只是向一个方向旋转并继续上下。请帮助我。 我正在使用adobe flash pro cs6和actionscript3。 我的代码是:

var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;

car.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);

function fl_MoveInDirectionOfKey(event:Event)
{
    if (upPressed)
    {
        car.y += 5;
    }
    if (downPressed)
    {
        car.y -= 5;
    }
    if (rightPressed)
    {
        car.rotation += 5;
    }
    if (leftPressed)
    {
        car.rotation -= 5;
    }
}

function fl_SetKeyPressed(event:KeyboardEvent):void
{
    switch (event.keyCode)
    {
        case Keyboard.UP:
        {
            upPressed = true;
            break;
        }
        case Keyboard.DOWN:
        {
            downPressed = true;
            break;
        }
        case Keyboard.LEFT:
        {
            leftPressed = true;
            break;
        }
        case Keyboard.RIGHT:
        {
            rightPressed = true;
            break;
        }
    }
}

function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
    switch (event.keyCode)
    {
        case Keyboard.UP:
        {
            upPressed = false;
            break;
        }
        case Keyboard.DOWN:
        {
            downPressed = false;
            break;
        }
        case Keyboard.LEFT:
        {
            leftPressed = false;
            break;
        }
        case Keyboard.RIGHT:
        {
            rightPressed = false;
            break;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您需要使用vector math根据角度和距离移动汽车的x,y

例如,您可以根据角度和速度移动汽车:

function move(degrees:Number, speed:Number):void {
    var radians:Number = degrees * (Math.PI / 180);
    car.x += Math.cos(radians) * speed;
    car.y += Math.sin(radians) * speed;
}

然后你可以使用汽车的rotation作为角度,5-5作为速度:

if (upPressed) {
    move(car.rotation, 5);
}
if (downPressed) {
    move(car.rotation, -5);
}

请注意,这假设rotation=0表示您的汽车正对着右侧。如果您的汽车朝向不同的方向,您需要补偿您驾驶汽车的角度,例如,如果汽车朝上,您需要使用move(car.rotation - 90, 5)