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.

fix(ai): a body does not block the view of itself

esengine8de54f5f319e
diff --git a/desktop/scripts/launch-export.mjs b/desktop/scripts/launch-export.mjs
index fa6f87f1f..3952bc5ac 100644
--- a/desktop/scripts/launch-export.mjs
+++ b/desktop/scripts/launch-export.mjs
@@ -21,6 +21,10 @@
* --timeout <ms> how long to wait for the first frame (default 30000)
* --allow-flat accept a single-colour frame (a deliberately blank scene)
* --input <json> drive it: {"keys":["ArrowRight"]} or {"pointer":{"x":.5,"y":.5}}
+ * --log <regex> also print console lines matching this (the engine's own
+ * warnings say why a subsystem sat out; only `[engine]`
+ * lines are forwarded otherwise, which means diagnosing
+ * one costs a probe planted in the game)
*/
import { app, BrowserWindow } from 'electron';
import http from 'node:http';
@@ -49,6 +53,8 @@ const H = Number(flag('h', '360'));
const SETTLE = Number(flag('settle', '30'));
const INPUT = flag('input', '');
const TIMEOUT = Number(flag('timeout', '30000'));
+const LOG = flag('log', '');
+const logRe = LOG ? new RegExp(LOG, 'i') : null;
const MIME = {
'.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
@@ -114,7 +120,7 @@ async function main() {
const errors = [];
const stop = onRendererConsole(win.webContents, (msg) => {
if (/error|uncaught|failed/i.test(msg)) errors.push(msg.slice(0, 300));
- if (msg.startsWith('[engine]')) console.log(` ${msg}`);
+ if (msg.startsWith('[engine]') || logRe?.test(msg)) console.log(` ${msg}`);
});
win.webContents.on('render-process-gone', (_e, d) => errors.push(`render process gone: ${d.reason}`));
diff --git a/sdk/src/ai/perception/PerceptionPlugin.ts b/sdk/src/ai/perception/PerceptionPlugin.ts
index 7235e353f..657c1fb83 100644
--- a/sdk/src/ai/perception/PerceptionPlugin.ts
+++ b/sdk/src/ai/perception/PerceptionPlugin.ts
@@ -30,7 +30,15 @@ export interface PerceptionWorldView {
insert<C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>): unknown;
}
-export type LosCheck = (ox: number, oy: number, tx: number, ty: number) => boolean;
+/**
+ * True when the line from (ox,oy) to (tx,ty) is occluded. `observer` and
+ * `target` are the two bodies at its ends — whatever they own is not what the
+ * check is asking about.
+ */
+export type LosCheck = (
+ ox: number, oy: number, tx: number, ty: number,
+ observer: Entity, target: Entity,
+) => boolean;
/** Update every Perceiver's Perception with the nearest visible target. */
export function stepPerception(world: PerceptionWorldView, isBlocked?: LosCheck): void {
@@ -50,7 +58,8 @@ export function stepPerception(world: PerceptionWorldView, isBlocked?: LosCheck)
let best: { x: number; y: number; distance: number; dirX: number; dirY: number } | null = null;
for (const t of targets) {
if (t.e === e) continue;
- const r = senseTarget(ox, oy, facing, t.x, t.y, cfg.range, halfFov, isBlocked);
+ const r = senseTarget(ox, oy, facing, t.x, t.y, cfg.range, halfFov,
+ isBlocked && ((ax, ay, bx, by) => isBlocked(ax, ay, bx, by, e, t.e)));
if (r.visible && (!best || r.distance < best.distance)) {
best = { x: t.x, y: t.y, distance: r.distance, dirX: r.dirX, dirY: r.dirY };
}
@@ -65,16 +74,20 @@ export function stepPerception(world: PerceptionWorldView, isBlocked?: LosCheck)
}
}
-/** Build a raycast-backed line-of-sight check. Occluded if anything is hit before the target. */
+/**
+ * Raycast-backed line of sight: occluded by anything hit before the target that
+ * is not one of the two bodies at the ends. A character's collider sits at its
+ * feet, so a ray aimed at the origin passes through the target's own capsule —
+ * counting that hides everyone approached from below.
+ */
export function makeLosCheck(physics: PhysicsAPI): LosCheck {
- return (ox, oy, tx, ty) => {
+ return (ox, oy, tx, ty, observer, target) => {
const dx = tx - ox;
const dy = ty - oy;
const dist = Math.hypot(dx, dy);
if (dist === 0) return false;
const hits = physics.raycast({ x: ox, y: oy }, { x: dx / dist, y: dy / dist }, dist);
- // A hit clearly short of the target blocks the view (the last ~2% is the target itself).
- return hits.some(h => h.fraction < 0.98);
+ return hits.some(h => h.fraction < 0.98 && h.entity !== observer && h.entity !== target);
};
}
diff --git a/sdk/tests/perception-los.test.ts b/sdk/tests/perception-los.test.ts
new file mode 100644
index 000000000..dcb50b6e7
--- /dev/null
+++ b/sdk/tests/perception-los.test.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What blocks a line of sight, and what only looks like it does.
+ *
+ * A collider is authored where a body stands, not at its origin — for a 3/4
+ * character, at its feet. A ray aimed at the origin therefore passes through
+ * the target's own capsule on the way in, and through the observer's on the way
+ * out. Counting either as an occluder makes enemies blind to anything they
+ * approach from below while leaving them able to see it from the side, which is
+ * the shape of a bug nobody would think to look for in a raycast.
+ */
+import { describe, it, expect } from 'vitest';
+import { makeLosCheck } from '../src/ai/perception/PerceptionPlugin';
+import type { PhysicsAPI, RaycastHit } from '../src/physics';
+import type { Entity } from '../src/types';
+
+const OBSERVER = 11 as Entity;
+const TARGET = 22 as Entity;
+const WALL = 33 as Entity;
+
+const hit = (entity: Entity, fraction: number): RaycastHit => ({
+ entity, fraction, point: { x: 0, y: 0 }, normal: { x: 0, y: 1 },
+});
+
+const physicsReturning = (hits: RaycastHit[]): PhysicsAPI =>
+ ({ raycast: () => hits }) as unknown as PhysicsAPI;
+
+describe('makeLosCheck', () => {
+ it('is not blocked by the target it is looking at', () => {
+ const los = makeLosCheck(physicsReturning([hit(TARGET, 0.6)]));
+ expect(los(0, 0, 100, 0, OBSERVER, TARGET)).toBe(false);
+ });
+
+ it('is not blocked by the observer it is looking from', () => {
+ const los = makeLosCheck(physicsReturning([hit(OBSERVER, 0.02)]));
+ expect(los(0, 0, 100, 0, OBSERVER, TARGET)).toBe(false);
+ });
+
+ it('is blocked by anything else in between', () => {
+ const los = makeLosCheck(physicsReturning([hit(WALL, 0.5)]));
+ expect(los(0, 0, 100, 0, OBSERVER, TARGET)).toBe(true);
+ });
+
+ it('still sees past a wall that is behind the target', () => {
+ const los = makeLosCheck(physicsReturning([hit(WALL, 0.99)]));
+ expect(los(0, 0, 100, 0, OBSERVER, TARGET)).toBe(false);
+ });
+
+ it('needs no ray at all when the two are on the same spot', () => {
+ const los = makeLosCheck(physicsReturning([hit(WALL, 0)]));
+ expect(los(50, 50, 50, 50, OBSERVER, TARGET)).toBe(false);
+ });
+});
diff --git a/sdk/tests/perception-step.test.ts b/sdk/tests/perception-step.test.ts
index 3bb30c931..03a820f1a 100644
--- a/sdk/tests/perception-step.test.ts
+++ b/sdk/tests/perception-step.test.ts
@@ -73,6 +73,21 @@ describe('stepPerception', () => {
expect(w.get(p, Perception).visible).toBe(true);
});
+ // The callback is asked about the space BETWEEN two bodies, so it is told
+ // which two: a character's collider sits at its feet, so a ray aimed at the
+ // origin passes through the target's own capsule on the way in.
+ it('tells the occlusion check which two bodies are at the ends of the line', () => {
+ const w = new FakeWorld();
+ const p = spawnPerceiver(w, 0, 0);
+ const t = spawnTarget(w, 80, 0);
+ const ends: Array<[number, number]> = [];
+ stepPerception(w, (_ox, _oy, _tx, _ty, observer, target) => {
+ ends.push([observer, target]);
+ return false;
+ });
+ expect(ends).toEqual([[p, t]]);
+ });
+
it('picks the nearest visible target', () => {
const w = new FakeWorld();
const p = spawnPerceiver(w, 0, 0);