Workshop › Zelda-style Dungeon › Step 8 of 22
Space (or a tap away from the pad) swings the sword for 12 frames. The sword is a box in front of the hero, in the direction it faces. While swinging the hero stands still, and holding Space does not swing again and again.
```js
let swing // frames left of the sword swing
swing = 0
if (DIRS[event.key] || event.key === ' ') event.preventDefault()
if (event.key === ' ' && !event.repeat) {
if (swing === 0) swing = 12
}
else if (swing === 0) swing = 12
// The sword: a box from the middle of the player out to 30 pixels in front, so it also hits an enemy right on top of you.
function swordBox() {
const [dx, dy] = player.dir
const cx = player.x + SIZE / 2 + dx * 15
const cy = player.y + SIZE / 2 + dy * 15
const w = dx ? 30 : 8
const h = dy ? 30 : 8
return { x: cx - w / 2, y: cy - h / 2, w, h }
}
if (dir && swing === 0) {
if (swing > 0) swing -= 1
if (swing > 0) {
const s = swordBox()
ctx.fillStyle = '#e5e7eb'
ctx.fillRect(s.x, s.y, s.w, s.h)
}
```event.repeat is true for the automatic repeats of a held key, so only a real press swings.dx ? 30 : 8: facing sideways (dx not 0) the box is wide, otherwise tall.held, write swing; at the top of reset, set it to 0.keydown, keep Space from scrolling and swing on a real press; on a tap away from the pad, swing too.update, write swordBox; walk only when not swinging; count the swing down at the end of update.draw, draw the sword before ctx.restore().Skills: Keyboard and mouse input, Game states