我正在尝试编写一个播放器对象,该对象使用 WASD 执行在画布上移动但不移动的简单任务



即使一切乍一看似乎都很好,但当我实际按下 WASD 时,它不会移动。我试图弄清楚我是否应该将"e"作为某个参数传递给对象或以某种方式调用它,但我不确定出了什么问题。我也知道这是实现 WASD 运动的糟糕方法,我保证我会研究做得更好,但首先我想在分支之前设法实现一个对象。

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const image = document.getElementById('player');
function Player() {
this.location = {w: 200, h: 200, x: 20, y: 200, speed: 5, dx: 0, dy: 0};
this.drawPlayer = function() {
ctx.drawImage(image, this.location.x, this.location.y, this.location.w, this.location.h);
}
this.clear = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
this.newPos = function() {
this.location.x += this.location.dx;
this.location.y += this.location.dy; 
this.detectWalls();
}
this.detectWalls = function() {
if(this.location.x < 0) {
this.location.x = 0;
}
if(this.location.x + this.location.w > canvas.width) {
this.location.x = canvas.width - this.location.w;
}
if(this.location.y < 0) {
this.location.y = 0;
}
if(this.location.y + this.location.h > canvas.height) {
this.location.y = canvas.height - this.location.h;
}
}
this.moveUp = function() {
this.location.dy = -this.location.speed;
}
this.moveDown = function() {
this.location.dy = this.location.speed;
}
this.moveRight = function() {
this.location.dx = this.location.speed;
}
this.moveLeft = function() {
this.location.dx = -this.location.speed;
}
this.keyDown = function(e) {
if (e.key === 'd') {
this.moveRight();
} else if (e.key === 'a') {
this.moveLeft();
} else if (e.key === 'w') {
this.moveUp();
} else if (e.key === 's') {
this.moveDown();
}
}
this.keyUp = function(e) {
if (
e.key == 'd' ||
e.key == 'a' ||
e.key == 'w' ||
e.key == 's'
) {
this.location.dx = 0;
this.location.dx = 0;
}
}
}
let player = new Player();
function update() {
player.clear();
player.drawPlayer();
player.newPos();
requestAnimationFrame(update);
}
update();
document.addEventListener('keydown', keyDown);
document.addEventListener('keyup', keyUp);

这里从实际移动播放器的东西开始,然后尽可能复杂地使其复杂化

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
var image = new Image();
image.src="https://i.stack.imgur.com/UFBxY.png"
image.onload = update;
function Player() {
this.location = { w: 80, h: 100, x: 50, y: 10, speed: 5 };
this.drawPlayer = function() {    
ctx.drawImage(image, this.location.x, this.location.y, this.location.w, this.location.h);
}
this.clear = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}  
}
let player = new Player();
function update() {
player.clear();
player.drawPlayer();
requestAnimationFrame(update);     
}
document.addEventListener("keydown", function(e) {
if (e.key === 'd') {
player.location.x += player.location.speed;
} else if (e.key === 'a') {
player.location.x += -player.location.speed;
}    
});
<canvas id="canvas"></canvas>

如您所见,我删除了很多代码只是为了专注于使用键移动播放器的问题,您在提问时也应该这样做,只需保持您的代码示例非常小,这样其他人更容易开始故障排除。

相关内容

  • 没有找到相关文章

最新更新