在javascript中长时间跳跃精灵?

时间:2017-02-03 22:45:56

标签: javascript html physics game-physics

我正在建造一个2d平台游戏,现在我正试图让你的玩家在按住空格键时跳得更长。现在玩家可以上下跳跃,但就像你按住键时机器人独角兽所具有的效果一样。我该怎么做呢?我没有使用移相器或任何东西,我见过的大多数教程都使用它。以下是我的更新方法中的内容:

     var gameEngine = this.game;

if (gameEngine.keyMap["Space"] && !this.jumping) { //only jump if not already in mid jump

    this.jumping = true;
    this.animationCurrent.elapsedTime = 0;
    this.game.space = false;
}

if (this.jumping) {

    if (this.animationCurrent.isDone()) {
        this.animationCurrent.elapsedTime = 0;
        this.jumping = false;
    }

    var jumpDistance = this.animationCurrent.elapsedTime /
        this.animationCurrent.totalTime;

    var totalHeight = 150;

    if (jumpDistance > 0.5)
        jumpDistance = 1 - jumpDistance;
    var height = totalHeight * (-4 * (jumpDistance * jumpDistance - jumpDistance));
    this.y = this.ground - height;
    console.log(this.y);
}

1 个答案:

答案 0 :(得分:1)

你基本上需要实现一个系统,按住跳跃键继续对角色施加逐渐减小的力。

看起来你现在正在将跳跃高度绑定到动画中?出于这个原因并不理想;调整东西变成了球疼。您需要更多基于物理的方法。

信封伪代码的基本背面:

旧式恒定跳跃动作:

const JUMP_STRENGTH = 100;
const GRAVITY = 10;

onJumpKeyupPress(){
    if(play.canJump)
    player.transform.up.velocity = JUMP_STRENGTH;

}

gameTick(){
    if(!player.onGround)
    {
        player.up.velocity -= GRAVITY
        player.y += player.up.velocity;
    }
    else{
        player.up.velocity = 0;
    }
}

正如你所看到的,这会使用重力来加速玩家角色的加班。但是当用户推动跳跃时,所有力都立即被施加

更大的跳跃,同时按住跳键:

const JUMP_STRENGTH = 100;
const GRAVITY = 10;

var jumpStrength = 0;

onJumpKeyupPress(){
    if(play.canJump)
    jumpStrength = JUMP_STRENGTH;
}

gameTick(){
    if(!player.onGround)
    {
        if(jumpKeyIsStillPressed){
            player.up.velocity += jumpStrength;
            jumpStrength /= 2;
        }
        player.up.velocity -= GRAVITY;
        player.y += player.up.velocity;
    }
    else{
        player.up.velocity = 0;
        jumpStrength = 0;
    }
}

通过这个例子,用户得到的初始跳跃强度为100,每次打勾都会减半,直到重力变强。

希望我已经足够清楚了!