Игра JS Canvas с использованием события нажатия клавиши для изменения скорости при удержании кнопки Shift - PullRequest
0 голосов
/ 22 января 2019

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

Любые предложения / помощь будет принята с благодарностью!

              var myGameArea = {
              canvas : document.createElement("canvas"),
              start : function() {
              this.canvas.width = 540;
              this.canvas.height = 330;
              this.context = this.canvas.getContext("2d");




      document.body.appendChild(this.canvas,document.body.childNodes[0]);
          this.canvas.setAttribute("id", "myCanvas");
          this.canvas.hidden = true;


    this.interval = setInterval(updateGameArea, 1000/FPS);
    window.addEventListener('keydown', function (e) {
        myGameArea.keys = (myGameArea.keys || []);
        myGameArea.keys[e.keyCode] = (e.type == "keydown");
    })
    window.addEventListener('keyup', function (e) {
        myGameArea.keys[e.keyCode] = (e.type == "keydown");            
    })
}, 
clear : function(){
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
      }
 }

function component(width, height, color, x, y) {
this.gamearea = myGameArea;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;    
this.x = x;
this.y = y;    
this.update = function() {
    ctx = myGameArea.context;
    ctx.fillStyle = color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
    this.x += this.speedX;
    this.y += this.speedY;        
}
}

function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;





if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -10; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 10; }
if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -10; }
if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 10; }


if (myGameArea.keys && myGameArea.keys[65]) {myGamePiece.speedX = -10; }
if (myGameArea.keys && myGameArea.keys[68]) {myGamePiece.speedX = 10; }
if (myGameArea.keys && myGameArea.keys[87]) {myGamePiece.speedY = -10; }
if (myGameArea.keys && myGameArea.keys[83]) {myGamePiece.speedY = 10; }

    //What do I need to do to get the following function to execute? (NOTE 
   //THIS WAS MOVED TO AFTER IF STATEMENTS PER COMMENT BELOW, THIS DID NOT 
    /////FIX the ISSUE)
GetShiftState(e);

myGamePiece.newPos();    
myGamePiece.update();
}


//Below is the get shift key function I cannot get to work. 
//What I am trying to do is increase the speed of the gamepiece moving 
//when holding shift + the directional arrow

    function GetShiftState (e) {
            if (e.shiftKey) {
    switch(e.which) {
        case 37:
            console.log("shift + left arrow");
          myGamePiece.speedX = -20; 
            break;
        case 38:
            console.log("shift + up arrow");
    myGamePiece.speedY = -20; 
            break;
        case 39:
            console.log("shift + right arrow");
    myGamePiece.speedX = 20;
            break;
        case 40:
            console.log("shift + down arrow");
    myGamePiece.speedY = 20;
            break;
        default:
            break;
       }
   }
        else {
            console.log("Shift key is up.");
        }
    }

Ответы [ 2 ]

0 голосов
/ 24 января 2019

Ниже приведен фрагмент кода, который я написал для перемещения div по экрану.Принцип тот же, хотя, обратите внимание, что у нас есть переменная step, и мы корректируем ее, если event.shiftKey равно true.Полный код можно посмотреть / разветвить здесь: https://repl.it/@PaulThomas1/MoveDivAroundTheScreen

var step = 10;

if (event.shiftKey) step = step * 2;

switch (key) {
  case "ArrowUp":
    event.preventDefault();
    box.style.top = (top - step) + "px";
    break;
  case "ArrowDown":
    event.preventDefault();
    box.style.top = (top + step) + "px";
    break;
  case "ArrowLeft":
    box.style.left = (left - step) + "px";
    break;
  case "ArrowRight":
    box.style.left = (left + step) + "px";
    break;
}
0 голосов
/ 22 января 2019

После вызова метода вы сбрасываете myGamePiece.speed до 10.
Переместите вызов функции на после окончания операторов if.

...