logo
By Lawrence

5 minutes

Add Enemy AI

For three lessons, the kilrathi has sat there. You fly circles around it and shoot off its wings, and it never fights back. A real dogfight needs the other side to fight too: the enemy ship should fly a real pattern, point its nose at you, and shoot back. The next lessons also need to know who is hostile, and matching an "enemy" string is fragile — so the game asks for a component it can query type-safely.

Make Enemy1 fly and add a second enemy

Enemy1 already has a pose, a mesh, and a kilrathi loadout from Lesson 3. To make it fly, give it the same flight stack the Player uses: Velocity6DOF, FlightIntent, and ShipFlight. Then add the brain (AiPilot), the hostile marker (Enemy), and its own MachineGun. Append these to Enemy1.components:

"Velocity6DOF": {},
"FlightIntent": {},
"ShipFlight": { "maxThrust": 26, "boostMultiplier": 1.6, "turnRate": 3.5, "rollRate": 5.0, "linearDrag": 1.2, "angularDrag": 3.5 },
"AiPilot": { "targetTag": "player", "orbitRadius": 70, "orbitHeight": 0, "orbitAngle": 0.15, "angularVel": 0.04 },
"Enemy": {},
"MachineGun": {}

Now add a second fighter, Enemy2, on the same stack but spinning the other way — note the negative angularVel. Enemy1 orbits clockwise and Enemy2 counterclockwise, which spreads the pair around you instead of stacking them on one arc.

"Enemy2": {
  "tags": ["enemy"],
  "components": {
    "Transform6DOF": { "x": -28, "y": -5, "z": 70 },
    "Velocity6DOF": {},
    "FlightIntent": {},
    "ShipFlight": { "maxThrust": 26, "boostMultiplier": 1.6, "turnRate": 3.5, "rollRate": 5.0, "linearDrag": 1.2, "angularDrag": 3.5 },
    "AiPilot": { "targetTag": "player", "orbitRadius": 80, "orbitHeight": 0, "orbitAngle": -0.15, "angularVel": -0.04 },
    "Enemy": {},
    "ShipLoadout": { "loadout": "kilrathi" },
    "MachineGun": {},
    "Renderable": { "shape": "kilrathi", "sx": 3, "sy": 1, "sz": 4, "r": 0.5, "g": 0.55, "b": 0.4, "emissive": 0.15, "glbSrc": "/spaceshooter/bugship.glb" }
  }
}

Continue reading

Unlock the Full Course

Every lesson, the runnable examples, and the finished build — yours to keep.

$9one-time

Was this page helpful?

We read every note — tell us what's working and what isn't.

↑↓ NavigateEnter SelectEsc CloseCtrl+K Open Search