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
fix(physics): the character controller's first step scaled by a pixels-per-unit nobody had pushed
yhh625f732c60d1
diff --git a/sdk/src/physics/CharacterController.ts b/sdk/src/physics/CharacterController.tsindex 47c0370a7..3497f2851 100644--- a/sdk/src/physics/CharacterController.ts+++ b/sdk/src/physics/CharacterController.ts@@ -28,10 +28,13 @@ import { Query, Mut } from '../ecs/query';import { Res, Time, type TimeData } from '../ecs/resource';import { playModeOnly } from '../ecs/env';import { Physics, type PhysicsAPI } from './Physics';+import { readPixelsPerUnit } from './PhysicsSystem';import { BoxCollider, CircleCollider, CapsuleCollider } from './PhysicsComponents';+import { log } from '../util/logger';import type {BoxColliderData, CircleColliderData, CapsuleColliderData,} from './PhysicsComponents';+import type { MoverResult } from './PhysicsTypes';import type { World } from '../ecs/world';// =============================================================================@@ -273,6 +276,21 @@ function moverCapsuleFromShape(s: CastShape): MoverCapsule {return { c1: { x: s.ox + half, y: s.oy }, c2: { x: s.ox - half, y: s.oy }, radius: s.hy };}+function isFiniteMove(r: MoverResult): boolean {+ return Number.isFinite(r.dx) && Number.isFinite(r.dy)+ && Number.isFinite(r.velX) && Number.isFinite(r.velY);+}++let warnedNonFiniteMove = false;++function warnNonFiniteMove(entity: Entity, ppu: number, dt: number): void {+ if (warnedNonFiniteMove) return;+ warnedNonFiniteMove = true;+ log.error('physics', `CharacterController move on entity ${entity} resolved to a non-finite pose `+ + `(ppu=${ppu}, dt=${dt}); the Transform was left where it was. Check the entity's collider, `+ + 'velocity and the Canvas pixelsPerUnit.');+}+/*** Register the character-controller system. Runs in FixedUpdate ahead of the* physics step so the resolved Transform is what gets pushed into a kinematic body.@@ -281,6 +299,7 @@ function moverCapsuleFromShape(s: CastShape): MoverCapsule {* resting on the ground with valid contact normals instead of wedging on it.*/export function registerCharacterControllerSystem(app: App): void {+ warnedNonFiniteMove = false;app.addSystemToSchedule(Schedule.FixedUpdate,defineSystem(@@ -293,6 +312,9 @@ export function registerCharacterControllerSystem(app: App): void {) => {const dt = time.fixedDelta;if (dt <= 0) return;+ // Push before reading: this runs ahead of PhysicsStepSystem, the other+ // caller, so on the first fixed step nobody has pushed one yet.+ physics.setPixelsPerUnit(readPixelsPerUnit(app));const ppu = physics.getPixelsPerUnit();const invDt = 1 / dt;@@ -316,6 +338,10 @@ export function registerCharacterControllerSystem(app: App): void {ppu,);if (!r) continue;+ // A non-finite move is not survivable: the next move starts from the+ // position this writes, so one NaN frame kills the character for the+ // session. Keep the last good pose and say so once.+ if (!isFiniteMove(r)) { warnNonFiniteMove(entity, ppu, dt); continue; }// Write both local and world position: PhysicsStepSystem runs next// in this same FixedUpdate and pushes worldPosition into a kinematicdiff --git a/sdk/src/physics/Physics.ts b/sdk/src/physics/Physics.tsindex 390f2f4af..eda8111f8 100644--- a/sdk/src/physics/Physics.ts+++ b/sdk/src/physics/Physics.ts@@ -28,6 +28,9 @@ import {// Physics API Helper// =============================================================================+/** World pixels per Box2D meter, until a Canvas says otherwise. */+const DEFAULT_PIXELS_PER_UNIT = 100;+/*** Unit contract: Box2D simulates in meters; the engine converts at the* pixels-per-unit (PPU) boundary. Spatial *queries* (`raycast` / `shapeCast` /@@ -37,14 +40,24 @@ import {* component dimensions. Convert with {@link getPixelsPerUnit} when mixing the two.*/export class PhysicsAPI {- private module_: PhysicsWasmModule;+ private module_!: PhysicsWasmModule;// Live pixels-per-unit, pushed each frame by PhysicsSystem from the Canvas, so// a query that omits `ppu` is scaled correctly instead of silently assuming 100.- private ppu_ = 100;+ private ppu_!: number;++ /**+ * Starting state for both construction paths. `_fromModule` uses `Object.create`,+ * which runs no field initializer — a default declared as `ppu_ = 100` would be+ * `undefined` there.+ */+ private init_(module: PhysicsWasmModule): void {+ this.module_ = module;+ this.ppu_ = DEFAULT_PIXELS_PER_UNIT;+ }/** @internal Update the pixels-per-unit used to scale queries by default. */setPixelsPerUnit(ppu: number): void {- if (ppu > 0) this.ppu_ = ppu;+ if (Number.isFinite(ppu) && ppu > 0) this.ppu_ = ppu;}/**@@ -63,13 +76,13 @@ export class PhysicsAPI {if (!module) {throw new Error('Physics module not loaded. Ensure PhysicsPlugin init is complete.');}- this.module_ = module;+ this.init_(module);}/** @internal */static _fromModule(module: PhysicsWasmModule): PhysicsAPI {const instance = Object.create(PhysicsAPI.prototype) as PhysicsAPI;- instance.module_ = module;+ instance.init_(module);return instance;}diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.tsindex 16a63da8b..ee1b3bd5c 100644--- a/sdk/src/physics/PhysicsSystem.ts+++ b/sdk/src/physics/PhysicsSystem.ts@@ -56,7 +56,8 @@ type PhysicsEngineApi = EngineApi & {// Canvas pixelsPerUnit live read// =============================================================================-function readPixelsPerUnit(app: App): number {+/** The scene's live pixels-per-unit — the one reader of Canvas.pixelsPerUnit. @internal */+export function readPixelsPerUnit(app: App): number {const entities = app.world.getEntitiesWithComponents([Canvas]);for (const entity of entities) {const canvas = app.world.get(entity, Canvas) as CanvasData;diff --git a/sdk/tests/physics-pixels-per-unit.test.ts b/sdk/tests/physics-pixels-per-unit.test.tsnew file mode 100644index 000000000..3caec2808--- /dev/null+++ b/sdk/tests/physics-pixels-per-unit.test.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A PhysicsAPI answers with a usable pixels-per-unit before anyone pushes one.+ *+ * `_fromModule` builds the instance with `Object.create`, which runs no field+ * initializer. The default lived in one, so the published `Physics` resource+ * answered `undefined`, and `1 / undefined` is NaN — the character controller+ * reads it one system before `PhysicsStepSystem` pushes the Canvas value, so its+ * first move wrote a NaN Transform that every later move started from.+ */+import { describe, it, expect } from 'vitest';+import { PhysicsAPI } from '../src/physics/Physics';+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';++const fakeModule = () => ({}) as unknown as PhysicsWasmModule;++describe('PhysicsAPI pixels-per-unit', () => {+ it('is finite and positive on a _fromModule instance, before any push', () => {+ const ppu = PhysicsAPI._fromModule(fakeModule()).getPixelsPerUnit();+ expect(Number.isFinite(ppu)).toBe(true);+ expect(ppu).toBeGreaterThan(0);+ });++ it('takes the pushed value', () => {+ const api = PhysicsAPI._fromModule(fakeModule());+ api.setPixelsPerUnit(1);+ expect(api.getPixelsPerUnit()).toBe(1);+ });++ it('keeps the last good value when pushed a non-finite or non-positive one', () => {+ const api = PhysicsAPI._fromModule(fakeModule());+ api.setPixelsPerUnit(64);+ for (const bad of [NaN, Infinity, 0, -1, undefined as unknown as number]) {+ api.setPixelsPerUnit(bad);+ expect(api.getPixelsPerUnit()).toBe(64);+ }+ });+});