我想使用箭头键使角色移动,但是它不起作用,我也不知道为什么。
这是我要制作的离线射击游戏。我尝试过不使用对象,但是很快它将成为多人游戏,所以我不想不断制作新文件。
这是我的代码:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
var x = 0;
var y = 0;
var Keys = {
up: false,
down: false,
left: false,
right: false
};
img.src = "images/char1.png";
let player = function player(x, y) {
this.x = x;
this.y = y;
this.speed = 5;
this.health = 100;
};
window.onkeydown = function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) {
Keys.left = true;
} else if (kc === 38) {
Keys.up = true;
} else if (kc === 39) {
Keys.right = true;
} else if (kc === 40) {
Keys.down = true;
}
};
window.onkeyup = function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) {
Keys.left = false;
} else if (kc === 38) {
Keys.up = false;
} else if (kc === 39) {
Keys.right = false;
} else if (kc === 40) {
Keys.down = false;
}
};
function move() {
if (Keys.left) {
x -= player.speed;
}else if (Keys.right) {
x += player.speed;
}else if (Keys.up) {
y -= player.speed;
}else if (Keys.down) {
y += player.speed;
}
}
function renderObject() {
ctx.drawImage(img, 0, 0, 32, 48, 0, 0, 32, 48);
}
function draw() {
renderObject();
move();
}
setInterval(draw, 10);
我希望当我按箭头键时角色会移动,但根本不会移动。
答案 0 :(得分:1)
您遇到了一些问题:
您需要创建一个播放器对象。目前,您的player
函数仅仅是player
的“模板”。相反,您需要创建此对象的实例。
var player = new Player(x, y);
每次重新绘制后,您都需要清理画布,否则,您会得到一些人物角色的图像:
ctx.clearRect(0, 0, canvas.width, canvas.height);
在播放器的位置而不是每次0, 0
处绘制播放器图像:
ctx.drawImage(img, x, y, 32, 48);
请参见下面的工作示例:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
var x = 0;
var y = 0;
var player = new Player(x, y);
var Keys = {
up: false,
down: false,
left: false,
right: false
};
img.src = "https://www.pinclipart.com/picdir/middle/366-3665375_deadpool-2d-video-game-characters-clipart.png";
function Player(x, y) {
this.x = x;
this.y = y;
this.speed = 5;
this.health = 100;
};
window.onkeydown = function(e) {
var kc = e.keyCode;
if (kc === 37) {
Keys.left = true;
} else if (kc === 38) {
Keys.up = true;
} else if (kc === 39) {
Keys.right = true;
} else if (kc === 40) {
Keys.down = true;
}
};
window.onkeyup = function(e) {
var kc = e.keyCode;
if (kc === 37) {
Keys.left = false;
} else if (kc === 38) {
Keys.up = false;
} else if (kc === 39) {
Keys.right = false;
} else if (kc === 40) {
Keys.down = false;
}
};
function move() {
if (Keys.left) {
x -= player.speed;
} else if (Keys.right) {
x += player.speed;
} else if (Keys.up) {
y -= player.speed;
} else if (Keys.down) {
y += player.speed;
}
}
function renderObject() {
ctx.drawImage(img, x, y, 32, 48);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
renderObject();
move();
}
setInterval(draw, 10);
<canvas height="120" width="400" id="canvas" style="border: 1px solid black;"></canvas>