AS3平稳跳跃

时间:2014-08-11 15:31:58

标签: actionscript-3 flash smooth

我想知道如何在游戏中顺利跳跃。它是一个2D游戏,代码非常简单,但我想知道如何让它在达到最大高度然后平滑下降时减慢速度。

这就是我跳跃的全部内容:

Player.y -= 50;

2 个答案:

答案 0 :(得分:1)

你最好的选择是使用物理引擎(Box2d等)。如果你不想要一个开销(如果你唯一使用它的是跳跃而不是碰撞)那么你只需要为你的逻辑添加一些摩擦。

var friction :Number = .85; //how fast to slow down / speed up - the lower the number the quicker (must be less than 1, and more than 0 to work properly)
var velocity :Number = 50;  //how much to move every increment, reset every jump to default value
var direction   :int = -1;  //reset this to -1 every time the jump starts

function jumpLoop(){ //lets assume this is running every frame while jumping 
    player.y += velocity * direction; //take the current velocity, and apply it in the current direction
    if(direction < 0){
        velocity *= friction; //reduce velocity as player ascends
    }else{
        velocity *= 1 + (1 - friction); //increase velocity now that player is falling
    }

    if(velocity < 1) direction = 1; //if player is moving less than 1 pixel now, change direction
    if(player.y > stage.stageHeight - player.height){  //stage.stageheight being wherever your floor is
        player.y = stage.stageHeight - player.height; //put player on the floor exactly
        //jump is over, stop the jumpLoop
    }
}

答案 1 :(得分:0)

复制/粘贴以下代码... jump()可以替换为jump2()(没有弹跳效果)。跳跃将由空格键产生:

const FA:Number = .99; // air resistance
const CR_BM:Number = .8; // bouncing coefficient
const µ:Number = .03; // floor friction
const LB:int = stage.stageHeight; // floor (bottom limit)
const G:int = 2.5; // gravity
const R:int = 50;

var ball:MovieClip = new MovieClip();
this.addChild(ball);
var ba:* = ball.graphics;

ba.beginFill(0xFFCC00);
ba.lineStyle(0, 0x666666);
ba.drawCircle(0, 0, R);
ba.endFill();

ball.vx = 2;
ball.vy = -30;
ball.r = R;
ball.x = 100;
ball.y = LB - R;

stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);

function myKeyDown(e:KeyboardEvent):void {
    if (e.keyCode == Keyboard.SPACE) {
        ball.vy = -30;
        addEventListener(Event.ENTER_FRAME, jump);
    }
}

function jump(e:Event):void {
        ball.vy = ball.vy + G;
        ball.vx *= FA;
        ball.vy *= FA;
        ball.x += ball.vx;
        ball.y += ball.vy;
        if (ball.y > LB - ball.r) {
            ball.y = LB - ball.r;
            ball.vy = -1 * ball.vy * CR_BM;
            ball.vx += ball.vx * - µ;
        }
}

/*
function jump2(e:Event):void {
        ball.vy = ball.vy + G;
        ball.vx *= FA;
        ball.vy *= FA;
        ball.x += ball.vx;
        ball.y += ball.vy;
        if (ball.y > LB - ball.r) {
            ball.y = LB - ball.r;
        }
}
*/