0
저는 HTML5 캔버스를 배우기 위해 작은 게임을 만들었고 동시에 여러 이벤트를 트리거하는 문제를 발견했습니다.canvas, shoot while while shoot
나는 위아래로 움직이고 촬영할 수있는 사각형 개체가 있습니다. 문제는 스페이스 바를 눌렀을 때 (위쪽 또는 아래쪽 화살표를 누르고있는 동안) 촬영을 멈추는 것입니다. 스페이스 바를 누른 상태에서 계속 움직이게 할 수 있습니까?
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))
<canvas width="500" height="200" style="border:1px solid black"></canvas>
HTML과 CSS도 함께 제공해 주시면 좋을 것입니다. 전체 게임을 제작합니다. – Taurus