Ну, я пытаюсь сделать игру, в которой прямоугольник сможет двигаться влево и вправо. Я попробовал этот Eventlistener, но с прямоугольником ничего не происходит. Это просто в середине моей границы, даже если я пытаюсь нажать клавиши со стрелками. < /P>
Вот код: < /p>
Ichi's Game
this is the game
const game = document.getElementById("game");
const context = game.getContext("2d");
const rectWidth = "50";
const rectHeight = "50";
const x = (game.width - rectWidth) / 2;
const y = game.height - rectHeight;
function drawRectangle() {
context.clearRect(0, 0, game.width, game.height); //Clearing the canvas
context.fillStyle = "blue";
context.fillRect(x, y, rectWidth, rectHeight);
}
document.addEventListener("keydown", (event) => {
const speed = 20;
if(event.key === "ArrowLeft" && x > 0){
x -= speed;
}
if(event.key === "ArrowRight" && x + rectWidth < game.width) {
x += speed;
}
drawRectangle();
})
drawRectangle();
< /code>
Я попытался добавить функцию вверх и вниз, но ничего не произошло. Я также пытался изменить скорость, но она ничего не сделала для прямоугольника.
Подробнее здесь: https://stackoverflow.com/questions/796 ... arrow-keys