Javascript 弹跳物理html 5帆布平台风格游戏

Javascript 弹跳物理html 5帆布平台风格游戏,javascript,html,css,html5-canvas,Javascript,Html,Css,Html5 Canvas,我正在创建一个平台式游戏,并设置了一些物理。我希望这样,当玩家跳跃和跌倒时,它会反弹并停下来。拜托,有人能帮忙吗?谢谢 指向我的代码的JSFIDLE链接: html: <html> <body> <canvas id="c" width="400" height="200"></canvas> </body> </html> javascript: var fps, canvas, context, control

我正在创建一个平台式游戏,并设置了一些物理。我希望这样,当玩家跳跃和跌倒时,它会反弹并停下来。拜托,有人能帮忙吗?谢谢 指向我的代码的JSFIDLE链接:

html:

<html>

<body>
 <canvas id="c" width="400" height="200"></canvas>
</body>

</html>
javascript:

 var fps, canvas, context, controller, gamePiece, gameEnemy, loop;

fps = 60;

canvas = document.getElementById("c");

context = canvas.getContext("2d");

controller = {

  left: false,
  right: false,
  up: false,
  keyListener: function(event) {

    var key_state = (event.type == "keydown") ? true : false;

    switch (event.keyCode) {

      case 37: // left key
        controller.left = key_state;
        break;
      case 38: // up key
        controller.up = key_state;
        break;
      case 39: // right key
        controller.right = key_state;
        break;

    }

  }

};

gamePiece = {
  x: canvas.width / 2,
  y: canvas.height / 2,
  w: 10,
  h: 10,
  yVel: 0,
  xVel: 0,
  jumping: false,
}

gameEnemy = {

}

loop = function() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  draw();
  move();
  collision();
  if (controller.up && gamePiece.jumping == false) {
    gamePiece.yVel -= 15;
    gamePiece.jumping = true;

  }
  if (controller.left) {
    gamePiece.xVel -= 0.5;
  }
  if(controller.right) {
    gamePiece.xVel += 0.5;
  }
}

function draw() {
  context.fillStyle = "#afeeee"
  context.fillRect(gamePiece.x, gamePiece.y, gamePiece.w, gamePiece.h);
  context.strokeStyle = "#f08080";
  context.beginPath();
  context.moveTo(0, canvas.height - 16);
  context.lineTo(canvas.width, canvas.height - 16);
  context.stroke();
}

function move() {
  gamePiece.yVel += 1.5;
  gamePiece.y += gamePiece.yVel;
  gamePiece.x += gamePiece.xVel;
  gamePiece.xVel *= 0.9;
  gamePiece.yVel *= 0.9;
}

function collision() {
  if (gamePiece.y > canvas.height - 16 - gamePiece.h) {
    gamePiece.y = canvas.height - 16 - gamePiece.h;
    gamePiece.yVel = 0;
    gamePiece.jumping = false;
  }
}

window.setInterval(loop, 1000 / fps);
window.addEventListener("keydown", controller.keyListener)
window.addEventListener("keyup", controller.keyListener);
在函数collision()中,而不是执行

 gamePiece.yVel = 0;
你可以

gamePiece.yVel = -gamePiece.yVel;
如果它太有弹性,乘以阻尼值

var yDamp = 0.5;
gamePiece.yVel = -gamePiece.yVel * yDamp;
最后,防止弹跳时跳跃

gamePiece.jumping = gamePiece.yVel > 1;

另外,如果你能以任何方式改进我的代码,请让我知道我很久以前写过这个答案,它有一个完整的弹跳球代码,看看它是否有帮助。。。此外,这里可能有更多的答案,以便您可以利用。我已经检查了所有地方,找不到答案,以便帮助我。我会检查链接。感谢这没有帮助,因为我希望它在1或2次反弹后停止计数反弹,并在需要时将速度设置为零。
gamePiece.jumping = gamePiece.yVel > 1;