Я хочу сделать простую игру 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();
Это результат.
Спасибо!
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, и вам придется перерисовать фон.