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): a collider switched off was still solid
esenginea545bd743037
diff --git a/docs/astro/src/content/docs/gameplay/physics.mdx b/docs/astro/src/content/docs/gameplay/physics.mdxindex af9e292c0..0a077c7af 100644--- a/docs/astro/src/content/docs/gameplay/physics.mdx+++ b/docs/astro/src/content/docs/gameplay/physics.mdx@@ -107,7 +107,7 @@ are in meters.| `isSensor` | boolean | `false` | Detect overlaps without a physical response (triggers). || `categoryBits` | number | `0x0001` | Which collision layer this collider is on. || `maskBits` | number | `0xFFFF` | Which layers it collides with. |-| `enabled` | boolean | `true` | Disable the shape. |+| `enabled` | boolean | `true` | Disable the shape. The body keeps its velocity, joints and other colliders; this one stops existing — nothing collides with it, and no query, raycast or character cast finds it. || Component | Shape parameters ||---|---|diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdxindex 2b741ec15..6be9bbbcd 100644--- a/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx+++ b/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx@@ -99,7 +99,7 @@ const spawnBall = defineSystem([Commands()], (cmds) => {| `isSensor` | boolean | `false` | 检测重叠但无物理响应(触发器)。 || `categoryBits` | number | `0x0001` | 该碰撞体所在的碰撞层。 || `maskBits` | number | `0xFFFF` | 它与哪些层碰撞。 |-| `enabled` | boolean | `true` | 关掉该形状。 |+| `enabled` | boolean | `true` | 关掉该形状。刚体的速度、关节和其它碰撞体都留着,只有这一个不再存在——没有东西会撞上它,查询、射线和角色控制器的扫掠也都找不到它。 || 组件 | 形状参数 ||---|---|diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex bd0862580..b39146f6f 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1659,6 +1659,7 @@ Nothing = 0## ColliderInstance — interface```+enabled: booleanisSensor: booleanshape: ColliderShape```diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 03e03064e..fe7c800e1 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1659,6 +1659,7 @@ Nothing = 0## ColliderInstance — interface```+enabled: booleanisSensor: booleanshape: ColliderShape```diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex c78068d0c..d14a61a76 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1654,6 +1654,7 @@ Nothing = 0## ColliderInstance — interface```+enabled: booleanisSensor: booleanshape: ColliderShape```diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 4c9fc727c..3a5072e29 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1654,6 +1654,7 @@ Nothing = 0## ColliderInstance — interface```+enabled: booleanisSensor: booleanshape: ColliderShape```diff --git a/sdk/etc/physics.api.md b/sdk/etc/physics.api.mdindex e26e24d1e..221460223 100644--- a/sdk/etc/physics.api.md+++ b/sdk/etc/physics.api.md@@ -111,6 +111,7 @@ restitution: number## ColliderInstance — interface```+enabled: booleanisSensor: booleanshape: ColliderShape```diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 4812aad0d..30a9cc069 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1654,6 +1654,7 @@ Nothing = 0## ColliderInstance — interface```+enabled: booleanisSensor: booleanshape: ColliderShape```diff --git a/sdk/src/physics/CharacterController.ts b/sdk/src/physics/CharacterController.tsindex 3497f2851..153c29bb3 100644--- a/sdk/src/physics/CharacterController.ts+++ b/sdk/src/physics/CharacterController.ts@@ -29,7 +29,7 @@ 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 { BoxCollider, CircleCollider, CapsuleCollider, activeCollider } from './PhysicsComponents';import { log } from '../util/logger';import type {BoxColliderData, CircleColliderData, CapsuleColliderData,@@ -239,19 +239,20 @@ type CastShape =| { kind: 'circle'; r: number; ox: number; oy: number }| { kind: 'capsule'; r: number; halfH: number; ox: number; oy: number };-/** Read the entity's collider into a pixel-space cast shape, or null if it has none. */+/** Read the entity's collider into a pixel-space cast shape, or null if it has no+ * enabled one — a disabled collider is no collider, here as everywhere. */function resolveCastShape(world: World, entity: Entity, ppu: number): CastShape | null {- if (world.has(entity, BoxCollider)) {- const c = world.get(entity, BoxCollider) as BoxColliderData;- return { kind: 'box', hx: c.halfExtents.x * ppu, hy: c.halfExtents.y * ppu, ox: c.offset.x * ppu, oy: c.offset.y * ppu };+ const box = activeCollider(world, entity, BoxCollider) as BoxColliderData | null;+ if (box) {+ return { kind: 'box', hx: box.halfExtents.x * ppu, hy: box.halfExtents.y * ppu, ox: box.offset.x * ppu, oy: box.offset.y * ppu };}- if (world.has(entity, CircleCollider)) {- const c = world.get(entity, CircleCollider) as CircleColliderData;- return { kind: 'circle', r: c.radius * ppu, ox: c.offset.x * ppu, oy: c.offset.y * ppu };+ const circle = activeCollider(world, entity, CircleCollider) as CircleColliderData | null;+ if (circle) {+ return { kind: 'circle', r: circle.radius * ppu, ox: circle.offset.x * ppu, oy: circle.offset.y * ppu };}- if (world.has(entity, CapsuleCollider)) {- const c = world.get(entity, CapsuleCollider) as CapsuleColliderData;- return { kind: 'capsule', r: c.radius * ppu, halfH: c.halfHeight * ppu, ox: c.offset.x * ppu, oy: c.offset.y * ppu };+ const capsule = activeCollider(world, entity, CapsuleCollider) as CapsuleColliderData | null;+ if (capsule) {+ return { kind: 'capsule', r: capsule.radius * ppu, halfH: capsule.halfHeight * ppu, ox: capsule.offset.x * ppu, oy: capsule.offset.y * ppu };}return null;}diff --git a/sdk/src/physics/ColliderShape.ts b/sdk/src/physics/ColliderShape.tsindex 54e8a6453..20c55f861 100644--- a/sdk/src/physics/ColliderShape.ts+++ b/sdk/src/physics/ColliderShape.ts@@ -37,10 +37,14 @@ export type ColliderShape =| { kind: 'polygon'; vertices: Vec2[] }| { kind: 'chain'; points: Vec2[]; isLoop: boolean };-/** A shape read off an entity, with the sensor flag the visualizers colour by. */+/** A shape read off an entity, with the sensor flag the visualizers colour by and+ * the enabled flag they decide by: a disabled collider is absent from the physics+ * world, so the runtime overlay skips it while the editor keeps drawing it (you+ * still author its geometry through the gizmo). */export interface ColliderInstance {shape: ColliderShape;isSensor: boolean;+ enabled: boolean;}/** World-space (pixel) outline: straight runs as polylines + true circles left as@@ -134,29 +138,30 @@ export function colliderShapeOutline(shape: ColliderShape, center: Vec2, angle:*/export function readColliderShapes(world: World, entity: number): ColliderInstance[] {const out: ColliderInstance[] = [];+ const isEnabled = (c: { enabled?: boolean }): boolean => c.enabled !== false;if (world.has(entity, BoxCollider)) {const b = world.get(entity, BoxCollider) as BoxColliderData;- out.push({ shape: { kind: 'box', halfExtents: b.halfExtents, offset: b.offset }, isSensor: b.isSensor });+ out.push({ shape: { kind: 'box', halfExtents: b.halfExtents, offset: b.offset }, isSensor: b.isSensor, enabled: isEnabled(b) });}if (world.has(entity, CircleCollider)) {const c = world.get(entity, CircleCollider) as CircleColliderData;- out.push({ shape: { kind: 'circle', radius: c.radius, offset: c.offset }, isSensor: c.isSensor });+ out.push({ shape: { kind: 'circle', radius: c.radius, offset: c.offset }, isSensor: c.isSensor, enabled: isEnabled(c) });}if (world.has(entity, CapsuleCollider)) {const c = world.get(entity, CapsuleCollider) as CapsuleColliderData;- out.push({ shape: { kind: 'capsule', radius: c.radius, halfHeight: c.halfHeight, offset: c.offset }, isSensor: c.isSensor });+ out.push({ shape: { kind: 'capsule', radius: c.radius, halfHeight: c.halfHeight, offset: c.offset }, isSensor: c.isSensor, enabled: isEnabled(c) });}if (world.has(entity, SegmentCollider)) {const s = world.get(entity, SegmentCollider) as SegmentColliderData;- out.push({ shape: { kind: 'segment', point1: s.point1, point2: s.point2 }, isSensor: s.isSensor });+ out.push({ shape: { kind: 'segment', point1: s.point1, point2: s.point2 }, isSensor: s.isSensor, enabled: isEnabled(s) });}if (world.has(entity, PolygonCollider)) {const p = world.get(entity, PolygonCollider) as PolygonColliderData;- out.push({ shape: { kind: 'polygon', vertices: p.vertices }, isSensor: p.isSensor });+ out.push({ shape: { kind: 'polygon', vertices: p.vertices }, isSensor: p.isSensor, enabled: isEnabled(p) });}if (world.has(entity, ChainCollider)) {const c = world.get(entity, ChainCollider) as ChainColliderData;- out.push({ shape: { kind: 'chain', points: c.points, isLoop: c.isLoop }, isSensor: false });+ out.push({ shape: { kind: 'chain', points: c.points, isLoop: c.isLoop }, isSensor: false, enabled: isEnabled(c) });}return out;}diff --git a/sdk/src/physics/PhysicsComponents.ts b/sdk/src/physics/PhysicsComponents.tsindex fca313697..7b1008421 100644--- a/sdk/src/physics/PhysicsComponents.ts+++ b/sdk/src/physics/PhysicsComponents.ts@@ -5,8 +5,10 @@* @brief Physics component definitions for TypeScript SDK*/-import type { Vec2 } from '../types';+import type { Entity, Vec2 } from '../types';+import type { AnyComponentDef, ComponentData } from '../ecs/component';import { defineBuiltin, defineComponent } from '../ecs/component';+import type { World } from '../ecs/world';// Box2D collision filtering: a body's own layers (category) and the layers it// collides with (mask), as named bitmasks. Bit labels come from the project's@@ -214,6 +216,24 @@ export const ChainCollider = defineComponent<ChainColliderData>('ChainCollider',enabled: true,}, { fields: { ...COLLISION_FILTER_META } });+// =============================================================================+// Collider Reads+// =============================================================================++/**+ * The collider's data, or null when the component is absent **or disabled** — a+ * disabled collider is equivalent to an absent one (no Box2D shape, nothing to+ * cast against, no debug outline), and every consumer reads it through here so+ * those answers agree. Data predating the field has no `enabled`, and stays solid.+ */+export function activeCollider<C extends AnyComponentDef>(+ world: World, entity: Entity, collider: C,+): ComponentData<C> | null {+ if (!world.has(entity, collider)) return null;+ const data = world.get(entity, collider);+ return (data as { enabled?: boolean }).enabled === false ? null : data;+}+// =============================================================================// One-Way (One-Sided) Platform// =============================================================================diff --git a/sdk/src/physics/PhysicsDebugDraw.ts b/sdk/src/physics/PhysicsDebugDraw.tsindex 8fc857349..6cc678759 100644--- a/sdk/src/physics/PhysicsDebugDraw.ts+++ b/sdk/src/physics/PhysicsDebugDraw.ts@@ -120,7 +120,8 @@ export function drawPhysicsDebug(// One projection for every shape: read the collider(s), take the offset+rotation// centre, and stroke the world-space outline. Same geometry the per-type branches// produced, now shared with the editor gizmo (see ColliderShape).- for (const { shape, isSensor } of readColliderShapes(app.world, entity)) {+ for (const { shape, isSensor, enabled } of readColliderShapes(app.world, entity)) {+ if (!enabled) continue; // no shape in the world → nothing to outlineconst color = isSensor ? SENSOR_COLOR : bodyTypeColor(rb.bodyType);const center = shapeCenter(shape, { x: wx, y: wy }, angle, ppu);const outline = colliderShapeOutline(shape, center, angle, ppu);diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.tsindex ee1b3bd5c..25f44bc54 100644--- a/sdk/src/physics/PhysicsSystem.ts+++ b/sdk/src/physics/PhysicsSystem.ts@@ -23,7 +23,7 @@ import {RigidBody, BoxCollider, CircleCollider, CapsuleCollider,SegmentCollider, PolygonCollider, ChainCollider, OneWayPlatform,RevoluteJoint, DistanceJoint, PrismaticJoint, WeldJoint, WheelJoint, MotorJoint,- BodyType,+ BodyType, activeCollider,type RigidBodyData, type BoxColliderData, type CircleColliderData,type CapsuleColliderData, type SegmentColliderData, type PolygonColliderData,type ChainColliderData, type OneWayPlatformData, type RevoluteJointData,@@ -86,11 +86,12 @@ function resolveCollisionMask(categoryBits: number, maskBits: number, layerMasks// Shape attachment (one collider component per body)// =============================================================================-function addShapeForEntity(app: App, module: PhysicsWasmModule, entity: Entity, layerMasks?: number[]): void {- const world = app.world;-- if (world.has(entity, BoxCollider)) {- const box = world.get(entity, BoxCollider) as BoxColliderData;+/** Attach a Box2D shape for each enabled collider on the entity. @internal */+export function addShapeForEntity(+ world: App['world'], module: PhysicsWasmModule, entity: Entity, layerMasks?: number[],+): void {+ const box = activeCollider(world, entity, BoxCollider) as BoxColliderData | null;+ if (box) {const category = box.categoryBits ?? 0x0001;const mask = resolveCollisionMask(category, box.maskBits ?? 0xFFFF, layerMasks);module._physics_addBoxShape(@@ -101,8 +102,8 @@ function addShapeForEntity(app: App, module: PhysicsWasmModule, entity: Entity,);}- if (world.has(entity, CircleCollider)) {- const circle = world.get(entity, CircleCollider) as CircleColliderData;+ const circle = activeCollider(world, entity, CircleCollider) as CircleColliderData | null;+ if (circle) {const category = circle.categoryBits ?? 0x0001;const mask = resolveCollisionMask(category, circle.maskBits ?? 0xFFFF, layerMasks);module._physics_addCircleShape(@@ -113,8 +114,8 @@ function addShapeForEntity(app: App, module: PhysicsWasmModule, entity: Entity,);}- if (world.has(entity, CapsuleCollider)) {- const capsule = world.get(entity, CapsuleCollider) as CapsuleColliderData;+ const capsule = activeCollider(world, entity, CapsuleCollider) as CapsuleColliderData | null;+ if (capsule) {const category = capsule.categoryBits ?? 0x0001;const mask = resolveCollisionMask(category, capsule.maskBits ?? 0xFFFF, layerMasks);module._physics_addCapsuleShape(@@ -125,8 +126,8 @@ function addShapeForEntity(app: App, module: PhysicsWasmModule, entity: Entity,);}- if (world.has(entity, SegmentCollider)) {- const seg = world.get(entity, SegmentCollider) as SegmentColliderData;+ const seg = activeCollider(world, entity, SegmentCollider) as SegmentColliderData | null;+ if (seg) {const category = seg.categoryBits ?? 0x0001;const mask = resolveCollisionMask(category, seg.maskBits ?? 0xFFFF, layerMasks);module._physics_addSegmentShape(@@ -136,8 +137,8 @@ function addShapeForEntity(app: App, module: PhysicsWasmModule, entity: Entity,);}- if (world.has(entity, PolygonCollider)) {- const poly = world.get(entity, PolygonCollider) as PolygonColliderData;+ const poly = activeCollider(world, entity, PolygonCollider) as PolygonColliderData | null;+ if (poly) {const category = poly.categoryBits ?? 0x0001;const mask = resolveCollisionMask(category, poly.maskBits ?? 0xFFFF, layerMasks);const verts = poly.vertices;@@ -157,8 +158,8 @@ function addShapeForEntity(app: App, module: PhysicsWasmModule, entity: Entity,});}- if (world.has(entity, ChainCollider)) {- const chain = world.get(entity, ChainCollider) as ChainColliderData;+ const chain = activeCollider(world, entity, ChainCollider) as ChainColliderData | null;+ if (chain) {const pts = chain.points;if (pts.length < 4) return;const byteSize = pts.length * 2 * 4;@@ -626,8 +627,8 @@ export function colliderSignature(world: App['world'], entity: Entity): number {return sig;}-/** True if any present collider component changed since `sinceTick`. */-function collidersChangedSince(world: App['world'], entity: Entity, sinceTick: number): boolean {+/** True if any present collider component changed since `sinceTick`. @internal */+export function collidersChangedSince(world: App['world'], entity: Entity, sinceTick: number): boolean {for (const C of COLLIDER_TYPES) {if (world.has(entity, C) && world.isChangedSince(entity, C, sinceTick)) return true;}@@ -780,7 +781,7 @@ export function registerPhysicsSystem(rb.gravityScale, rb.linearDamping, rb.angularDamping,rb.fixedRotation ? 1 : 0, rb.bullet ? 1 : 0,);- addShapeForEntity(app, module, entity, config.collisionLayerMasks);+ addShapeForEntity(world, module, entity, config.collisionLayerMasks);trackedEntities.add(entity);if (hasParent) parentedBodies.add(entity);cachedProps.set(entity, {@@ -832,7 +833,7 @@ export function registerPhysicsSystem(if (sig !== cached.colliderSig ||collidersChangedSince(world, entity, lastEntitySyncTick)) {module._physics_clearShapes(entity);- addShapeForEntity(app, module, entity, config.collisionLayerMasks);+ addShapeForEntity(world, module, entity, config.collisionLayerMasks);cached.colliderSig = sig;}diff --git a/sdk/tests/colliderEnabled.test.ts b/sdk/tests/colliderEnabled.test.tsnew file mode 100644index 000000000..079d3d136--- /dev/null+++ b/sdk/tests/colliderEnabled.test.ts@@ -0,0 +1,123 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A collider's `enabled` flag gates its Box2D shape.+ *+ * The field is authored in the inspector and documented as "disable the+ * shape", but the shape attach re-added every collider unconditionally,+ * so a platform switched off stayed solid — against bodies and against+ * the character controller's mover alike.+ */+import { describe, it, expect } from 'vitest';+import { World } from '../src/ecs/world';+import { createMockModule } from './mocks/wasm';+import {+ BoxCollider, CircleCollider, CapsuleCollider,+ SegmentCollider, PolygonCollider, ChainCollider,+} from '../src/physics/PhysicsComponents';+import { addShapeForEntity, collidersChangedSince } from '../src/physics/PhysicsSystem';+import { readColliderShapes } from '../src/physics/ColliderShape';+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';++function testWorld(): World {+ const mod = createMockModule();+ const world = new World();+ world.connectCpp(mod.getRegistry(), mod);+ return world;+}++/** A physics module that records which shapes were attached, and nothing else. */+function recordingModule(): { shapes: string[]; module: PhysicsWasmModule } {+ const shapes: string[] = [];+ const heap = new Float32Array(64);+ const module = {+ _malloc: () => 0,+ _free: () => {},+ HEAPF32: heap,+ _physics_addBoxShape: () => shapes.push('box'),+ _physics_addCircleShape: () => shapes.push('circle'),+ _physics_addCapsuleShape: () => shapes.push('capsule'),+ _physics_addSegmentShape: () => shapes.push('segment'),+ _physics_addPolygonShape: () => shapes.push('polygon'),+ _physics_addChainShape: () => shapes.push('chain'),+ };+ return { shapes, module: module as unknown as PhysicsWasmModule };+}++const COLLIDERS = [+ { name: 'box', component: BoxCollider },+ { name: 'circle', component: CircleCollider },+ { name: 'capsule', component: CapsuleCollider },+ { name: 'segment', component: SegmentCollider },+ { name: 'polygon', component: PolygonCollider },+ { name: 'chain', component: ChainCollider },+] as const;++describe('addShapeForEntity honours collider.enabled', () => {+ for (const { name, component } of COLLIDERS) {+ it(`attaches a ${name} shape while it is enabled`, () => {+ const world = testWorld();+ const { shapes, module } = recordingModule();+ const e = world.spawn();+ world.insert(e, component, {} as never);+ addShapeForEntity(world, module, e);+ expect(shapes).toEqual([name]);+ });++ it(`attaches no ${name} shape once it is disabled`, () => {+ const world = testWorld();+ const { shapes, module } = recordingModule();+ const e = world.spawn();+ world.insert(e, component, { enabled: false } as never);+ addShapeForEntity(world, module, e);+ expect(shapes).toEqual([]);+ });+ }++ it('takes away only the disabled collider, not the others on the body', () => {+ const world = testWorld();+ const { shapes, module } = recordingModule();+ const e = world.spawn();+ world.insert(e, BoxCollider, { enabled: false } as never);+ world.insert(e, CircleCollider, {} as never);+ addShapeForEntity(world, module, e);+ expect(shapes).toEqual(['circle']);+ });++ it('keeps a collider stored before the flag existed solid', () => {+ const world = testWorld();+ const { shapes, module } = recordingModule();+ const e = world.spawn();+ world.insert(e, BoxCollider, {} as never);+ const legacy = { ...world.get(e, BoxCollider) } as Record<string, unknown>;+ delete legacy.enabled;+ world.set(e, BoxCollider, legacy as never);+ addShapeForEntity(world, module, e);+ expect(shapes).toEqual(['box']);+ });+});++describe('the rest of the engine agrees with the shape that is there', () => {+ it('reports the flag to the visualizers, so the debug overlay can skip it', () => {+ const world = testWorld();+ const e = world.spawn();+ world.insert(e, BoxCollider, { enabled: false } as never);+ world.insert(e, CircleCollider, {} as never);+ const [box, circle] = readColliderShapes(world, e);+ expect(box.enabled).toBe(false);+ expect(circle.enabled).toBe(true);+ });++ it('marks the collider changed when the flag flips, which is what rebuilds the shapes', () => {+ const world = testWorld();+ world.enableChangeTracking(BoxCollider); // registerPhysicsSystem does this+ const e = world.spawn();+ world.insert(e, BoxCollider, {} as never);+ const settled = world.getWorldTick();+ expect(collidersChangedSince(world, e, settled)).toBe(false);++ world.advanceTick(); // next frame: the game turns the platform off+ world.set(e, BoxCollider, { ...world.get(e, BoxCollider), enabled: false });+ expect(collidersChangedSince(world, e, settled)).toBe(true);+ });+});