Какой код я могу добавить к этому, чтобы заставить это изображение вращаться, когда левая или правая клавиши нажаты? - PullRequest
0 голосов
/ 08 января 2019

Я хочу, чтобы мой «GamePiece» вращался в центральной точке, когда я нажимаю левую или правую кнопку на клавиатуре. Я учусь и изучаю javascript в школе. Я просмотрел похожие статьи, но нашел их действительно запутанными. Я, вероятно, не собираюсь отвечать в течение следующих 18 часов, так как я пишу это ночью.

JavaScript:

var myGamePiece;
var myBackground;


function startGame() {
    myGameArea.start();
    myGamePiece = new component(30, 30, "GamePiece.png", 10, 500, "image");
    myBackground = new component(656, 270, "PLACE IMAGE HERE", 0, 0, "image");
    var button = document.getElementById("Play");
    button.style.display = "none";  
}

var myGameArea = {
    canvas : document.getElementById("myCanvas"),
    start : function() {
        this.canvas.width = 1300;
        this.canvas.height = 600;
        this.canvas.style.position = "absolute";
        this.canvas.style.top = "267px";
        this.canvas.style.left = "303px";
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.interval = setInterval(updateGameArea, 20);
        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, type) {
    this.type = type;
    if (type === "image") {
        this.image = new Image();
        this.image.src = color;
    }
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;    
    this.x = x;
    this.y = y;    
    this.update = function() {
        context = myGameArea.context;
        if (type === "image") {
            context.drawImage(this.image, 
                this.x, 
                this.y,
                this.width, this.height);
        } else {
            context.fillStyle = color;
            context.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 = -1; }
    if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 1; }
    if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -1; }
    if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 1; }
    myGamePiece.newPos();    
    myGamePiece.update();
    myBackground.newPos();
    myBackground.update();
}  

Я хочу, чтобы круглое изображение ("GamePiece") вращалось от его центра при нажатии клавиши.

Извините, я не был ясен Я хочу, чтобы шар вращался, как будто он катится по земле. Это 2d платформа. Мне нравится Я хочу, чтобы мяч катился, пока я держу кнопку

Ответы [ 2 ]

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

Вам просто нужно использовать addEventListener для прослушивания keydown событий на document. Если событие keydown сработало, ваш обработчик события должен проверить, была ли нажатая клавиша кнопкой со стрелкой вправо - этого можно достичь, открыв e.keyCode и проверив, что оно равно 39 - если оно установлено, установите images style.transform свойство, чтобы заставить его вращаться.

e - это аргумент, который передается вашему обработчику событий (браузер позаботится о том, чтобы передать вам e) - он содержит множество метаданных о событии, которое вы слушаете.

Ниже приведен пример того, что я описал выше:

const imgEl = document.querySelector('#imgEl');
let offset = 0;

document.addEventListener('keydown', function(e) {
  if (e.keyCode === 39) {
    offset += 90;
    if (offset === 360) {
      offset = 0;
    }
    rotate(imgEl, offset);
  } else if (e.keyCode === 37) {
    offset -= 90;
    if (offset === -360) {
      offset = 0;
    }
    rotate(imgEl, offset);
  }
});

function rotate(el, degrees) {
  // Code for Safari
  el.style.WebkitTransform = `rotate(${degrees}deg)`;
  // Code for IE9
  el.style.msTransform = `rotate(${degrees}deg)`;
  // Standard syntax
  el.style.transform = `rotate(${degrees}deg)`;
}
<img id="imgEl" src="https://static-s.aa-cdn.net/img/ios/1037581527/890273ca9f97b338cd84ab01f7549bc2?v=1">
0 голосов
/ 08 января 2019

Если вы думаете о холсте как о листе бумаги, который может двигаться, но ваша ручка неподвижна, вам будет проще представить, как может работать поворот изображения. Вы перемещаете весь холст в точку, где вы хотите повернуть (координаты вашего изображения), вы поворачиваете холст на величину, которую вы хотите повернуть, тянете ручку назад и вверх на половину размера вашего изображения (так что центр находится в точке, которую вы повернули), а затем нарисуйте изображение как обычно. Теперь, когда вы вернете свой холст / бумагу в исходное положение, изображение все равно будет рисоваться на холсте в нужном вам положении и повороте.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

var square1 = {
  x: 50,
  y: 50,
  w: 50,
  h: 25,
  rotation: -25
};
var square2 = {
  x: 150,
  y: 50,
  w: 50,
  h: 50,
  rotation: 45
};

drawSquare(square1);
drawSquare(square2);

function drawSquare(square) {
  ctx.save(); //saves the original state of the canvas
  ctx.translate(square.x, square.y); //moves the canvas to the object's point of origin
  ctx.rotate(square.rotation * Math.PI / 180); //rotates the canvas the desired amount
  ctx.fillRect(-(square.w / 2), -(square.h / 2), square.w, square.h); //draws the object
  ctx.restore(); //restores the canvas to its original position
}
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

Что касается вращения клавиш, оно будет работать так же, как ваше движение. Сохраните значение для каждого объекта для вращения, а затем увеличьте это значение на основе желаемой скорости вращения.

...