Workshop › Zelda-style Dungeon › Step 10 of 22
The sword hits an enemy it overlaps: the enemy loses health and is knocked back, sliding 4 pixels a frame for 10 frames in the direction you face. An enemy with no health left is gone.
```js
const overlap = (a, b) => a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y
const box = (body) => ({ x: body.x, y: body.y, w: SIZE, h: SIZE })
const sword = swing > 0 ? swordBox() : null
for (const e of enemies) {
if (e.knock > 0) {
// Knocked back: slide away from the sword for a few frames.
e.knock -= 1
move(e, e.kx, e.ky)
}
if (sword && e.knock === 0 && overlap(sword, box(e))) {
e.hp -= 1
e.knock = 10
e.kx = player.dir[0] * 4
e.ky = player.dir[1] * 4
}
}
enemies = enemies.filter((e) => e.hp > 0)
```overlap is the classic check for two boxes; box makes a box from a body.move as the hero, so walls stop it.e.knock === 0 makes sure one swing hits an enemy only once.filter keeps only enemies with health left.update, write overlap and box.update, find the sword and go through the enemies.Skills: Collision detection