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(physics): synchronize static body transforms in place

yhh2027aca55827
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9849f2e51..43a3505cf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Fixed
+- **Static 2D bodies follow authored transforms and parent movement.** Box2D updates changed static poses in place, preserving bodies and shapes without repeating writes for unchanged poses. Initial body creation composes the hierarchy first, and parented static bodies no longer force dynamic-body writeback out of its batch path.
+
- **Recreated tilemap layers discard old geometry and collision.** A layer generation distinguishes replacement from ordinary edits, even when the same entity and edit count are reused. Reinitializing or immediately recreating a layer releases its old chunk meshes and rebuilds collision from the replacement; unchanged layers retain their caches.
- **Tilemap runtimes and saved chunks stay with their own worlds.** Closing a preview or an older App no longer destroys another core's same-numbered layers or disables its collision updates. Scene codecs serialize each world's own tiles; closing the current runtime restores the previous live tooling interface and collision lookup, and releases the retired codec.
diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.ts
index 042f377bb..2772468fd 100644
--- a/sdk/src/physics/PhysicsSystem.ts
+++ b/sdk/src/physics/PhysicsSystem.ts
@@ -699,9 +699,14 @@ export function registerPhysics2DSystem(
const physicsComponents = [RigidBody2D, ...COLLIDER_TYPES, ...JOINT_TYPES, OneWayPlatform2D];
for (const c of physicsComponents) app.world.enableChangeTracking(c);
const kinematicEntities = new Set<Entity>();
+ const staticPoses = new Map<Entity, { x: number; y: number; angle: number; parented: boolean }>();
+ let lastStaticEpoch = -1;
+ let lastStaticTick = -1;
+ let lastStaticPpu = -1;
let lastStructuralVersion = -1;
const world = app.world;
+ world.enableChangeTracking(Transform);
world.onDespawn((entity: Entity) => {
if (trackedJoints.has(entity)) {
@@ -718,6 +723,7 @@ export function registerPhysics2DSystem(
cachedProps.delete(entity);
parentedBodies.delete(entity);
kinematicEntities.delete(entity);
+ staticPoses.delete(entity);
// The module's pose snapshots need no cleanup: destroying the body drops
// it from the dynamic set the next capture rebuilds from, and the lerp is
// driven by the current snapshot, so a stale `prev` entry is never read.
@@ -758,6 +764,7 @@ export function registerPhysics2DSystem(
}
}
if (needReconcile) {
+ world.ensureTransformsComposed();
const entities = world.getEntitiesWithComponents([RigidBody2D, Transform]);
const currentEntities = new Set<Entity>();
@@ -786,7 +793,7 @@ export function registerPhysics2DSystem(
);
addShapeForEntity(world, module, entity, config.collisionLayerMasks);
trackedEntities.add(entity);
- if (hasParent) parentedBodies.add(entity);
+ if (hasParent && rb.bodyType !== BodyType.Static) parentedBodies.add(entity);
cachedProps.set(entity, {
bodyType: rb.bodyType,
gravityScale: rb.gravityScale,
@@ -798,6 +805,10 @@ export function registerPhysics2DSystem(
colliderSig: colliderSignature(world, entity),
});
if (rb.bodyType === BodyType.Kinematic) kinematicEntities.add(entity);
+ if (rb.bodyType === BodyType.Static) {
+ staticPoses.set(entity, { x: posX * invPpu, y: posY * invPpu,
+ angle: quatToAngleZ(rot), parented: hasParent });
+ }
continue;
}
@@ -845,6 +856,13 @@ export function registerPhysics2DSystem(
// skipped frames.
if (cached.bodyType === BodyType.Kinematic) kinematicEntities.add(entity);
else kinematicEntities.delete(entity);
+ if (cached.bodyType === BodyType.Static) {
+ const parented = world.has(entity, Parent);
+ const pose = staticPoses.get(entity);
+ if (pose) pose.parented = parented;
+ else staticPoses.set(entity, { x: NaN, y: NaN, angle: NaN, parented });
+ parentedBodies.delete(entity);
+ } else staticPoses.delete(entity);
}
// Activity filtering removes descendants from the query too.
@@ -865,6 +883,7 @@ export function registerPhysics2DSystem(
cachedProps.delete(entity);
parentedBodies.delete(entity);
kinematicEntities.delete(entity);
+ staticPoses.delete(entity);
}
}
@@ -885,6 +904,31 @@ export function registerPhysics2DSystem(
lastStructuralVersion = structuralVersion;
} // end if (needReconcile)
+ const staticEpoch = world.transformEpoch();
+ if (staticPoses.size > 0 && (needReconcile || staticEpoch < 0
+ || staticEpoch !== lastStaticEpoch || ppu !== lastStaticPpu)) {
+ world.ensureTransformsComposed();
+ for (const [entity, pose] of staticPoses) {
+ if (!cachedProps.get(entity)?.enabled) continue;
+ const hasParent = pose.parented;
+ if (!hasParent && !needReconcile && ppu === lastStaticPpu
+ && !world.isChangedSince(entity, Transform, lastStaticTick)) continue;
+ if (!world.isEntityActive(entity)) continue;
+ const tf = world.get(entity, Transform) as TransformData;
+ const position = hasParent ? tf.worldPosition : tf.position;
+ const rotation = hasParent ? tf.worldRotation : tf.rotation;
+ const x = position.x * invPpu, y = position.y * invPpu;
+ const angle = quatToAngleZ(rotation);
+ if (pose.x !== x || pose.y !== y || pose.angle !== angle) {
+ module._physics_setBodyTransform(entity, x, y, angle);
+ pose.x = x; pose.y = y; pose.angle = angle;
+ }
+ }
+ }
+ lastStaticEpoch = world.transformEpoch();
+ lastStaticTick = world.getWorldTick() - 1;
+ lastStaticPpu = ppu;
+
// Kinematic bodies are driven by their Transform (changed via gameplay,
// not tracked as a physics edit) — push every step, even when the
// reconcile above was skipped. Drive them toward the target over the
@@ -917,7 +961,9 @@ export function registerPhysics2DSystem(
// every body every step.
if (needReconcile) {
for (const entity of trackedEntities) {
- if (world.has(entity, Parent)) parentedBodies.add(entity);
+ if (cachedProps.get(entity)?.bodyType !== BodyType.Static && world.has(entity, Parent)) {
+ parentedBodies.add(entity);
+ }
else parentedBodies.delete(entity);
}
}
diff --git a/sdk/tests/physics-static-transform-wasm.test.ts b/sdk/tests/physics-static-transform-wasm.test.ts
new file mode 100644
index 000000000..9f13f1322
--- /dev/null
+++ b/sdk/tests/physics-static-transform-wasm.test.ts
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import { App } from '../src/app/app';
+import { Transform } from '../src/ecs/component';
+import { Physics2DPlugin } from '../src/physics/Physics2DPlugin';
+import { Physics2DRuntime } from '../src/physics/Physics2DRuntime';
+import { Physics2D } from '../src/physics/Physics2D';
+import { RigidBody2D, BoxCollider2D, BodyType } from '../src/physics/PhysicsComponents';
+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';
+import type { ESEngineModule } from '../src/wasm';
+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';
+
+let engine: ESEngineModule;
+const apps: App[] = [];
+afterEach(() => { for (const app of apps.splice(0)) app.quit(); vi.restoreAllMocks(); });
+describe.skipIf(!HAS_WASM || !hasSideModule('physics'))('static Box2D transform projection', () => {
+ beforeAll(async () => { engine = await loadWasmModule(); });
+ it.each([false, true])('moves a static body in place without repeated writes (parented=%s)', async parented => {
+ const app = App.new(); apps.push(app);
+ app.connectCpp(new engine.Registry(), engine, { ownedRegistry: true });
+ const module = await loadSideModule<PhysicsWasmModule>('physics');
+ app.addPlugin(new Physics2DPlugin('', { gravity: { x: 0, y: 0 } }, async () => module));
+ await app.getResource(Physics2DRuntime).initPromise;
+ const world = app.world, body = world.spawn();
+ world.insert(body, Transform, { position: { x: 5, y: 0, z: 0 } });
+ world.insert(body, RigidBody2D, { bodyType: BodyType.Static });
+ world.insert(body, BoxCollider2D, { halfExtents: { x: .1, y: .1 } });
+ const driver = parented ? world.spawn() : body;
+ if (parented) { world.insert(driver, Transform, {}); world.setParent(body, driver); }
+ const move = vi.spyOn(module, '_physics_setBodyTransform');
+ const create = vi.spyOn(module, '_physics_createBody');
+ await app.stepFrames(2, 1 / 30);
+ const api = app.getResource(Physics2D);
+ const hit = () => api.raycast({ x: -50, y: 0 }, { x: 1, y: 0 }, 200).find(value => value.entity === body)!;
+ const before = hit().point.x;
+ world.update(driver, Transform, value => { value.position.x += 30; });
+ await app.stepFrames(2, 1 / 30);
+ expect(hit().point.x).toBeCloseTo(before + 30, 3);
+ expect(create).toHaveBeenCalledTimes(1);
+ expect(move.mock.calls).toHaveLength(1);
+ move.mockClear();
+ await app.stepFrames(20, 1 / 30);
+ expect(move).not.toHaveBeenCalled();
+ expect(module._physics_hasBody(body)).toBe(1);
+ });
+ it('keeps batched dynamic writeback when static bodies have parents', async () => {
+ const app = App.new(); apps.push(app);
+ app.connectCpp(new engine.Registry(), engine, { ownedRegistry: true });
+ const module = await loadSideModule<PhysicsWasmModule>('physics');
+ app.addPlugin(new Physics2DPlugin('', { gravity: { x: 0, y: 0 } }, async () => module));
+ await app.getResource(Physics2DRuntime).initPromise;
+ const parent = app.world.spawn(); app.world.insert(parent, Transform);
+ const platform = app.world.spawn(); app.world.insert(platform, Transform);
+ app.world.insert(platform, RigidBody2D, { bodyType: BodyType.Static });
+ app.world.insert(platform, BoxCollider2D, {}); app.world.setParent(platform, parent);
+ const dynamic = app.world.spawn();
+ app.world.insert(dynamic, Transform, { position: { x: 100, y: 100, z: 0 } });
+ app.world.insert(dynamic, RigidBody2D, { bodyType: BodyType.Dynamic });
+ app.world.insert(dynamic, BoxCollider2D, {});
+ const batch = vi.spyOn(engine, 'registry_batchSyncPhysicsTransforms');
+ await app.stepFrames(2, 1 / 30);
+ expect(batch).toHaveBeenCalled();
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 3d6eca146..f6e4fa200 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'fix(physics): synchronize static body transforms in place':
+ { note: 'Static 2D bodies follow authored transforms and parent movement.' },
'fix(tilemap): invalidate caches when a layer is recreated':
{ note: 'Recreated tilemap layers discard old geometry and collision.' },
'fix(tilemap): isolate runtime tools and scene codecs per world':