如何在as3中获得角色的速度

时间:2013-03-31 17:14:53

标签: actionscript-3

我试图制作一个传送器游戏,我的角色需要有一定的速度和重力,有没有人知道我需要能够实现这一点的总和?

到目前为止,这是我的代码:

var char = this.addChild(new Char());
char.width = 20;
char.height = 20;
char.x = startPos.x;  //startPos is an invisible movieclip that I can move around to     make the starting position
char.y = startPos.y;        // accurate
var vx:Number = 0;
var vt:Number = 0;

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);

function keyDownHandler (e:KeyboardEvent):void {
    switch (e.keyCode)  {
        case Keyboard.UP:
        char.y = char.y - 5   
    }
}

1 个答案:

答案 0 :(得分:1)

如果您的char只需要上升,那么以下代码将完成这项工作。

但如果它需要向所有方向移动,则需要更高级的代码。 关注Moving Character in all directions.

这是满足您需求的快速解决方案。

var gravity:Number = 2;

var velocity:Number = 1.1;

var move:Boolean = false;

function moveChar(e:Event):void
{
   if(move)
   {
       gravity *= velocity; 
       char.y -= gravity; // move char
   }
}
char.addEventListener(Event.ENTER_FRAME, moveChar, false, 0, true);


//Keyboard events
function keyDownHandler (e:KeyboardEvent):void
{
    switch (e.keyCode) 
    {
        case Keyboard.UP:
        move = true;
    }
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);

function keyUpHandler (e:KeyboardEvent):void
{
    move = false;
    gravity = 2;
}
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);