Reset this lesson?

Your edits to this lesson are deleted and its starting files load again.

Zelda-4 fills the first two rooms with Moblins. They wander about, take three sword hits to defeat, and hurt Link when they touch him. Because the assignment adds more enemy types, most of this lesson is a reusable base: Enemy and EnemyState hold everything a new enemy shares.

Link kills one Moblin, then walks into the other on purpose. Watch player.health in the readout: with no damage cooldown yet, it drops on every frame the Moblin touches him.

Spawning Enemies

Each room definition gains an enemies list. A spawn names its type and the tile it starts on, as an index into the room’s tiles array:

src/config/rooms.js
39
enemies: [
40
{ tileIndex: 43, type: "moblin" },
41
{ tileIndex: 22, type: "moblin" },
42
],

Default health, speed, and contact damage for each type live in src/config/enemies.js. A spawn can override any of them, so one room could hold a tougher Moblin without a new class:

src/config/enemies.js
2
export const moblinDefinition = {
3
health: 3,
4
speed: 32,
5
contactDamage: 1,
6
};

roomBuilder.js turns a spawn’s type into a class through a dictionary:

src/roomBuilder.js
16
const enemyClasses = {
17
moblin: Moblin,
18
};

Every enemy constructor takes the same (services, room, player, spawn), so adding an enemy type means one class, one entry here, and its name in the EnemyType union in globals.d.ts.

Rooms still rebuild on every visit, so Room.spawnEnemies() runs each time Link enters: defeated Moblins are back when you return.

The Enemy Base

Enemy extends Actor like Player does, so it already has a room, a position, a hurtbox, and pixel-by-pixel move(). It adds health, speed, contact damage, and its own state machine, and registers the death state every enemy shares:

src/objects/Enemy.js
73
this.health = spawn.health ?? definition.health;
74
this.speed = spawn.speed ?? definition.speed;
75
this.contactDamage = spawn.contactDamage ?? definition.contactDamage;
76
this.stateMachine.add(
77
EnemyStateName.Death,
78
new EnemyDeathState(services, this),
79
);

The Moblin class is tiny. It registers one state, Move, and starts in it.

The State Answers

Whether an enemy can hurt Link, or be hurt, depends on what it’s doing. A charging boss might hurt on contact while a stunned one doesn’t. So Enemy keeps no flags for this. EnemyState answers instead:

src/states/enemy/EnemyState.js
64
getHitbox() {
65
return this.enemy.getHurtbox();
66
}
67
68
/**
69
* Called after this state's hitbox hurts Link, so an attack that hits
70
* once can stop offering its hitbox. Contact damage has nothing to use up.
71
*
72
* @returns {void}
73
*/
74
confirmHit() {}
75
76
/** @returns {boolean} Whether Link's attacks can hurt the enemy in this state. */
77
get isVulnerable() {
78
return true;
79
}

By default an enemy’s whole body hurts Link and the sword can hit it. A state overrides only what’s different. EnemyDeathState returns undefined from getHitbox() and false from isVulnerable, so a dying enemy is harmless and can’t be hit twice.

Each enemy state also owns a Timer, cancelled in exit(), just like Link’s states.

Wandering

MoblinMoveState picks a random direction and walks it for half a second to a second and a half:

src/states/enemy/moblin/MoblinMoveState.js
50
if (!this.direction || this.remaining <= 0) {
51
this.direction = pickRandomElement([
52
Direction.Up,
53
Direction.Down,
54
Direction.Left,
55
Direction.Right,
56
]);
57
this.remaining = getRandomPositiveNumber(0.5, 1.5);
58
}
59
60
const distance = this.moblin.speed * dt;
61
const moved = this.moblin.move(this.direction, distance);
62
63
this.moblin.setFacing(this.direction);
64
this.remaining = moved < distance ? 0 : this.remaining - dt;

This is where move() returning the distance actually moved pays off. If a wall cut the step short, the Moblin picks a new direction on the next frame instead of pushing against the wall.

Enemy.canOccupy() uses the same isAreaOpen() as Link. Doorways are floor tiles but lead off the map, so enemies stay in their room.

Combat

PlayState.checkEnemyCollisions() puts it together each frame. For every enemy in the room, it asks two questions:

src/states/PlayState.js
116
if (
117
playerHitbox &&
118
playerState.canHit(enemy) &&
119
enemy.state.isVulnerable &&
120
isAABBCollision(playerHitbox, enemy.getHurtbox())
121
) {
122
enemy.takeDamage(playerState.attackDamage, this.player.position);
123
playerState.confirmHit(enemy);
124
}
125
126
const enemyHitbox = enemy.state.getHitbox();
127
128
if (
129
enemyHitbox &&
130
isAABBCollision(enemyHitbox, this.player.getHurtbox())
131
) {
132
this.player.takeDamage(enemy.contactDamage);
133
enemy.state.confirmHit();
134
}

The sword’s hitbox stays out for a tenth of a second, which is several frames. canHit() and confirmHit() make sure one swing lands once: the sword state remembers what it hit and stops after its first target.

Knockback is off in this demo so the Moblin stays in reach:

For now, Player.takeDamage() only lowers Link’s health. There’s no cooldown yet, so a Moblin touching him drains a point every frame. Open the debug panel and watch it fall to zero. Fixing that is Zelda-6’s job.

Knockback

A non-lethal hit plays the hurt sound and knocks the enemy back, away from Link:

src/objects/Enemy.js
133
this.knockbackDirection = getDirectionToward(
134
this.position.x - sourcePosition.x,
135
this.position.y - sourcePosition.y,
136
);
137
this.knockbackRemaining = ENEMY_KNOCKBACK_DURATION;

getDirectionToward() picks whichever axis covers more distance, so the knockback is always one of the four directions. While knockbackRemaining is above zero, Enemy.update() slides the enemy instead of updating its state.

Here’s the difference for a Moblin whose state is counting down to an attack when Link hits it twice:

A lethal hit changes to EnemyDeathState, which plays the explosion and then sets isRemoved. Room.removeFinishedEnemies() drops removed enemies after the update loop, so nothing leaves the array while it’s being looped over.

Who’s in Front?

In a top-down game, something lower on screen is nearer the viewer and should draw over something higher up. PlayState.renderActors() sorts Link and every enemy by the bottom of their hurtbox before drawing them:

src/states/PlayState.js
162
actors.sort(
163
(first, second) => this.getDepth(first) - this.getDepth(second),
164
);

getDepth() adds the room’s position, so actors in both rooms sort together during a pan. Here’s the difference sorting makes as Link walks past a Moblin:

The debug panel now also shows how many enemies are in the room.

Sort by depth

Walk below a Moblin: Link still draws behind it, because renderActors() in src/states/PlayState.js draws actors in the order it collected them.

The missing line is the code block under Who’s in Front? above. Add it just before actors.forEach(...).

Then walk Link up into the Moblin from below, so he overlaps it. The Challenge tab gets a ✓ once you’ve seen it work in the game.

📚 References

Powered by WebContainers
Files
Preparing Environment