Canvas Rectangle Movement On Keydown

1

Я хочу сделать простую игру Arkanoid с Canvas. Все нормально, но когда я нажимаю левую или правую клавишу, я не знаю, как заставить ее двигаться.

var c = document.getElementById("game");
var ctx = c.getContext("2d");
document.addEventListener("keydown", Keys);
var x = 180;
var rx = 10;

function init() {
    drawBackground("#000000");
    drawPlayer();
}

function drawBackground(color) {
    ctx.fillStyle = color;
    ctx.fillRect(0, 0, 500, 250);
}

function drawPlayer() {
    ctx.fillStyle = "red";
    ctx.fillRect(x, 220, 150, 10);
}

function moveTo(x) {
    ctx.clearRect(x, 220, 150, 10);
}

function Keys(e) {
    switch (e.keyCode) {
        case 37:
            moveTo(x - rx);
            break;
        case 39:
            moveTo(x + rx)
    }
}

init();

Это результат.

Спасибо!

Теги:
canvas

1 ответ

0
Лучший ответ
var c = document.getElementById("game");
var ctx = c.getContext("2d");
document.addEventListener("keydown", Keys);
var x = 180;
var rx = 10;

function init() {
    drawBackground("#000000");
    drawPlayer();
}

function drawBackground(color) {
    ctx.fillStyle = color;
    ctx.fillRect(0, 0, 500, 250);
}

function drawPlayer() {
    ctx.fillStyle = "red";
    ctx.fillRect(x, 220, 150, 10);
}

function moveTo(xP) { // changed parameter name
    x = xP; // update variable x
    init(); // redraw background and player
}

function Keys(e) {
    switch ((e.keyCode || e.which)) { // some browsers use e.which
        case 37:
            moveTo(x - rx);
            break;
        case 39:
            moveTo(x + rx)
    }
}

init();

Это правильный код. Вы должны установить переменную x, и вам придется перерисовать фон.

  • 0
    Ох, спасибо!! : D

Ещё вопросы

Сообщество Overcoder
Наверх
Меню