отскок физики для HTML 5 холст платформер стиль игры - PullRequest
1 голос
/ 29 сентября 2019

Я создаю игру в стиле платформера и настроил немного физики. Я хочу сделать так, чтобы, когда игрок прыгает и падает, он подпрыгивает и останавливается. Пожалуйста, кто-нибудь может помочь? Благодарю. Jsfiddle ссылка на мой код: https://jsfiddle.net/fezzie07/nfbv5oLd/153/#&togetherjs=HH8otvf7hA

html:

<html>

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

</html>

css:

#c {
   background-color: #202020;
   border-style: dashed;
   border-color: black;
   border-width: 1px;
}

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);

1 Ответ

1 голос
/ 29 сентября 2019

В функции collision () вместо выполнения

 gamePiece.yVel = 0;

Вы можете сделать

gamePiece.yVel = -gamePiece.yVel;

Если оно слишком оживленное, умножьте его на значение демпфирования,

var yDamp = 0.5;
gamePiece.yVel = -gamePiece.yVel * yDamp;

Наконец, для предотвращения прыжков при подпрыгивании

gamePiece.jumping = gamePiece.yVel > 1;
...