在ActionScript中简单的船

时间:2011-04-26 15:24:13

标签: flash actionscript

我正在使用Actionscript创建一个简单的可控船,并让它前进,左右转动,但不能让它转过来。我希望船朝着它指向的方向前进。

function moveBoat(event:Event):void
{
    if(rightKeyIsDown)
    {
        player_mc.x += speed;
        player_mc.rotationZ += speed;
    }
    if(leftKeyIsDown)
    {
        player_mc.x -= speed;
        player_mc.rotationZ -= speed;

    }
    if(upKeyIsDown)
    {
        player_mc.y -= speed;
    }
}

提前感谢任何可以告诉我我做错了什么的人。

修改

function moveBoat(event:Event):void
{
    if(rightKeyIsDown)
    {
        player_mc.rotationZ += turnFactor;
    }
    if(leftKeyIsDown)
    {
        player_mc.rotationZ -= turnFactor;
    }
    if(upKeyIsDown)
    {
        player_mc.x += speed * Math.cos(player_mc.rotationZ * Math.PI / 180);
        player_mc.y -= speed * Math.sin(player_mc.rotationZ * Math.PI / 180);
    }
}

修改

function moveBoat(event:Event):void
{
    if(rightKeyIsDown)
    {
        player_mc.rotation += turnFactor;
    }
    if(leftKeyIsDown)
    {
        player_mc.rotation -= turnFactor;
    }
    if( upKeyIsDown )
    {
        // convert our rotation to radians first
        var rads:Number = player_mc.rotation * ( Math.PI / 180.0 );
        player_mc.x += speed * Math.cos( rads );
        player_mc.y += speed * Math.sin( rads );
    }
}

3 个答案:

答案 0 :(得分:1)

尝试类似:

function moveBoat(event:Event):void
{
    if(rightKeyIsDown)
    {
        player_mc.rotationZ -= turnFactor;
    }
    if(leftKeyIsDown)
    {
        player_mc.rotationZ += turnFactor;
    }
    if(upKeyIsDown)
    {
        player_mc.x += speed * Math.cos(player_mc.rotationZ * Math.PI / 180);
        player_mc.y -= speed * Math.sin(player_mc.rotationZ * Math.PI / 180);
    }
}

我现在无法测试代码,但这应该足以解释这个想法。我正在做的不同的是使用左和右键来操纵船(通过改变它的角度)并在点击向上键时沿着它指向的方向移动它。

移动船只时,您不能简单地在X和Y轴上移动一定量,您还需要考虑船舶的方向。为此,请使用正弦和余弦函数。

答案 1 :(得分:0)

使用一些简单的三角法来计算在X轴和Y轴上移动物体的程度。创建一个直角三角形,其中船是A点,速度是h,船的方向是角度A:

right triangle

现在使用正弦和余弦来计算边a和b的长度。这就是在X轴和Y轴上移动的距离。

答案 2 :(得分:-1)

TokPhobia几乎没错了

private function _moveBoat(event:Event):void
{
    if( rightKeyIsDown )
        this.m_player.rotation += turnFactor;

    if ( leftKeyIsDown )
        this.m_player.rotation -= turnFactor;

    if( upKeyIsDown )
    {
        // convert our rotation to radians first
        var rads:Number = this.m_player.rotation * ( Math.PI / 180.0 );
        this.m_player.x += speed * Math.cos( rads );
        this.m_player.y += speed * Math.sin( rads );
    }
}

顺便说一句,除非你在3D中这样做,rotation属性才能正常工作,你不需要使用rotationZ