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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(nav): an agent with a body is steered along its route, not moved
esengineb2f25ec64315
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 824514a7a..3a1d3cc86 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -170,6 +170,19 @@ published separately; it ships inside the editor.than the box around them. Nothing waits for the solver any more: the geometry isin the scene from the first frame.+- **A NavAgent with a body is steered, not moved.** The follower wrote the+ Transform, which is right for a marker and wrong for a character: a+ `CharacterController3D` has a solver of its own that collides, steps up and+ falls, and a Transform written from outside it fights that solver and loses —+ measured, an agent driven that way does not move at all. An entity carrying one+ now has its horizontal velocity written toward the next waypoint instead, and+ the vertical axis is left alone, because that one is the world's and writing a+ zero there would hold the body in the air. Distances for such an agent are+ measured in the ground plane: a character stands with its capsule's centre above+ the floor its route was planned on. New editor check `nav3d-character`, the one+ place the mesh, the character solver and the follower between them all exist at+ once.+- **A route over a grid is pulled taut, like a route over a mesh.** A\* answers insteps of one cell, so crossing open ground came back as a staircase and an agentwalking it wobbled down every diagonal. `shortenPath` keeps only the cells wherediff --git a/desktop b/desktopindex 91b6de7b8..5853fcde2 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 91b6de7b82b50adef9e50fa968d8c0143ef0dd3a+Subproject commit 5853fcde2f8eb4026c2e4f7526ce8d3bcd4e82f9diff --git a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/gameplay/ai/navigation.mdxindex e24293763..02e0e8069 100644--- a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx+++ b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx@@ -160,6 +160,30 @@ stopNavAgent(world, entity);only replans when the target actually moves or `repathInterval` elapses. Read`agent.arrived` (or `Perception`) to know when to switch behavior.+## Agents with a body++An agent whose entity also carries a **`CharacterController3D`** is **steered**+rather than moved: the plugin writes the controller's horizontal velocity toward+the next waypoint and lets the character's own solver do the walking, so the agent+collides with the world, steps up what it can and falls where it should. The+vertical axis is never written — that one belongs to the world, which is what makes+a route down a step a fall rather than a glide.++```typescript+cmds.spawn()+ .insert(Transform, { position: { x: 0, y: 200, z: 0 } })+ .insert(CharacterController3D, { radius: 30, halfHeight: 50 })+ .insert(NavAgent, { speed: 400, arriveRadius: 90 });+```++Distances are measured in the ground plane for such an agent, because a character+stands with its capsule's centre above the floor the route was planned on. Set the+volume's `agentRadius` to the controller's `radius` (and `agentHeight` to roughly+twice `halfHeight` plus the radius) so the mesh is the set of places that body fits.++Without a controller the agent's Transform is moved along the path directly, which+is what every flat game wants and what a 3D one gets before it has a body.+## Agents have widthOn a **grid**, set `radius` to the body's actual half-width and planning keeps itdiff --git a/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdxindex ae31af4b9..8268c6ba6 100644--- a/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx+++ b/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx@@ -143,6 +143,27 @@ stopNavAgent(world, entity);`repathInterval` 到点时,agent 才重新规划。读 `agent.arrived`(或 `Perception`)来判断何时切换行为。+## 有身体的 agent++如果 agent 所在实体同时带着 **`CharacterController3D`**,插件就**操舵**它而不是搬动它:+把控制器的水平速度指向下一个路点,由角色自己的求解器去走——于是它会和世界碰撞、爬得上去的+台阶就爬、该掉下去的地方就掉。垂直轴永远不写,那个轴是世界的,正是它让「下一级台阶」是掉+下去而不是滑下去。++```typescript+cmds.spawn()+ .insert(Transform, { position: { x: 0, y: 200, z: 0 } })+ .insert(CharacterController3D, { radius: 30, halfHeight: 50 })+ .insert(NavAgent, { speed: 400, arriveRadius: 90 });+```++这种 agent 的距离都在地平面上量,因为角色是**胶囊中心**悬在路线所在的地面之上的。把体积的+`agentRadius` 设成控制器的 `radius`(`agentHeight` 大致设成 `halfHeight` 的两倍加半径),+网格才是「这个身体站得下的所有位置」。++没有控制器时,agent 的 Transform 会被直接沿路径推进——平面游戏要的就是这个,3D 游戏在还没有+身体之前拿到的也是这个。+## agent 是有宽度的在**格子**上,把 `radius` 设成身体的实际半宽,寻路就会绕开它挤不过去的缝隙。留在 `0` 表示diff --git a/sdk/src/ai/nav/NavPlugin.ts b/sdk/src/ai/nav/NavPlugin.tsindex be18bab80..d04627173 100644--- a/sdk/src/ai/nav/NavPlugin.ts+++ b/sdk/src/ai/nav/NavPlugin.ts@@ -23,6 +23,7 @@ import {type ComponentData,} from '../../ecs/component';import { playModeOnly } from '../../ecs/env';+import { CharacterController3D } from '../../physics3d/Physics3DComponents';import { log } from '../../util/logger';import { Navigation, Nav } from './Navigation';import { NavAgent } from './NavAgent';@@ -104,6 +105,7 @@ export function bakeVolumes(/** The slice of `World` the nav step needs — lets tests inject a fake. */export interface NavWorldView {getEntitiesWithComponents(components: readonly AnyComponentDef[]): readonly Entity[];+ has<C extends AnyComponentDef>(entity: Entity, component: C): boolean;get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C>;set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void;}@@ -157,20 +159,16 @@ export function stepNavigation(// change or repath timer) rather than churning it every frame.if (!rt.reachable) continue;- const pos = { x: tf.position.x, y: tf.position.y, z: tf.position.z };- rt.index = advanceAlongPath(pos, rt.waypoints, rt.index, agent.speed * dt);- tf.position.x = pos.x;- tf.position.y = pos.y;- tf.position.z = pos.z;- world.set(entity, Transform, tf);-- // Arrival is a DISTANCE, not the end of the list: an agent that has to- // stop short of what it is chasing never reaches the last waypoint, and- // one that walks the path exactly stands on top of its target.- const goal = rt.waypoints[rt.waypoints.length - 1];- const withinGoal = goal !== undefined && agent.arriveRadius > 0- && Math.hypot(goal.x - pos.x, goal.y - pos.y, goal.z - pos.z) <= agent.arriveRadius;- if (rt.index >= rt.waypoints.length || withinGoal) {+ // A body walks; anything else is moved, and which one an entity is, is+ // what it CARRIES. A character has a solver that collides, steps up and+ // falls; a follower writing the Transform would fight all three.+ const character = world.has(entity, CharacterController3D)+ ? world.get(entity, CharacterController3D) : null;+ const done = character && character.enabled !== false+ ? steerCharacter(world, entity, agent, rt, character, dt)+ : walkTransform(world, entity, agent, rt, tf, dt);++ if (done) {agent.arrived = true;agent.hasTarget = false;world.set(entity, NavAgent, agent);@@ -179,6 +177,73 @@ export function stepNavigation(}}+/** Move the Transform along the path directly. Returns whether the goal is reached. */+function walkTransform(+ world: NavWorldView, entity: Entity, agent: ComponentData<typeof NavAgent>,+ rt: AgentRuntime, tf: ComponentData<typeof Transform>, dt: number,+): boolean {+ const pos = { x: tf.position.x, y: tf.position.y, z: tf.position.z };+ rt.index = advanceAlongPath(pos, rt.waypoints, rt.index, agent.speed * dt);+ tf.position.x = pos.x;+ tf.position.y = pos.y;+ tf.position.z = pos.z;+ world.set(entity, Transform, tf);++ // Arrival is a DISTANCE, not the end of the list: an agent that has to stop+ // short of what it is chasing never reaches the last waypoint, and one that+ // walks the path exactly stands on top of its target.+ const goal = rt.waypoints[rt.waypoints.length - 1];+ const withinGoal = goal !== undefined && agent.arriveRadius > 0+ && Math.hypot(goal.x - pos.x, goal.y - pos.y, goal.z - pos.z) <= agent.arriveRadius;+ return rt.index >= rt.waypoints.length || withinGoal;+}++/**+ * Point a character controller at the next waypoint and let its own solver move+ * it. Only the horizontal axes are written — the vertical one is the world's, and+ * that is what makes a route down a step a fall. Distances are in the ground plane+ * for the same reason: a capsule stands with its CENTRE above the floor.+ */+function steerCharacter(+ world: NavWorldView, entity: Entity, agent: ComponentData<typeof NavAgent>,+ rt: AgentRuntime, character: ComponentData<typeof CharacterController3D>, dt: number,+): boolean {+ const tf = world.get(entity, Transform);+ const pos = tf.position;+ // A body cannot be snapped onto a waypoint, so one counts as reached when it+ // is closer than the step this frame would have taken — otherwise an agent+ // orbits the waypoint it can never land exactly on.+ const reach = Math.max(agent.speed * dt * 1.5, WAYPOINT_REACH);+ while (rt.index < rt.waypoints.length) {+ const wp = rt.waypoints[rt.index]!;+ if (Math.hypot(wp.x - pos.x, wp.z - pos.z) > reach) break;+ rt.index++;+ }++ const goal = rt.waypoints[rt.waypoints.length - 1];+ const withinGoal = goal !== undefined && agent.arriveRadius > 0+ && Math.hypot(goal.x - pos.x, goal.z - pos.z) <= agent.arriveRadius;+ const target = rt.waypoints[rt.index];+ const done = rt.index >= rt.waypoints.length || withinGoal || target === undefined;++ if (done) {+ character.velocity.x = 0;+ character.velocity.z = 0;+ } else {+ const dx = target.x - pos.x;+ const dz = target.z - pos.z;+ const length = Math.hypot(dx, dz);+ character.velocity.x = length > 0 ? (dx / length) * agent.speed : 0;+ character.velocity.z = length > 0 ? (dz / length) * agent.speed : 0;+ }+ world.set(entity, CharacterController3D, character);+ return done;+}++/** How close a body has to get to a waypoint before the route moves on, in world+ * pixels, for an agent too slow for its own step to be the answer. */+const WAYPOINT_REACH = 8;+export class NavPlugin implements Plugin {name = 'nav';@@ -214,7 +279,7 @@ export class NavPlugin implements Plugin {name: 'NavAgentSystem',touches: {reads: [NavVolume._name],- writes: [NavAgent._name, Transform._name],+ writes: [NavAgent._name, Transform._name, CharacterController3D._name],},// Both move an entity; for one carrying both, the path is the// intent and the drift is not, so the follow lands last. Thediff --git a/sdk/tests/nav-step.test.ts b/sdk/tests/nav-step.test.tsindex 0dffd996b..ed08b196e 100644--- a/sdk/tests/nav-step.test.ts+++ b/sdk/tests/nav-step.test.ts@@ -29,9 +29,22 @@ class FakeWorld implements NavWorldView {return e;}+ /** Give an agent a body, so the follower steers it instead of moving it. */+ giveCharacter(entity: Entity, over: Record<string, unknown> = {}): void {+ this.store.set(`${entity}:CharacterController3D`, {+ velocity: { x: 0, y: 0, z: 0 }, enabled: true, ...over,+ });+ }+ character(entity: Entity): { velocity: { x: number; y: number; z: number }; enabled: boolean } {+ return this.store.get(`${entity}:CharacterController3D`) as never;+ }+getEntitiesWithComponents(): Entity[] {return this.entities;}+ has(entity: Entity, component: { _name: string }): boolean {+ return this.store.has(`${entity}:${component._name}`);+ }// eslint-disable-next-line @typescript-eslint/no-explicit-anyget(entity: Entity, component: { _name: string }): any {return this.store.get(`${entity}:${component._name}`);@@ -40,6 +53,9 @@ class FakeWorld implements NavWorldView {this.store.set(`${entity}:${component._name}`, data);}+ place(entity: Entity, x: number, y: number): void {+ this.store.set(`${entity}:Transform`, { position: { x, y, z: 0 } });+ }pos(entity: Entity): { x: number; y: number } {const tf = this.store.get(`${entity}:Transform`) as { position: { x: number; y: number } };return { x: tf.position.x, y: tf.position.y };@@ -239,3 +255,50 @@ describe('navGridFromTilemapLayer', () => {expect(grid.isWalkable(1, 2)).toBe(false);});});++// A character has a solver of its own — it collides, steps up and falls. A+// follower that wrote the Transform would undo all three every frame, so what+// it writes instead is where the body should be TRYING to go.+describe('an agent with a body', () => {+ const walker = (): { world: FakeWorld; nav: Navigation; entity: Entity } => {+ const world = new FakeWorld();+ const entity = world.spawnAgent(0, 0, { speed: 100, arriveRadius: 0, hasTarget: true, targetX: 80, targetY: 0 });+ world.giveCharacter(entity);+ return { world, nav: openNav(), entity };+ };++ it('is steered rather than moved', () => {+ const { world, nav, entity } = walker();+ stepNavigation(world, nav, 1 / 60, new Map());+ expect(world.pos(entity)).toEqual({ x: 0, y: 0 });+ expect(world.character(entity).velocity.x).toBeCloseTo(100, 3);+ });++ // The world carries the vertical axis: a zero written there is "walk", and+ // a follower that wrote one would hold the body up in the air.+ it('never writes the axis the world carries', () => {+ const { world, nav, entity } = walker();+ world.character(entity).velocity.y = -320;+ stepNavigation(world, nav, 1 / 60, new Map());+ expect(world.character(entity).velocity.y).toBe(-320);+ });++ it('stops the body when it arrives', () => {+ const { world, nav, entity } = walker();+ const runtimes = new Map<Entity, AgentRuntime>();+ stepNavigation(world, nav, 1 / 60, runtimes);+ // Put it on the goal; a body is not snapped there, it walks there.+ world.place(entity, 80, 0);+ stepNavigation(world, nav, 1 / 60, runtimes);+ expect(world.agent(entity).arrived).toBe(true);+ expect(world.character(entity).velocity.x).toBe(0);+ expect(world.character(entity).velocity.z).toBe(0);+ });++ it('is moved like anything else when its body is switched off', () => {+ const { world, nav, entity } = walker();+ world.character(entity).enabled = false;+ stepNavigation(world, nav, 1 / 60, new Map());+ expect(world.pos(entity).x).toBeGreaterThan(0);+ });+});