我正在构建一个小游戏来学习HTML5画布,我遇到了一个涉及同时触发多个事件的问题。
我有一个矩形物体,可以上下移动,然后拍摄。问题是,当您按空格键进行拍摄(向上或向下箭头)时,对象将停止移动。如何在按空格键的同时让它继续移动?
let canvas = document.querySelector(`canvas`),
ctx = canvas.getContext(`2d`),
body = document.querySelector(`body`)
let shooter = {
y: canvas.height / 2 - 25,
height: 50,
width: 20,
shots: [],
draw_shooter() {
ctx.strokeRect(5, this.y, this.width, this.height)
},
move_shooter(e) {
if (e.code === "ArrowUp")
if (this.y - 6 > 0) this.y -= 6;
if (e.code === "ArrowDown")
if (this.y + this.height + 6 < canvas.height) this.y += 6;
},
shoot() {
let shot = {
x: 30,
y: this.y + 20,
draw() {
//check if more, then kill in array
ctx.strokeRect(this.x, this.y, 20, 10)
this.x += 5;
}
}
this.shots.push(shot)
}
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
shooter.draw_shooter()
shooter.shots.map((shot) => shot.draw())
requestAnimationFrame(update)
}
update()
body.addEventListener(`keydown`, (e) => shooter.move_shooter(e))
body.addEventListener(`keypress`, (e) => shooter.shoot(e))
&#13;
<canvas width="500" height="200" style="border:1px solid black"></canvas>
&#13;
答案 0 :(得分:0)
另一种方法是记录按下的按键并根据当前按下的按键在update
上移动射手:
let canvas = document.querySelector(`canvas`),
ctx = canvas.getContext(`2d`),
body = document.body;
let shooter = {
y: canvas.height / 2 - 25,
height: 50,
width: 20,
// Pressed keys will be stored here
pressed_keys: [],
shots: [],
draw_shooter() {
ctx.strokeRect(5, this.y, this.width, this.height);
},
move_shooter() {
const up = this.pressed_keys.includes("ArrowUp"),
down = this.pressed_keys.includes("ArrowDown");
// If both keys are pressed, do nothing
if (up && down) { return; }
if (up) { this.y = Math.max(0, this.y - 2); }
if (down) { this.y = Math.min(canvas.height, this.y + 2); }
},
// Add key to the Array
on_key_down(e) {
this.pressed_keys.push(e.code);
},
// Remove key from the Array
on_key_up(e) {
this.pressed_keys = this.pressed_keys.filter(k => k !== e.code);
},
shoot() {
let shot = {
x: 30,
y: this.y + 20,
draw() {
//check if more, then kill in array
ctx.strokeRect(this.x, this.y, 20, 10);
this.x += 5;
}
}
this.shots.push(shot);
}
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
shooter.draw_shooter();
shooter.shots.map((shot) => shot.draw());
// Move shooter
shooter.move_shooter();
requestAnimationFrame(update);
}
update();
body.addEventListener(`keydown`, (e) => shooter.on_key_down(e));
body.addEventListener(`keyup`, (e) => shooter.on_key_up(e));
body.addEventListener(`keypress`, (e) => shooter.shoot(e));
<canvas width="500" height="200" style="border:1px solid black"></canvas>