0

I'm just trying to animate a jump in canvas, but I don't think I got the math formula properly, instead of doing a sine wave kind of motion, it just instantly telports, with no animation, any help would be great thanks.

var ctx = new CtxScene(500, 500, '1px solid black').create()
  , player = {
    x: 0,
        y: 0,
        moving: false,
        dir: undefined
  };



var i = 0;
(function draw() {
    setTimeout(function() {  
    requestAnimationFrame(draw);
        checkDir();
        update();
    }, 1000 / 60);
})();

document.onkeydown = function(e) {
    if (e.which === 37) {
        player.moving = true;
        player.dir = 'left';
    } 
    if (e.which === 39) {
        player.moving = true;
        player.dir = 'right';
    }
    if (e.which === 38) {
        player.moving = true;
        player.dir = 'up';
    }
    if (e.which === 40) {
        player.moving = true;
        player.dir = 'down';
    }
    if (e.which === 32) {
        player.moving = true;
        player.dir = 'jump';
    }
   console.log(e.which);    
}

document.onkeyup = function(e) {
    player.moving = false;
}

function update() {
    ctx.clearRect(0, 0, 500, 500);
    ctx.fillStyle = '#00A';
    ctx.fillRect(player.x, player.y, 100, 100)
}

function checkDir() {

    if (player.moving) {

        if (player.dir === 'left') {
            player.x  -=5;
        } else if (player.dir === 'right') {
            player.x += 5;
        } else if (player.dir === 'up') {
            player.y -= 5;
        } else if (player.dir === 'down') {
            player.y += 5;
        } else if (player.dir === 'jump') {
            player.y = 100 * Math.sin(5*Math.PI/200);
        }
    }

}

the math is a few lines from the bottom (I'm almost 100% sure it's wrong)

4

1 回答 1

1

好的,所以最简单的方法是使用物理学,非常非常基础的物理学。给你的角色一个重力和至少一个 Y 方向的速度,类似于:

player.gravity= 0.92;

var characterUpdate= function(){
    player.y+=player.velocityY;
    player.velocityY+=player.gravity;
}

这将导致玩家不断想要向下(重力),并且您增加速度 Y 以在跳跃期间抵消这种情况。您需要设置一些界限以避免角色暂时离开屏幕,例如:

if (player.y+player.height >= ctx.height) {
    player.y=ctx.height-player.height;
}

这种方法的另一个好处是它可以解决您可能计划在以后包括的任何跌倒。

于 2013-07-24T18:54:24.323 回答