Добавление кнопок в игру на платформе JavaScript

Я сделал игру на платформе javascript, в которой игрок может двигаться влево, вправо или прыгать с помощью клавиш со стрелками на клавиатуре. Я хотел бы быть в состоянии сделать это с помощью кнопок JavaScript, которые я сделал вместо клавиш со стрелками на клавиатуре.

Это мои кнопки JavaScript.

<button id="left" type="button">Left</button>
<button id="up" type="button">Jump</button>
<button id="right" type="button">Right</button> 

Вот мой неотредактированный код JavaScript, который использует его, чтобы персонаж мог прыгать или перемещаться влево или вправо с помощью клавиш со стрелками на клавиатуре.

var playerXSpeed = 7;
var gravity = 30;
var jumpSpeed = 17;


Player.prototype.update = function(time, state, keys) {
  let xSpeed = 0;
  if (keys.ArrowLeft) xSpeed -= playerXSpeed;
  if (keys.ArrowRight) xSpeed += playerXSpeed;
  let pos = this.pos;
  let movedX = pos.plus(new Vec(xSpeed * time, 0));
  if (!state.level.touches(movedX, this.size, "wall")) {
    pos = movedX;
  }

  let ySpeed = this.speed.y + time * gravity;
  let movedY = pos.plus(new Vec(0, ySpeed * time));
  if (!state.level.touches(movedY, this.size, "wall")) {
    pos = movedY;
  } else if (keys.ArrowUp && ySpeed > 0) {
    ySpeed = -jumpSpeed;
  } else {
    ySpeed = 0;
  }
  return new Player(pos, new Vec(xSpeed, ySpeed));
};

Вот часть кода, которая проверяет, находятся ли клавиши со стрелками вверх или вниз. Если клавиши со стрелками вверх, то персонаж не двигается. Если они удерживаются, персонаж продолжает двигаться и не останавливается, пока не отпущены клавиши. Я знаю, что мне нужно сделать что-то еще, чтобы это взаимодействовало с моими кнопками JavaScript, но я не знаю, что делать.

function trackKeys(keys) {
  let down = Object.create(null);
  function track(event) {
    if (keys.includes(event.key)) {
      down[event.key] = event.type == "keydown";
      event.preventDefault();
    }
  }
  window.addEventListener("keydown", track);
  window.addEventListener("keyup", track);
  return down;
}

var arrowKeys =
  trackKeys(["ArrowLeft", "ArrowRight", "ArrowUp"]);

1 ответ

Вы можете довольно легко добавить эти элементы управления, добавив прослушиватели событий к вашим кнопкам. onmousedown & onmouseup События.

Вам также следует избегать создания новых объектов с new в вашем player.update(), поскольку он будет медленным из-за того, что браузер ищет больше памяти и сборщик мусора тратит время на очистку старых объектов.

Ниже приведен фрагмент кода, который должен делать то, что вам нужно.

<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <style>
   body {
    background-color: black;
   }
   
   canvas {
    display: block;
    margin: auto;
    margin-bottom: 15px;
    border: solid 1px white;
    border-radius: 10px;
   }
   
   div {
    display: block;
    margin: auto;
    width: 170px;
    height: 30px;
   }
   
   button {
    width: 75px;
    height: 30px;
    text-align: center;
    font:-style: Lucida Console;
    font-size: 20px;
    border: solid 1px white;
    border-radius: 10px;
    
    color: #FFFFFFFF;
    background-color: #333333FF;
    transition-duration: 0.1s;
   }
   
   button:hover {
    background-color: #777777FF;
   }
   
   button:active {
    background-color: #AAAAAAFF;
   }
   
   .top {
    display: block;
    margin: auto;
    margin-bottom: 10px;
   }
   
   .bottom {
    display: inline-block;
    margin: auto;
    margin-left: 5px;
    margin-right: 1px;
   }
   
  </style>
 </head>
 
 <body>
  <canvas id="canvas"></canvas>
  <button id="jumpButton" class="top">↑</button>
  <div>
   <button id="leftButton" class="bottom">←</button>
   <button id="rightButton" class="bottom">→</button>
  </div>
  <script type="application/javascript">
  
  void function() {
  
   "use strict";
   
   // Variables
   var canvasWidth = 180;
   var canvasHeight = 160;
   var canvas = null;
   var ctx = null;
   var player = null;
   
   var jumpButton = null;
   var leftButton = null;
   var rightButton = null;
   
   // Classes
   function Player(x,y) {
    // Position
    this.x = x || 0.0; // Using || in JS means use this second value if the first is null or undefined
    this.y = y || 0.0;
    
    // Velocity
    this.dx = 0.0;
    this.dy = 0.0;
    
    // Input
    this.isJumping = false; // Extra boolean to stop the player from jumping in mid-air
    this.isJumpDown = false;
    this.isLeftDown = false;
    this.isRightDown = false;
   }
   
   Player.prototype = {
    WIDTH: 10.0,
    HEIGHT: 20.0,
    
    SIDE_SPEED: 1.0,
    JUMP_SPEED: 4.0,
    FALL_SPEED: 0.2,
   
    tick: function() {
     // Input
     if (this.isLeftDown) {
      this.dx = -this.SIDE_SPEED;
     } else if (this.isRightDown) {
      this.dx = +this.SIDE_SPEED;
     } else {
      this.dx = 0.0;
     }
     
     if (this.isJumpDown && !this.isJumping) {
      this.isJumping = true;
      this.dy = -this.JUMP_SPEED;
     }
     
     // Falling
     if (this.isJumping) {
      this.dy += this.FALL_SPEED;
      
      if (this.y + this.dy > canvasHeight - this.HEIGHT) {
       this.y = canvasHeight - this.HEIGHT;
       this.dy = 0.0;
       this.isJumping = false;
      }
     }
     
     // Left/Right boundaries
     if (this.x < -this.WIDTH) {
      this.x = canvasWidth;
     } else if (this.x > canvasWidth) {
      this.x = -this.WIDTH;
     }
    
     this.x += this.dx;
     this.y += this.dy;
    },
    
    render: function(ctx) {
     ctx.strokeStyle = "black";
     ctx.fillStyle = "darkred";
     ctx.beginPath();
     ctx.rect(this.x,this.y,this.WIDTH,this.HEIGHT);
     ctx.fill();
     ctx.stroke();
    }
   };
   
   // Functions
   
   // Button event listeners
   function onJumpDown(e) {
    player.isJumpDown = true;
   }
   
   function onJumpUp(e) {
    player.isJumpDown = false;
   }
   
   function onLeftDown(e) {
    player.isLeftDown = true;
   }
   
   function onLeftUp(e) {
    player.isLeftDown = false;
   }
   
   function onRightDown(e) {
    player.isRightDown = true;
   }
   
   function onRightUp(e) {
    player.isRightDown = false;
   }
   
   // Game loop
   function loop() {
    // Tick
    player.tick();
    
    // Render
    ctx.fillStyle = "gray";
    ctx.fillRect(0,0,canvasWidth,canvasHeight);
    
    player.render(ctx);
    
    //
    requestAnimationFrame(loop);
   }
   
   // Entry point (this function runs first, window.onload)
   onload = function() {
    canvas = document.getElementById("canvas");
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    
    ctx = canvas.getContext("2d");
    
    jumpButton = document.getElementById("jumpButton");
    leftButton = document.getElementById("leftButton");
    rightButton = document.getElementById("rightButton");
    
    jumpButton.onmousedown = onJumpDown;
    jumpButton.onmouseup = onJumpUp;
    
    leftButton.onmousedown = onLeftDown;
    leftButton.onmouseup = onLeftUp;
    
    rightButton.onmousedown = onRightDown;
    rightButton.onmouseup = onRightUp;
    
    player = new Player(85.0,140.0);
    
    loop();
   }
  
  }();
  
  </script>
 </body>
</html>

Другие вопросы по тегам