Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(gameplay): a character that hunts, asked of the same machinery a player is

esengine6b9cc4ef25bf
diff --git a/sdk/src/gameplay/GameplayPlugin.ts b/sdk/src/gameplay/GameplayPlugin.ts
index 64d5080a3..472ee5ad0 100644
--- a/sdk/src/gameplay/GameplayPlugin.ts
+++ b/sdk/src/gameplay/GameplayPlugin.ts
@@ -28,27 +28,21 @@ import { AnimatorEvent, type AnimatorEventPayload } from '../animation/animatorE
import { EventReader, EventWriter, type EventWriterInstance } from '../ecs/event';
import { Damage, applyDamage, type DamagePayload } from './Health';
import { MeleeAttacks, resolveMeleeHits } from './MeleeAttack';
+import { huntTargets, driveHunterRootMotion } from './Hunter';
import { q } from '../math/quat';
import type { World } from '../ecs/world';
import type { Entity } from '../types';
import {
ThirdPersonController, type ThirdPersonControllerData,
desiredDirection, approachVelocity, facingYaw, turnToward, rootMotionVelocity,
- yawQuaternion, yawOfQuaternion, WORLD_BASIS, DODGE_KEY, ATTACK_KEY, type MoveBasis,
+ yawQuaternion, yawOfQuaternion, WORLD_BASIS, DODGE_KEY, ATTACK_KEY,
+ TPC_SPEED, TPC_GROUNDED, TPC_DODGE, TPC_ATTACK, type MoveBasis,
} from './ThirdPersonController';
import {
ThirdPersonCamera, type ThirdPersonCameraData,
orbitOffset, cameraGroundBasis, dampFactor, clampPitch,
} from './ThirdPersonCamera';
-/** Animator parameters this controller writes. Names, not clips. */
-export const TPC_SPEED = 'speed';
-export const TPC_GROUNDED = 'grounded';
-/** The trigger a dodge press sets. Whether any state answers it is the graph's. */
-export const TPC_DODGE = 'dodge';
-/** The trigger an attack press sets. The graph decides which state answers it. */
-export const TPC_ATTACK = 'attack';
-
/**
* What the animation is asking this character to do, or null when nothing is.
* Presence of the component is the opt-in and `active` is the switch — "the
@@ -300,6 +294,19 @@ export class GameplayPlugin implements Plugin {
{ name: 'DamageSystem' },
), { runIf: playModeOnly });
+ // Perception wrote what each hunter can see this frame; navigation plans
+ // in Update. Deciding between the two is what makes a destination set
+ // here the one planned on the same frame it was chosen.
+ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
+ [Res(Time)],
+ (time: TimeData) => {
+ const animator = app.hasResource(AnimatorController)
+ ? app.getResource(AnimatorController) : null;
+ huntTargets(world, animator, TPC_ATTACK, time.delta);
+ },
+ { name: 'HunterSystem' },
+ ), { runAfter: ['PerceptionSystem'], runIf: playModeOnly });
+
// Before the physics step: what the player is asking for.
app.addSystemToSchedule(Schedule.FixedPreUpdate, defineSystem(
[Res(Time), Res(Input)],
@@ -311,6 +318,14 @@ export class GameplayPlugin implements Plugin {
{ name: 'ThirdPersonControllerSystem' },
), { runIf: playModeOnly });
+ // Last writer before the step, after navigation's steering: a lunge is
+ // the animation's to override, and the same rule the player follows.
+ app.addSystemToSchedule(Schedule.FixedPreUpdate, defineSystem(
+ [],
+ () => { driveHunterRootMotion(world); },
+ { name: 'HunterRootMotionSystem' },
+ ), { runIf: playModeOnly });
+
// After it: what the world allowed. The animator hears this one.
app.addSystemToSchedule(Schedule.FixedPostUpdate, defineSystem(
[Res(Time)],
diff --git a/sdk/src/gameplay/Hunter.ts b/sdk/src/gameplay/Hunter.ts
new file mode 100644
index 000000000..5597160bb
--- /dev/null
+++ b/sdk/src/gameplay/Hunter.ts
@@ -0,0 +1,224 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Hunter.ts
+ * @brief The gameplay layer above a character that hunts: what it decides,
+ * asked of the same navigation, physics, animator and combat a player
+ * goes through.
+ *
+ * @details The twin of {@link ThirdPersonController}. That one turns INPUT into a
+ * request; this one turns PERCEPTION into one. Everything downstream is
+ * deliberately identical — the route is navigation's, the movement is
+ * the character controller's, the speed the animator hears is the one
+ * the world allowed, and a swing goes out as an animator trigger and
+ * comes back through the same MeleeAttack. An attacker being a program
+ * rather than a person must not change the mechanism.
+ *
+ * Four states and no authoring surface: this is a concrete enemy, not a
+ * framework. The FSM and behaviour-tree runtimes are how a GAME declares
+ * its own; what needed proving first is that the chain holds at all.
+ */
+
+import { defineComponent, type ComponentDef } from '../ecs/component';
+import { Transform, type TransformData } from '../ecs/component';
+import type { World } from '../ecs/world';
+import type { Entity, Vec3 } from '../types';
+import { CharacterController3D, type CharacterController3DData } from '../physics3d/Physics3DComponents';
+import { Perception, type PerceptionData } from '../ai/perception/components';
+import { NavAgent, setNavDestination, stopNavAgent } from '../ai/nav/NavAgent';
+import { Animator } from '../animation/Animator';
+import type { AnimatorControllerAPI } from '../animation/Animator';
+import { AnimatorRootMotion, type AnimatorRootMotionData } from '../animation/animatorRootMotion';
+import { Health, type HealthData } from './Health';
+import {
+ facingYaw, turnToward, yawQuaternion, yawOfQuaternion, rootMotionVelocity,
+ TPC_SPEED, TPC_GROUNDED,
+} from './ThirdPersonController';
+
+/** What a hunter is doing. Engine-written; a game reads it. @experimental */
+export type HunterState = 'idle' | 'chase' | 'attack' | 'dead';
+
+/** The fields of the `Hunter` component. @experimental */
+export interface HunterData {
+ /** Ground-plane distance it closes to before it swings, world units. */
+ attackRange: number;
+ /** Seconds between swings. */
+ attackInterval: number;
+ /** How fast it turns to face, degrees per second. */
+ rotationSpeed: number;
+ /** Speed under which the animator is told it is standing still. */
+ idleThreshold: number;
+ enabled: boolean;
+ /** Engine-written: one of `idle` / `chase` / `attack` / `dead`. */
+ state: string;
+ /** Engine-written: seconds until it may swing again. */
+ cooldown: number;
+}
+
+/**
+ * A character that hunts what it perceives: it asks navigation for a route, the
+ * character controller for the movement, and the animator for a swing. Add it
+ * beside `Perceiver`/`Perception`, `NavAgent`, `CharacterController3D` and an
+ * `Animator` whose graph answers `attack`; damage stays `MeleeAttack`'s.
+ *
+ * @experimental
+ */
+export const Hunter: ComponentDef<HunterData> = defineComponent<HunterData>('Hunter', {
+ attackRange: 110,
+ attackInterval: 1.6,
+ rotationSpeed: 540,
+ idleThreshold: 8,
+ enabled: true,
+ state: 'idle',
+ cooldown: 0,
+}, {
+ readonlyFields: ['state', 'cooldown'],
+ fields: {
+ attackRange: { min: 0, tooltip: 'How close it gets before it swings.' },
+ attackInterval: { min: 0, unit: 's' },
+ rotationSpeed: { min: 0, unit: '°/s' },
+ idleThreshold: { min: 0, step: 0.05, advanced: true },
+ state: { advanced: true },
+ cooldown: { advanced: true, unit: 's' },
+ },
+});
+
+// =============================================================================
+// The decision, as a pure function
+// =============================================================================
+
+/** Everything the decision depends on, so it can be made without a world. */
+export interface HunterSituation {
+ alive: boolean;
+ visible: boolean;
+ /** Distance to what it sees, IN THE GROUND PLANE — two capsules standing on
+ * the same floor are never as close as their three-axis distance says. */
+ distance: number;
+ attackRange: number;
+}
+
+/**
+ * What a hunter should be doing. Recomputed every frame rather than latched:
+ * a target that steps out of reach mid-swing has to be chased again, and a
+ * state that only leaves on its own would leave it swinging at air.
+ */
+export function decideHunterState(s: HunterSituation): HunterState {
+ if (!s.alive) return 'dead';
+ if (!s.visible) return 'idle';
+ return s.distance <= s.attackRange ? 'attack' : 'chase';
+}
+
+// =============================================================================
+// The system
+// =============================================================================
+
+const ZERO: Vec3 = { x: 0, y: 0, z: 0 };
+
+/** Stop the body. Navigation SKIPS an agent with no destination, so the velocity
+ * it last wrote would carry a hunter on walking after it stopped chasing. */
+function halt(world: World, entity: Entity): void {
+ if (!world.has(entity, CharacterController3D)) return;
+ world.update(entity, CharacterController3D, (c: CharacterController3DData) => {
+ c.velocity.x = 0;
+ c.velocity.z = 0;
+ });
+}
+
+/** Turn toward `wanted` at the component's rate; a zero direction holds. */
+function face(world: World, entity: Entity, wanted: Vec3, degreesPerSecond: number, dt: number): void {
+ if (Math.hypot(wanted.x, wanted.z) < 1e-6 || !world.has(entity, Transform)) return;
+ const to = facingYaw({ x: wanted.x, y: 0, z: wanted.z });
+ world.update(entity, Transform, (t: TransformData) => {
+ const turned = turnToward(yawOfQuaternion(t.rotation), to, degreesPerSecond, dt);
+ const yaw = yawQuaternion(turned);
+ t.rotation.w = yaw.w; t.rotation.x = yaw.x; t.rotation.y = yaw.y; t.rotation.z = yaw.z;
+ });
+}
+
+/**
+ * Perceive, decide, and ask — after perception, before navigation, so the
+ * destination is planned the frame it was chosen. It moves nothing: where the
+ * hunter ends up is the character controller's answer, and the speed the
+ * animator hears is that answer. A hunter shoving a wall is not running on the spot.
+ */
+export function huntTargets(
+ world: World, animator: AnimatorControllerAPI | null, attackTrigger: string, dt: number,
+): void {
+ for (const entity of world.getEntitiesWithComponents([Hunter, Perception, Transform])) {
+ const data = world.get(entity, Hunter) as HunterData;
+ if (!data.enabled) continue;
+
+ const sight = world.get(entity, Perception) as PerceptionData;
+ const here = (world.get(entity, Transform) as TransformData).position;
+ const alive = !world.has(entity, Health)
+ || (world.get(entity, Health) as HealthData).current > 0;
+ const state = decideHunterState({
+ alive,
+ visible: sight.visible,
+ distance: Math.hypot(sight.targetX - here.x, sight.targetZ - here.z),
+ attackRange: data.attackRange,
+ });
+
+ if (state === 'chase' && world.has(entity, NavAgent)) {
+ setNavDestination(world, entity, {
+ x: sight.targetX, y: sight.targetY, z: sight.targetZ,
+ });
+ } else {
+ if (world.has(entity, NavAgent)) stopNavAgent(world, entity);
+ halt(world, entity);
+ }
+
+ let cooldown = Math.max(0, data.cooldown - dt);
+ if (state === 'attack' && cooldown <= 0 && animator && world.has(entity, Animator)) {
+ // The ACTION, not the clip: whether this character has a swing at all
+ // is its animator graph's answer, exactly as it is for a player.
+ animator.setTrigger(entity, attackTrigger);
+ cooldown = data.attackInterval;
+ }
+
+ const character = world.has(entity, CharacterController3D)
+ ? world.get(entity, CharacterController3D) as CharacterController3DData : null;
+ const moved = character?.realVelocity ?? ZERO;
+ const speed = Math.hypot(moved.x, moved.z);
+ if (animator && world.has(entity, Animator)) {
+ animator.setFloat(entity, TPC_SPEED,
+ state === 'dead' || speed < data.idleThreshold ? 0 : speed);
+ animator.setBool(entity, TPC_GROUNDED, character?.isOnFloor ?? true);
+ }
+
+ // Where it goes while chasing, what it is fighting while attacking. The
+ // two are different questions: a swing aimed down the last bit of drift
+ // lands beside the target it was aimed at.
+ if (state === 'chase' && speed >= data.idleThreshold) {
+ face(world, entity, { x: moved.x, y: 0, z: moved.z }, data.rotationSpeed, dt);
+ } else if (state === 'attack') {
+ face(world, entity, { x: sight.dirX, y: 0, z: sight.dirZ }, data.rotationSpeed, dt);
+ }
+
+ world.update(entity, Hunter, (h: HunterData) => {
+ h.state = state;
+ h.cooldown = cooldown;
+ });
+ }
+}
+
+/**
+ * Hand a hunter's live root motion to its character controller, as the rate it
+ * covers. Last writer before the step, because navigation wrote a steering
+ * velocity earlier in the frame and a lunge is the animation's to override.
+ */
+export function driveHunterRootMotion(world: World): void {
+ for (const entity of world.getEntitiesWithComponents(
+ [Hunter, AnimatorRootMotion, CharacterController3D],
+ )) {
+ const data = world.get(entity, Hunter) as HunterData;
+ if (!data.enabled) continue;
+ const request = world.get(entity, AnimatorRootMotion) as AnimatorRootMotionData;
+ if (!request.active) continue;
+ const v = rootMotionVelocity(request.deltaPosition, request.deltaTime);
+ world.update(entity, CharacterController3D, (c: CharacterController3DData) => {
+ c.velocity.x = v.x;
+ c.velocity.z = v.z;
+ });
+ }
+}
diff --git a/sdk/src/gameplay/MeleeAttack.ts b/sdk/src/gameplay/MeleeAttack.ts
index bb81f9306..911fca2a7 100644
--- a/sdk/src/gameplay/MeleeAttack.ts
+++ b/sdk/src/gameplay/MeleeAttack.ts
@@ -26,7 +26,7 @@ import type { World } from '../ecs/world';
import type { Entity } from '../types';
import type { Overlap3DHit } from '../physics3d/Physics3DQueries';
import type { AnimatorEventPayload } from '../animation/animatorEvent';
-import { Health, type DamagePayload } from './Health';
+import { Health, type DamagePayload, type HealthData } from './Health';
/**
* The events a clip declares that this reads. Names rather than times: a state
@@ -190,6 +190,11 @@ export function resolveMeleeHits(
if (!world.valid(attacker) || !world.has(attacker, MeleeAttack)) continue;
const attack = world.get(attacker, MeleeAttack) as MeleeAttackData;
if (!attack.enabled) continue;
+ // A swing already in the air when its owner went down lands on nobody:
+ // the animator keeps playing whatever it was playing, and "the attack
+ // stops" cannot be left to whoever remembers to switch this off.
+ if (world.has(attacker, Health)
+ && (world.get(attacker, Health) as HealthData).current <= 0) continue;
if (event.name === COMBAT_ATTACK_START) {
attacks.open(attacker);
diff --git a/sdk/src/gameplay/ThirdPersonController.ts b/sdk/src/gameplay/ThirdPersonController.ts
index 4270fc858..77cce1a41 100644
--- a/sdk/src/gameplay/ThirdPersonController.ts
+++ b/sdk/src/gameplay/ThirdPersonController.ts
@@ -20,6 +20,16 @@ import { defineComponent, type ComponentDef } from '../ecs/component';
import type { Entity } from '../types';
import type { Vec3 } from '../types';
+/**
+ * Animator parameters a controller writes, and the triggers it sets. Names, not
+ * clips — and shared with {@link Hunter}, so one graph drives a player and an
+ * enemy and neither can drift into a private vocabulary.
+ */
+export const TPC_SPEED = 'speed';
+export const TPC_GROUNDED = 'grounded';
+export const TPC_DODGE = 'dodge';
+export const TPC_ATTACK = 'attack';
+
/** The key a dodge is asked for on; the animator decides whether there is one. */
export const DODGE_KEY = 'ShiftLeft';
diff --git a/sdk/src/gameplay/index.ts b/sdk/src/gameplay/index.ts
index d5a99a0af..ccc2da55b 100644
--- a/sdk/src/gameplay/index.ts
+++ b/sdk/src/gameplay/index.ts
@@ -8,6 +8,10 @@ export {
shortestAngleDelta,
turnToward,
rootMotionVelocity,
+ TPC_SPEED,
+ TPC_GROUNDED,
+ TPC_DODGE,
+ TPC_ATTACK,
yawQuaternion,
yawOfQuaternion,
WORLD_BASIS,
@@ -26,6 +30,16 @@ export {
type ThirdPersonCameraData,
} from './ThirdPersonCamera';
+export {
+ Hunter,
+ decideHunterState,
+ huntTargets,
+ driveHunterRootMotion,
+ type HunterData,
+ type HunterState,
+ type HunterSituation,
+} from './Hunter';
+
export {
Health,
Damage,
@@ -48,10 +62,6 @@ export {
export {
GameplayPlugin,
gameplayPlugin,
- TPC_SPEED,
- TPC_GROUNDED,
- TPC_DODGE,
- TPC_ATTACK,
requestMotion,
observeMotion,
updateCameras,
diff --git a/sdk/tests/combat.test.ts b/sdk/tests/combat.test.ts
index d4722622c..0ccd870fe 100644
--- a/sdk/tests/combat.test.ts
+++ b/sdk/tests/combat.test.ts
@@ -253,6 +253,12 @@ describe('what the animator says is not what combat does', () => {
expect(swing(world, new MeleeAttacks(), ['footstep', 'windup', 'recover'])).toEqual([]);
});
+ it('lands nothing once the attacker itself is down', () => {
+ const world = scene();
+ world.insert(ATTACKER, Health, health(0));
+ expect(swing(world, new MeleeAttacks(), [COMBAT_ATTACK_START, COMBAT_HIT])).toEqual([]);
+ });
+
it('does nothing at all while the attack is disabled', () => {
const world = scene({ enabled: false });
expect(swing(world, new MeleeAttacks(), [COMBAT_ATTACK_START, COMBAT_HIT])).toEqual([]);
diff --git a/sdk/tests/hunter.test.ts b/sdk/tests/hunter.test.ts
new file mode 100644
index 000000000..42754e0cb
--- /dev/null
+++ b/sdk/tests/hunter.test.ts
@@ -0,0 +1,305 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The claim: a hunter decides and asks. It moves no transform, deals no damage,
+ * and what its animator hears is what the world allowed.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ Hunter, decideHunterState, huntTargets, driveHunterRootMotion,
+ TPC_SPEED, TPC_GROUNDED, TPC_ATTACK,
+ type HunterData,
+} from '../src/gameplay';
+import { Health, type HealthData } from '../src/gameplay';
+import { Perception, type PerceptionData } from '../src/ai/perception/components';
+import { NavAgent, type NavAgentData } from '../src/ai/nav/NavAgent';
+import { CharacterController3D, type CharacterController3DData } from '../src/physics3d/Physics3DComponents';
+import { AnimatorRootMotion, type AnimatorRootMotionData } from '../src/animation';
+import { Animator, AnimatorControllerAPI, type AnimatorData } from '../src/animation';
+import { Transform, type TransformData } from '../src/ecs/component';
+import { q } from '../src/math/quat';
+
+const ENEMY = 1;
+
+function makeWorld() {
+ const store = new Map<unknown, Map<number, unknown>>();
+ const mapOf = (c: unknown) => {
+ let m = store.get(c);
+ if (!m) { m = new Map(); store.set(c, m); }
+ return m;
+ };
+ return {
+ insert(e: number, c: unknown, d: unknown) { mapOf(c).set(e, d); },
+ get(e: number, c: unknown) { return mapOf(c).get(e); },
+ has(e: number, c: unknown) { return mapOf(c).has(e); },
+ set(e: number, c: unknown, d: unknown) { mapOf(c).set(e, d); },
+ valid() { return true; },
+ update(e: number, c: unknown, edit: (d: any) => void) {
+ const d = mapOf(c).get(e);
+ if (d === undefined) throw new Error('update: entity does not carry it');
+ edit(d); mapOf(c).set(e, d);
+ },
+ getEntitiesWithComponents(comps: unknown[]) {
+ const [first, ...rest] = comps;
+ return [...mapOf(first).keys()].filter(e => rest.every(c => mapOf(c).has(e)));
+ },
+ } as any;
+}
+
+const sight = (over: Partial<PerceptionData> = {}): PerceptionData => ({
+ visible: true, distance: 0,
+ targetX: 0, targetY: 0, targetZ: -400,
+ dirX: 0, dirY: 0, dirZ: -1,
+ ...over,
+} as PerceptionData);
+
+const character = (over: Partial<CharacterController3DData> = {}): CharacterController3DData => ({
+ velocity: { x: 0, y: 0, z: 0 },
+ radius: 30, halfHeight: 30, maxSlope: 0.87, layer: 0,
+ stepHeight: 40, snapDown: 50, mass: 70, pushForce: 5000, enabled: true,
+ isOnFloor: true, floorNormal: { x: 0, y: 1, z: 0 },
+ realVelocity: { x: 0, y: 0, z: 0 },
+ ...over,
+} as CharacterController3DData);
+
+/** A hunter at the origin that can see something 400 units up the -Z axis. */
+function scene(over: Partial<HunterData> = {}, perception: Partial<PerceptionData> = {}) {
+ const world = makeWorld();
+ world.insert(ENEMY, Transform, {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 },
+ } as unknown as TransformData);
+ world.insert(ENEMY, Hunter, {
+ attackRange: 110, attackInterval: 1.6, rotationSpeed: 3600,
+ idleThreshold: 8, enabled: true, state: 'idle', cooldown: 0, ...over,
+ } as HunterData);
+ world.insert(ENEMY, Perception, sight(perception));
+ world.insert(ENEMY, NavAgent, {
+ speed: 200, radius: 0, arriveRadius: 6, repathInterval: 0.5,
+ hasTarget: false, targetX: 0, targetY: 0, targetZ: 0, arrived: false,
+ } as NavAgentData);
+ world.insert(ENEMY, CharacterController3D, character());
+ world.insert(ENEMY, Animator, { controller: 'x', currentState: '', enabled: true } as AnimatorData);
+ world.insert(ENEMY, Health, { current: 100, max: 100 } as HealthData);
+ return world;
+}
+
+const hunter = (world: any) => world.get(ENEMY, Hunter) as HunterData;
+const agent = (world: any) => world.get(ENEMY, NavAgent) as NavAgentData;
+const body = (world: any) => world.get(ENEMY, CharacterController3D) as CharacterController3DData;
+const hunt = (world: any, animator: AnimatorControllerAPI | null = null, dt = 1 / 60) =>
+ huntTargets(world, animator, TPC_ATTACK, dt);
+
+// =============================================================================
+// The decision, on its own
+// =============================================================================
+
+describe('what a hunter should be doing', () => {
+ const at = (over: Partial<Parameters<typeof decideHunterState>[0]>) =>
+ decideHunterState({ alive: true, visible: true, distance: 400, attackRange: 110, ...over });
+
+ it('is nothing at all once it is down, whatever it can see', () => {
+ expect(at({ alive: false, visible: true, distance: 10 })).toBe('dead');
+ });
+
+ it('is idle while it sees nothing', () => {
+ expect(at({ visible: false })).toBe('idle');
+ });
+
+ it('is a chase while what it sees is out of reach', () => {
+ expect(at({ distance: 400 })).toBe('chase');
+ });
+
+ it('is a swing once it is close enough', () => {
+ expect(at({ distance: 100 })).toBe('attack');
+ });
+
+ it('goes back to a chase when the target steps away mid-swing', () => {
+ // Recomputed, not latched: a state that only left on its own would leave
+ // the hunter swinging at air.
+ expect(at({ distance: 111 })).toBe('chase');
+ });
+});
+
+// =============================================================================
+// What it asks for
+// =============================================================================
+
+describe('a hunter asks navigation, and nothing else', () => {
+ it('points the agent at what it sees', () => {
+ const world = scene();
+ hunt(world);
+ expect(hunter(world).state).toBe('chase');
+ expect(agent(world).hasTarget).toBe(true);
+ expect(agent(world).targetZ).toBe(-400);
+ });
+
+ it('moves no transform of its own', () => {
+ const world = scene();
+ const before = { ...(world.get(ENEMY, Transform) as TransformData).position };
+ hunt(world);
+ expect((world.get(ENEMY, Transform) as TransformData).position).toEqual(before);
+ });
+
+ it('stops the agent AND the body when it loses sight', () => {
+ const world = scene();
+ hunt(world);
+ // Navigation SKIPS an agent with no destination, so a hunter that only
+ // cleared the target would coast on the velocity nav last wrote.
+ world.update(ENEMY, CharacterController3D, (c: CharacterController3DData) => {
+ c.velocity.x = 120; c.velocity.z = -160;
+ });
+ world.insert(ENEMY, Perception, sight({ visible: false }));
+ hunt(world);
+
+ expect(hunter(world).state).toBe('idle');
+ expect(agent(world).hasTarget).toBe(false);
+ expect(body(world).velocity.x).toBe(0);
+ expect(body(world).velocity.z).toBe(0);
+ });
+
+ it('stops chasing once it is close enough to swing', () => {
+ const world = scene({}, { targetZ: -80 });
+ hunt(world);
+ expect(hunter(world).state).toBe('attack');
+ expect(agent(world).hasTarget).toBe(false);
+ });
+});
+
+describe('a hunter swings through the animator', () => {
+ /** The triggers an animator is holding for the enemy, read back. */
+ const triggersOf = (a: AnimatorControllerAPI): string[] => {
+ const store = (a as unknown as { triggers: Map<number, Set<string>> }).triggers;
+ return [...(store.get(ENEMY) ?? [])];
+ };
+
+ it('sets the action, and names no clip', () => {
+ const world = scene({}, { targetZ: -80 });
+ const animator = new AnimatorControllerAPI();
+ hunt(world, animator);
+ expect(triggersOf(animator)).toContain(TPC_ATTACK);
+ });
+
+ it('and waits out its own interval before the next one', () => {
+ const world = scene({ attackInterval: 1 }, { targetZ: -80 });
+ const animator = new AnimatorControllerAPI();
+ hunt(world, animator, 0.1);
+ animator.resetTrigger(ENEMY, TPC_ATTACK);
+
+ for (let i = 0; i < 5; i++) hunt(world, animator, 0.1);
+ expect(triggersOf(animator)).not.toContain(TPC_ATTACK);
+ for (let i = 0; i < 6; i++) hunt(world, animator, 0.1);
+ expect(triggersOf(animator)).toContain(TPC_ATTACK);
+ });
+
+ it('never swings once it is down', () => {
+ const world = scene({}, { targetZ: -80 });
+ world.insert(ENEMY, Health, { current: 0, max: 100 } as HealthData);
+ const animator = new AnimatorControllerAPI();
+ hunt(world, animator);
+ expect(hunter(world).state).toBe('dead');
+ expect(triggersOf(animator)).not.toContain(TPC_ATTACK);
+ expect(agent(world).hasTarget).toBe(false);
+ });
+});
+
+describe('what the animator hears', () => {
+ it('is the speed the world allowed, not the one navigation asked for', () => {
+ const world = scene();
+ const animator = new AnimatorControllerAPI();
+ // Navigation asked for a full run and the world gave nothing back.
+ world.update(ENEMY, CharacterController3D, (c: CharacterController3DData) => {
+ c.velocity.z = -200;
+ c.realVelocity.z = 0;
+ });
+ hunt(world, animator);
+ expect(animator.getFloat(ENEMY, TPC_SPEED)).toBe(0);
+ });
+
+ it('is that speed when it is real', () => {
+ const world = scene();
+ const animator = new AnimatorControllerAPI();
+ world.update(ENEMY, CharacterController3D, (c: CharacterController3DData) => {
+ c.realVelocity.z = -150;
+ });
+ hunt(world, animator);
+ expect(animator.getFloat(ENEMY, TPC_SPEED)).toBeCloseTo(150, 5);
+ });
+
+ it('is standing still once it is down, however fast it was going', () => {
+ const world = scene();
+ world.insert(ENEMY, Health, { current: 0, max: 100 } as HealthData);
+ const animator = new AnimatorControllerAPI();
+ world.update(ENEMY, CharacterController3D, (c: CharacterController3DData) => {
+ c.realVelocity.z = -150;
+ });
+ hunt(world, animator);
+ expect(animator.getFloat(ENEMY, TPC_SPEED)).toBe(0);
+ });
+
+ it('carries the floor contact through as it stands', () => {
+ const world = scene();
+ const animator = new AnimatorControllerAPI();
+ world.update(ENEMY, CharacterController3D, (c: CharacterController3DData) => {
+ c.isOnFloor = false;
+ });
+ hunt(world, animator);
+ expect(animator.getBool(ENEMY, TPC_GROUNDED)).toBe(false);
+ });
+});
+
+describe('which way a hunter looks', () => {
+ const yawOf = (world: any) =>
+ q.toEuler((world.get(ENEMY, Transform) as TransformData).rotation)[1];
+
+ it('is where it actually went while it is chasing', () => {
+ const world = scene();
+ world.update(ENEMY, CharacterController3D, (c: CharacterController3DData) => {
+ c.realVelocity.x = -150;
+ });
+ // Turning is rate-limited, so give it the steps the quarter turn takes.
+ for (let i = 0; i < 5; i++) hunt(world);
+ expect(yawOf(world)).toBeCloseTo(90, 3);
+ });
+
+ it('is at the target while it is swinging, whatever the last drift was', () => {
+ // A swing aimed down a residual drift lands beside what it aimed at.
+ const world = scene({}, { targetZ: -80, dirX: -1, dirZ: 0 });
+ world.update(ENEMY, CharacterController3D, (c: CharacterController3DData) => {
+ c.realVelocity.z = -150;
+ });
+ for (let i = 0; i < 5; i++) hunt(world);
+ expect(hunter(world).state).toBe('attack');
+ expect(yawOf(world)).toBeCloseTo(90, 3);
+ });
+});
+
+describe('a hunter’s lunge goes through the character controller', () => {
+ it('becomes the rate the animation asked for', () => {
+ const world = scene();
+ world.insert(ENEMY, AnimatorRootMotion, {
+ enabled: true, active: true,
+ deltaPosition: { x: 0, y: 0, z: -4 },
+ deltaRotation: { w: 1, x: 0, y: 0, z: 0 },
+ deltaTime: 1 / 60,
+ } as AnimatorRootMotionData);
+ driveHunterRootMotion(world);
+ expect(body(world).velocity.z).toBeCloseTo(-240, 5);
+ });
+
+ it('and leaves the steering alone when no animation is driving', () => {
+ const world = scene();
+ world.insert(ENEMY, AnimatorRootMotion, {
+ enabled: true, active: false,
+ deltaPosition: { x: 0, y: 0, z: -4 },
+ deltaRotation: { w: 1, x: 0, y: 0, z: 0 },
+ deltaTime: 1 / 60,
+ } as AnimatorRootMotionData);
+ world.update(ENEMY, CharacterController3D, (c: CharacterController3DData) => {
+ c.velocity.z = -77;
+ });
+ driveHunterRootMotion(world);
+ expect(body(world).velocity.z).toBe(-77);
+ });
+});