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.

feat(physics): one-way platforms + motor & mouse (drag) joints

yhh7acd8583f0bc
diff --git a/docs/astro/src/content/docs/guides/physics.mdx b/docs/astro/src/content/docs/guides/physics.mdx
index dff516267..24019ef2e 100644
--- a/docs/astro/src/content/docs/guides/physics.mdx
+++ b/docs/astro/src/content/docs/guides/physics.mdx
@@ -189,8 +189,8 @@ const onHit = defineSystem([Res(PhysicsEvents)], (events) => {
## Joints
Connect two bodies. Add a joint **component** (`RevoluteJoint`, `DistanceJoint`,
-`PrismaticJoint`, `WeldJoint`, `WheelJoint`), or create one imperatively and drive
-its motor / limits:
+`PrismaticJoint`, `WeldJoint`, `WheelJoint`, `MotorJoint`), or create one imperatively
+and drive its motor / limits:
```typescript
// A hinge with a motor (a powered wheel or swinging door).
@@ -213,9 +213,64 @@ Each joint type has a parallel set of control methods:
| Distance (spring) | `setDistanceJointLength`, `getDistanceJoint*Length`, `enableDistanceJointSpring`/`Limit`/`Motor`, `setDistanceJointLimits`, `setDistanceJointMotorSpeed`, … |
| Prismatic (slider) | `getPrismaticJointTranslation`/`Speed`, `enablePrismaticJointSpring`/`Limit`/`Motor`, `setPrismaticJointLimits`/`MotorSpeed`/`MaxMotorForce`, … |
| Wheel | `enableWheelJointSpring`/`Limit`/`Motor`, `setWheelJointLimits`/`MotorSpeed`/`MaxMotorTorque`, `getWheelJointMotorTorque`. |
+| Motor | `setMotorJointLinearVelocity`, `setMotorJointAngularVelocity`, `setMotorJointMaxVelocityForce`, `setMotorJointMaxVelocityTorque`. |
Destroy any joint with `destroyJoint(bodyA)`.
+The **motor joint** drives body B toward a target velocity (or spring-held offset)
+relative to body A — a conveyor, a driven platform, or anything that should move under
+its own power:
+
+```typescript
+// A conveyor: drive the crate toward +x at a fixed speed.
+world.spawn(MotorJoint, {
+ connectedEntity: anchor,
+ linearVelocity: { x: 200, y: 0 }, // world px/s
+ maxVelocityForce: 500, // newtons available to reach it
+});
+physics.setMotorJointLinearVelocity(crate, { x: -200, y: 0 }); // reverse at runtime
+```
+
+## One-way platforms
+
+Add `OneWayPlatform` to a static (or kinematic) collider to make it **one-sided** — a
+body lands on it from one direction and passes through from the others. This is the
+classic jump-up-through-a-ledge behaviour, built on Box2D's pre-solve callback (zero
+cost when no one-way platforms exist):
+
+```typescript
+import { OneWayPlatform } from 'esengine/physics';
+
+world.spawn(
+ Transform, { position: { x: 0, y: 0 } },
+ RigidBody, { bodyType: BodyType.Static },
+ BoxCollider, { halfExtents: { x: 2, y: 0.2 } },
+ OneWayPlatform, { normal: { x: 0, y: 1 } }, // solid top: land from above, pass from below
+);
+```
+
+`normal` is the solid-side direction in world space; `{ x: 0, y: 1 }` (the default)
+means "solid top". Set `enabled: false` to turn the platform back into a normal solid.
+
+## Mouse / drag joint
+
+To let the player drag a body with the pointer, use the drag-joint API. Box2D v3 has no
+dedicated mouse joint, so this is its canonical replacement — a spring that pulls the
+body toward a moving target. Create it on pointer-down (grabbing the body at the cursor),
+move the target on pointer-move, and destroy it on pointer-up:
+
+```typescript
+// pointer down — grab the body at the world-space cursor:
+physics.createMouseJoint(entity, cursorWorld); // maxForce auto-sizes to the body
+// pointer move:
+physics.setMouseTarget(cursorWorld);
+// pointer up:
+physics.destroyMouseJoint();
+```
+
+Only one drag is live at a time. Pass `{ hertz, dampingRatio, maxForce }` to tune the
+spring's stiffness and grip.
+
## Character controller
For a player that walks along surfaces instead of tumbling like a dynamic body, add
diff --git a/docs/astro/src/content/docs/zh-cn/guides/physics.mdx b/docs/astro/src/content/docs/zh-cn/guides/physics.mdx
index f46ac1e24..3f7ec8a6c 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/physics.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/physics.mdx
@@ -181,7 +181,7 @@ const onHit = defineSystem([Res(PhysicsEvents)], (events) => {
## 关节
连接两个刚体。加一个关节**组件**(`RevoluteJoint`、`DistanceJoint`、`PrismaticJoint`、
-`WeldJoint`、`WheelJoint`),或命令式创建一个并驱动它的马达 / 限位:
+`WeldJoint`、`WheelJoint`、`MotorJoint`),或命令式创建一个并驱动它的马达 / 限位:
```typescript
// A hinge with a motor (a powered wheel or swinging door).
@@ -204,9 +204,59 @@ physics.destroyJoint(bodyA);
| Distance(弹簧) | `setDistanceJointLength`、`getDistanceJoint*Length`、`enableDistanceJointSpring`/`Limit`/`Motor`、`setDistanceJointLimits`、`setDistanceJointMotorSpeed`…… |
| Prismatic(滑轨) | `getPrismaticJointTranslation`/`Speed`、`enablePrismaticJointSpring`/`Limit`/`Motor`、`setPrismaticJointLimits`/`MotorSpeed`/`MaxMotorForce`…… |
| Wheel(车轮) | `enableWheelJointSpring`/`Limit`/`Motor`、`setWheelJointLimits`/`MotorSpeed`/`MaxMotorTorque`、`getWheelJointMotorTorque`。 |
+| Motor(马达) | `setMotorJointLinearVelocity`、`setMotorJointAngularVelocity`、`setMotorJointMaxVelocityForce`、`setMotorJointMaxVelocityTorque`。 |
用 `destroyJoint(bodyA)` 销毁任何关节。
+**马达关节**驱动刚体 B 相对刚体 A 达到目标速度(或弹簧保持的偏移)——传送带、动力平台,
+或任何要靠自身动力移动的东西:
+
+```typescript
+// 传送带:把箱子沿 +x 匀速驱动。
+world.spawn(MotorJoint, {
+ connectedEntity: anchor,
+ linearVelocity: { x: 200, y: 0 }, // 世界像素/秒
+ maxVelocityForce: 500, // 可用于达到该速度的力(牛顿)
+});
+physics.setMotorJointLinearVelocity(crate, { x: -200, y: 0 }); // 运行时反向
+```
+
+## 单向平台
+
+给静态(或运动学)碰撞体加 `OneWayPlatform`,使其**单面**——刚体从一个方向落上去、从其它
+方向穿过。这就是经典的"从下往上跳穿平台"行为,建在 Box2D 的 pre-solve 回调上(没有单向平台时
+零开销):
+
+```typescript
+import { OneWayPlatform } from 'esengine/physics';
+
+world.spawn(
+ Transform, { position: { x: 0, y: 0 } },
+ RigidBody, { bodyType: BodyType.Static },
+ BoxCollider, { halfExtents: { x: 2, y: 0.2 } },
+ OneWayPlatform, { normal: { x: 0, y: 1 } }, // 实心顶面:从上落下、从下穿过
+);
+```
+
+`normal` 是世界空间里的实心侧方向;`{ x: 0, y: 1 }`(默认)= "实心顶面"。设 `enabled: false`
+让平台恢复为普通实心体。
+
+## 鼠标 / 拖拽关节
+
+想让玩家用指针拖动刚体,用拖拽关节 API。Box2D v3 没有专门的鼠标关节,这是它的官方替代——一根
+把刚体拉向移动目标的弹簧。指针按下时创建(在光标处抓住刚体)、移动时更新目标、抬起时销毁:
+
+```typescript
+// 指针按下——在世界光标处抓住刚体:
+physics.createMouseJoint(entity, cursorWorld); // maxForce 按刚体自动取值
+// 指针移动:
+physics.setMouseTarget(cursorWorld);
+// 指针抬起:
+physics.destroyMouseJoint();
+```
+
+同一时刻只有一个拖拽在生效。传 `{ hertz, dampingRatio, maxForce }` 调弹簧的刚度与抓力。
+
## 角色控制器
想让玩家沿着表面行走、而不是像动态刚体那样翻滚,加一个 `CharacterController`。每步从玩法设它
diff --git a/sdk/src/physics/Physics.ts b/sdk/src/physics/Physics.ts
index d358cf864..5327b02f3 100644
--- a/sdk/src/physics/Physics.ts
+++ b/sdk/src/physics/Physics.ts
@@ -412,6 +412,57 @@ export class Physics {
return this.module_._physics_getWheelJointMotorTorque(entity);
}
+ // ── Motor joint (runtime control) ───────────────────────────────────────
+ // `velocity` is world pixels/s (scaled to meters); force/torque are physics-space
+ // (newtons, N·m). Targets a joint keyed by its owning entity (see MotorJoint).
+
+ setMotorJointLinearVelocity(entity: Entity, velocity: Vec2, ppu = this.ppu_): void {
+ this.module_._physics_setMotorJointLinearVelocity(entity, velocity.x / ppu, velocity.y / ppu);
+ }
+
+ setMotorJointAngularVelocity(entity: Entity, omega: number): void {
+ this.module_._physics_setMotorJointAngularVelocity(entity, omega);
+ }
+
+ setMotorJointMaxVelocityForce(entity: Entity, force: number): void {
+ this.module_._physics_setMotorJointMaxVelocityForce(entity, force);
+ }
+
+ setMotorJointMaxVelocityTorque(entity: Entity, torque: number): void {
+ this.module_._physics_setMotorJointMaxVelocityTorque(entity, torque);
+ }
+
+ // ── Mouse / drag joint ──────────────────────────────────────────────────
+ // Box2D v3 has no dedicated mouse joint; this is the canonical replacement — a
+ // kinematic body plus a spring motor joint that pulls `entity` toward a
+ // world-pixel target. Create on pointer-down, setMouseTarget on move, destroy on
+ // up. Only one drag is live at a time (a new create replaces the previous).
+ // `maxForce` defaults to an auto-sized value from the body's weight.
+
+ createMouseJoint(
+ entity: Entity,
+ target: Vec2,
+ opts: { hertz?: number; dampingRatio?: number; maxForce?: number } = {},
+ ppu = this.ppu_,
+ ): boolean {
+ return this.module_._physics_createMouseJoint(
+ entity, target.x / ppu, target.y / ppu,
+ opts.hertz ?? 7.5, opts.dampingRatio ?? 1.0, opts.maxForce ?? 0,
+ ) !== 0;
+ }
+
+ setMouseTarget(target: Vec2, ppu = this.ppu_): void {
+ this.module_._physics_setMouseTarget(target.x / ppu, target.y / ppu);
+ }
+
+ destroyMouseJoint(): void {
+ this.module_._physics_destroyMouseJoint();
+ }
+
+ hasMouseJoint(): boolean {
+ return this.module_._physics_hasMouseJoint() !== 0;
+ }
+
private readUniqueEntityBuffer_(count: number): Entity[] {
if (count === 0) return [];
const ptr = this.module_._physics_getOverlapBuffer() >> 2;
diff --git a/sdk/src/physics/PhysicsComponents.ts b/sdk/src/physics/PhysicsComponents.ts
index 741082f3d..6114f04d3 100644
--- a/sdk/src/physics/PhysicsComponents.ts
+++ b/sdk/src/physics/PhysicsComponents.ts
@@ -214,6 +214,26 @@ export const ChainCollider = defineComponent<ChainColliderData>('ChainCollider',
enabled: true,
}, { fields: { ...COLLISION_FILTER_META } });
+// =============================================================================
+// One-Way (One-Sided) Platform
+// =============================================================================
+
+export interface OneWayPlatformData {
+ // Solid-side normal in world/physics space. Contacts are cancelled unless the
+ // other body approaches from this side. Default {0,1} = solid top (land on top,
+ // jump up through it).
+ normal: Vec2;
+ enabled: boolean;
+}
+
+// A collider modifier: put it on an entity that also has a RigidBody + a collider.
+// Consumed by PhysicsSystem, which enables Box2D pre-solve events on the entity's
+// shapes and feeds the normal to the one-way pre-solve callback.
+export const OneWayPlatform = defineComponent<OneWayPlatformData>('OneWayPlatform', {
+ normal: { x: 0, y: 1 },
+ enabled: true,
+});
+
// =============================================================================
// Joint Components
// =============================================================================
@@ -377,3 +397,38 @@ export const WheelJoint = defineComponent<WheelJointData>('WheelJoint', {
collideConnected: false,
enabled: true,
}, { entityFields: ['connectedEntity'] });
+
+export interface MotorJointData {
+ connectedEntity: number;
+ // Target relative linear velocity (world units/s) and the max force to reach it.
+ linearVelocity: Vec2;
+ maxVelocityForce: number;
+ // Target relative angular velocity (rad/s) and the max torque to reach it.
+ angularVelocity: number;
+ maxVelocityTorque: number;
+ // Optional spring position control (0 hertz = velocity-only motor).
+ linearHertz: number;
+ linearDampingRatio: number;
+ maxSpringForce: number;
+ angularHertz: number;
+ angularDampingRatio: number;
+ maxSpringTorque: number;
+ collideConnected: boolean;
+ enabled: boolean;
+}
+
+export const MotorJoint = defineComponent<MotorJointData>('MotorJoint', {
+ connectedEntity: -1,
+ linearVelocity: { x: 0, y: 0 },
+ maxVelocityForce: 0,
+ angularVelocity: 0,
+ maxVelocityTorque: 0,
+ linearHertz: 0,
+ linearDampingRatio: 0,
+ maxSpringForce: 0,
+ angularHertz: 0,
+ angularDampingRatio: 0,
+ maxSpringTorque: 0,
+ collideConnected: false,
+ enabled: true,
+}, { entityFields: ['connectedEntity'] });
diff --git a/sdk/src/physics/PhysicsModuleLoader.ts b/sdk/src/physics/PhysicsModuleLoader.ts
index f82ddea92..d7e89c994 100644
--- a/sdk/src/physics/PhysicsModuleLoader.ts
+++ b/sdk/src/physics/PhysicsModuleLoader.ts
@@ -82,6 +82,8 @@ export interface PhysicsWasmModule {
gravityScale: number, linearDamping: number, angularDamping: number,
fixedRotation: number, bullet: number): void;
+ _physics_setOneWayPlatform(entityId: number, nx: number, ny: number, enable: number): void;
+
_physics_createRevoluteJoint(entityIdA: number, entityIdB: number,
anchorAx: number, anchorAy: number, anchorBx: number, anchorBy: number,
enableMotor: number, motorSpeed: number, maxMotorTorque: number,
@@ -123,6 +125,23 @@ export interface PhysicsWasmModule {
enableMotor: number, maxMotorTorque: number, motorSpeed: number,
collideConnected: number): number;
+ _physics_createMotorJoint(entityIdA: number, entityIdB: number,
+ linearVelX: number, linearVelY: number, maxVelocityForce: number,
+ angularVelocity: number, maxVelocityTorque: number,
+ linearHertz: number, linearDampingRatio: number, maxSpringForce: number,
+ angularHertz: number, angularDampingRatio: number, maxSpringTorque: number,
+ collideConnected: number): number;
+ _physics_setMotorJointLinearVelocity(entityId: number, vx: number, vy: number): void;
+ _physics_setMotorJointAngularVelocity(entityId: number, omega: number): void;
+ _physics_setMotorJointMaxVelocityForce(entityId: number, force: number): void;
+ _physics_setMotorJointMaxVelocityTorque(entityId: number, torque: number): void;
+
+ _physics_createMouseJoint(entityId: number, targetX: number, targetY: number,
+ hertz: number, dampingRatio: number, maxForce: number): number;
+ _physics_setMouseTarget(targetX: number, targetY: number): void;
+ _physics_destroyMouseJoint(): void;
+ _physics_hasMouseJoint(): number;
+
_physics_raycast(originX: number, originY: number, dirX: number, dirY: number,
maxDistance: number, maskBits: number): number;
_physics_getRaycastBuffer(): number;
diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.ts
index 94af839d3..7e3c7cd37 100644
--- a/sdk/src/physics/PhysicsSystem.ts
+++ b/sdk/src/physics/PhysicsSystem.ts
@@ -21,13 +21,14 @@ import type { PhysicsWasmModule } from './PhysicsModuleLoader';
import { PhysicsAPI } from './Physics';
import {
RigidBody, BoxCollider, CircleCollider, CapsuleCollider,
- SegmentCollider, PolygonCollider, ChainCollider,
- RevoluteJoint, DistanceJoint, PrismaticJoint, WeldJoint, WheelJoint,
+ SegmentCollider, PolygonCollider, ChainCollider, OneWayPlatform,
+ RevoluteJoint, DistanceJoint, PrismaticJoint, WeldJoint, WheelJoint, MotorJoint,
BodyType,
type RigidBodyData, type BoxColliderData, type CircleColliderData,
type CapsuleColliderData, type SegmentColliderData, type PolygonColliderData,
- type ChainColliderData, type RevoluteJointData,
+ type ChainColliderData, type OneWayPlatformData, type RevoluteJointData,
type DistanceJointData, type PrismaticJointData, type WeldJointData, type WheelJointData,
+ type MotorJointData,
} from './PhysicsComponents';
import {
PhysicsEvents,
@@ -272,6 +273,54 @@ function createPendingJoints(
);
trackedJoints.add(entity);
}
+
+ for (const entity of world.getEntitiesWithComponents([MotorJoint, RigidBody])) {
+ if (trackedJoints.has(entity)) continue;
+ if (!trackedEntities.has(entity)) continue;
+ const j = world.get(entity, MotorJoint) as MotorJointData;
+ if (!j.enabled) continue;
+ const connected = j.connectedEntity as Entity;
+ if (!trackedEntities.has(connected)) continue;
+ module._physics_createMotorJoint(
+ connected, entity,
+ j.linearVelocity.x * invPpu, j.linearVelocity.y * invPpu, j.maxVelocityForce,
+ j.angularVelocity, j.maxVelocityTorque,
+ j.linearHertz, j.linearDampingRatio, j.maxSpringForce,
+ j.angularHertz, j.angularDampingRatio, j.maxSpringTorque,
+ j.collideConnected ? 1 : 0,
+ );
+ trackedJoints.add(entity);
+ }
+}
+
+// =============================================================================
+// One-way platform sync
+// =============================================================================
+
+// Re-applied every reconcile (idempotent): pushes each one-way platform's normal +
+// enabled flag to the native pre-solve state and re-arms pre-solve events on shapes
+// the collider reconcile may have just rebuilt. Entities that lost the component are
+// cleared. `trackedOneWay` mirrors the native state so despawn can tear it down.
+function syncOneWayPlatforms(
+ world: App['world'],
+ module: PhysicsWasmModule,
+ trackedEntities: Set<Entity>,
+ trackedOneWay: Set<Entity>,
+): void {
+ const seen = new Set<Entity>();
+ for (const entity of world.getEntitiesWithComponents([OneWayPlatform, RigidBody])) {
+ if (!trackedEntities.has(entity)) continue;
+ const ow = world.get(entity, OneWayPlatform) as OneWayPlatformData;
+ module._physics_setOneWayPlatform(entity, ow.normal.x, ow.normal.y, ow.enabled ? 1 : 0);
+ trackedOneWay.add(entity);
+ seen.add(entity);
+ }
+ for (const entity of [...trackedOneWay]) {
+ if (!seen.has(entity)) {
+ module._physics_setOneWayPlatform(entity, 0, 0, 0);
+ trackedOneWay.delete(entity);
+ }
+ }
}
// =============================================================================
@@ -566,7 +615,7 @@ const COLLIDER_TYPES = [
BoxCollider, CircleCollider, CapsuleCollider, SegmentCollider, PolygonCollider, ChainCollider,
] as const;
-const JOINT_TYPES = [RevoluteJoint, DistanceJoint, PrismaticJoint, WeldJoint, WheelJoint] as const;
+const JOINT_TYPES = [RevoluteJoint, DistanceJoint, PrismaticJoint, WeldJoint, WheelJoint, MotorJoint] as const;
/** Bitmask of which collider components an entity currently has. @internal */
export function colliderSignature(world: App['world'], entity: Entity): number {
@@ -610,6 +659,7 @@ export function registerPhysicsSystem(
): void {
const trackedEntities = new Set<Entity>();
const trackedJoints = new Set<Entity>();
+ const trackedOneWay = new Set<Entity>();
const parentedBodies = new Set<Entity>();
const cachedProps = new Map<Entity, CachedBodyProps>();
let lastEntitySyncTick = -1;
@@ -627,7 +677,7 @@ export function registerPhysicsSystem(
// state (no structural change + no physics-component edit). Kinematic bodies
// are driven by their Transform, so they're tracked separately and pushed every
// step regardless of whether the reconcile ran.
- const physicsComponents = [RigidBody, ...COLLIDER_TYPES, ...JOINT_TYPES];
+ const physicsComponents = [RigidBody, ...COLLIDER_TYPES, ...JOINT_TYPES, OneWayPlatform];
for (const c of physicsComponents) app.world.enableChangeTracking(c);
const kinematicEntities = new Set<Entity>();
let lastStructuralVersion = -1;
@@ -639,6 +689,10 @@ export function registerPhysicsSystem(
module._physics_destroyJoint(entity);
trackedJoints.delete(entity);
}
+ if (trackedOneWay.has(entity)) {
+ module._physics_setOneWayPlatform(entity, 0, 0, 0);
+ trackedOneWay.delete(entity);
+ }
if (trackedEntities.has(entity)) {
module._physics_destroyBody(entity);
trackedEntities.delete(entity);
@@ -794,6 +848,7 @@ export function registerPhysicsSystem(
}
}
createPendingJoints(world, module, trackedEntities, trackedJoints, invPpu);
+ syncOneWayPlatforms(world, module, trackedEntities, trackedOneWay);
lastEntitySyncTick = world.getWorldTick();
lastStructuralVersion = structuralVersion;
diff --git a/sdk/src/physics/index.ts b/sdk/src/physics/index.ts
index f5263866b..4fdc0b9fd 100644
--- a/sdk/src/physics/index.ts
+++ b/sdk/src/physics/index.ts
@@ -40,11 +40,13 @@ export {
SegmentCollider,
PolygonCollider,
ChainCollider,
+ OneWayPlatform,
RevoluteJoint,
DistanceJoint,
PrismaticJoint,
WeldJoint,
WheelJoint,
+ MotorJoint,
BodyType,
type RigidBodyData,
type BoxColliderData,
@@ -53,11 +55,13 @@ export {
type SegmentColliderData,
type PolygonColliderData,
type ChainColliderData,
+ type OneWayPlatformData,
type RevoluteJointData,
type DistanceJointData,
type PrismaticJointData,
type WeldJointData,
type WheelJointData,
+ type MotorJointData,
} from './PhysicsComponents';
export {
diff --git a/sdk/tests/physics-features-smoke.mjs b/sdk/tests/physics-features-smoke.mjs
new file mode 100644
index 000000000..2b9792ef1
--- /dev/null
+++ b/sdk/tests/physics-features-smoke.mjs
@@ -0,0 +1,99 @@
+// Headless validation of one-way platforms, motor joints, and mouse (drag) joints.
+// Loads the built physics wasm directly and asserts each behaviour end-to-end, the
+// same pattern as mover-smoke.mjs / sensor-smoke.mjs.
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+
+const dir = path.dirname(fileURLToPath(import.meta.url));
+const wasmDir = path.resolve(dir, '../../desktop/public/wasm');
+const factory = (await import('file://' + path.join(wasmDir, 'physics.js').replace(/\\/g, '/'))).default;
+const wasmBinary = readFileSync(path.join(wasmDir, 'physics.wasm'));
+const m = await factory({ wasmBinary });
+
+let pass = true;
+const check = (name, cond, detail) => {
+ console.log(`${cond ? 'PASS' : 'FAIL'} ${name} ${detail ?? ''}`);
+ if (!cond) pass = false;
+};
+
+// Read a dynamic body's (x, y) from the batched transform buffer.
+function bodyPos(entity) {
+ const count = m._physics_getDynamicBodyCount();
+ const base = m._physics_getDynamicBodyTransforms() >> 2;
+ for (let i = 0; i < count; i++) {
+ const o = base + i * 4;
+ if (m.HEAPU32[o] === entity) return { x: m.HEAPF32[o + 1], y: m.HEAPF32[o + 2] };
+ }
+ return null;
+}
+const STATIC = 0, DYNAMIC = 2;
+const body = (e, type, x, y) => m._physics_createBody(e, type, x, y, 0, 1, 0, 0, 0, 0);
+const box = (e, hw, hh) => m._physics_addBoxShape(e, hw, hh, 0, 0, 0, 1, 0.3, 0, 0, 1, 0xffff);
+const step = (n) => { for (let i = 0; i < n; i++) m._physics_step(1 / 60); };
+
+// ── 1) One-way platform ─────────────────────────────────────────────────────
+// Platforms have a solid top (+Y): a body resting from above lands, a body launched
+// up from below passes through, then falls back and lands on top.
+m._physics_init(0, -9.81, 1 / 60, 4, 30, 10, 3);
+
+const PLAT_A = 1, ABOVE = 2;
+body(PLAT_A, STATIC, -5, 0); box(PLAT_A, 2, 0.2);
+m._physics_setOneWayPlatform(PLAT_A, 0, 1, 1);
+body(ABOVE, DYNAMIC, -5, 3); box(ABOVE, 0.2, 0.2);
+
+const PLAT_B = 3, BELOW = 4;
+body(PLAT_B, STATIC, 5, 0); box(PLAT_B, 2, 0.2);
+m._physics_setOneWayPlatform(PLAT_B, 0, 1, 1);
+body(BELOW, DYNAMIC, 5, -3); box(BELOW, 0.2, 0.2);
+m._physics_setLinearVelocity(BELOW, 0, 12); // launch up through the platform
+
+let belowMaxY = -Infinity;
+for (let i = 0; i < 240; i++) {
+ m._physics_step(1 / 60);
+ const p = bodyPos(BELOW);
+ if (p) belowMaxY = Math.max(belowMaxY, p.y);
+}
+const aPos = bodyPos(ABOVE), bPos = bodyPos(BELOW);
+// Platform top at 0.2, body half-height 0.2 → resting centre ≈ 0.4.
+check('above body lands on top', aPos && Math.abs(aPos.y - 0.4) < 0.15, `y=${aPos?.y.toFixed(3)} (want ≈0.4)`);
+check('above body does not sink through', aPos && aPos.y > 0.2, `y=${aPos?.y.toFixed(3)}`);
+check('below body passes up through', belowMaxY > 1.5, `maxY=${belowMaxY.toFixed(3)} (want >1.5)`);
+check('below body lands on top after passing', bPos && Math.abs(bPos.y - 0.4) < 0.2, `y=${bPos?.y.toFixed(3)} (want ≈0.4)`);
+
+// ── 2) Motor joint (conveyor / driven motion) ───────────────────────────────
+m._physics_shutdown();
+m._physics_init(0, 0, 1 / 60, 4, 30, 10, 3); // no gravity isolates the motor
+const ANCHOR = 1, DRIVEN = 2;
+body(ANCHOR, STATIC, 0, 0);
+body(DRIVEN, DYNAMIC, 0, 0); box(DRIVEN, 0.3, 0.3);
+// Drive DRIVEN toward +x at 4 m/s with ample force (velocity-only motor).
+m._physics_createMotorJoint(ANCHOR, DRIVEN, 4, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0);
+step(60);
+const driven1 = bodyPos(DRIVEN);
+check('motor drives body +x', driven1 && driven1.x > 2.0, `x=${driven1?.x.toFixed(3)} (want >2.0 after 1s @ 4 m/s)`);
+m._physics_setMotorJointLinearVelocity(DRIVEN, -4, 0); // reverse at runtime
+step(120);
+const driven2 = bodyPos(DRIVEN);
+check('motor reverses body -x', driven2 && driven2.x < driven1.x, `x=${driven2?.x.toFixed(3)} < ${driven1?.x.toFixed(3)}`);
+
+// ── 3) Mouse (drag) joint ───────────────────────────────────────────────────
+m._physics_shutdown();
+m._physics_init(0, 0, 1 / 60, 4, 30, 10, 3);
+const DRAG = 1;
+body(DRAG, DYNAMIC, 0, 0); box(DRAG, 0.3, 0.3);
+// Grab the body at its centre (0,0), then drag the target around.
+const created = m._physics_createMouseJoint(DRAG, 0, 0, 7.5, 1.0, 0 /*auto force*/);
+check('mouse joint created', created === 1, `ret=${created}`);
+check('has mouse joint', m._physics_hasMouseJoint() === 1, '');
+for (let i = 0; i < 90; i++) { m._physics_setMouseTarget(5, 0); m._physics_step(1 / 60); }
+const drag1 = bodyPos(DRAG);
+check('drag pulls body toward x=5', drag1 && drag1.x > 3.0, `x=${drag1?.x.toFixed(3)} (want >3.0)`);
+for (let i = 0; i < 120; i++) { m._physics_setMouseTarget(5, 5); m._physics_step(1 / 60); }
+const drag2 = bodyPos(DRAG);
+check('drag follows target to y=5', drag2 && drag2.y > 3.0, `y=${drag2?.y.toFixed(3)} (want >3.0)`);
+m._physics_destroyMouseJoint();
+check('mouse joint destroyed', m._physics_hasMouseJoint() === 0, '');
+
+console.log(pass ? '\nPHYSICS_FEATURES_SMOKE PASS' : '\nPHYSICS_FEATURES_SMOKE FAIL');
+process.exit(pass ? 0 : 1);
diff --git a/sdk/tests/physics-features.test.ts b/sdk/tests/physics-features.test.ts
new file mode 100644
index 000000000..7196f19d3
--- /dev/null
+++ b/sdk/tests/physics-features.test.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file One-way platform + motor joint component contracts. The runtime behaviour
+ * (pass-through, drive, drag) is proven end-to-end against the real wasm in
+ * physics-features-smoke.mjs; these guard the TS-side wiring that feeds it —
+ * defaults, registration, and MotorJoint's place in the joint reconcile.
+ */
+import { describe, it, expect } from 'vitest';
+import { World } from '../src/world';
+import { createMockModule } from './mocks/wasm';
+import {
+ OneWayPlatform, MotorJoint,
+ type OneWayPlatformData, type MotorJointData,
+} from '../src/physics/PhysicsComponents';
+import { jointChangedOrGone } from '../src/physics/PhysicsSystem';
+
+function testWorld(): World {
+ const mod = createMockModule();
+ const world = new World();
+ world.connectCpp(mod.getRegistry(), mod);
+ return world;
+}
+
+describe('OneWayPlatform component', () => {
+ it('defaults to a solid top (+Y) and enabled', () => {
+ const d = OneWayPlatform._default as OneWayPlatformData;
+ expect(d.normal).toEqual({ x: 0, y: 1 });
+ expect(d.enabled).toBe(true);
+ });
+});
+
+describe('MotorJoint component', () => {
+ it('defaults are inert (no drive) with connectedEntity unset', () => {
+ const d = MotorJoint._default as MotorJointData;
+ expect(d.connectedEntity).toBe(-1);
+ expect(d.linearVelocity).toEqual({ x: 0, y: 0 });
+ expect(d.maxVelocityForce).toBe(0);
+ expect(d.enabled).toBe(true);
+ });
+
+ it('participates in the joint reconcile — present + unedited is left intact', () => {
+ const world = testWorld();
+ const e = world.spawn();
+ world.insert(e, MotorJoint, {} as never);
+ expect(jointChangedOrGone(world, e, world.getWorldTick())).toBe(false);
+ });
+
+ it('reports gone when no joint component remains', () => {
+ const world = testWorld();
+ const e = world.spawn();
+ expect(jointChangedOrGone(world, e, 0)).toBe(true);
+ });
+});
diff --git a/src/esengine/bindings/PhysicsContext.hpp b/src/esengine/bindings/PhysicsContext.hpp
index 331285d3f..69c5987c2 100644
--- a/src/esengine/bindings/PhysicsContext.hpp
+++ b/src/esengine/bindings/PhysicsContext.hpp
@@ -28,6 +28,16 @@ struct PhysicsContext {
std::unordered_map<uint32_t, b2JointId> entityToJoint;
std::vector<uint32_t> dynamicBodyEntities;
+ // One-way (one-sided) platforms: entity -> solid-side normal in physics space
+ // (normalized). Read by the pre-solve callback to cancel contacts that approach
+ // from the pass-through side. Empty map = zero pre-solve overhead.
+ std::unordered_map<uint32_t, b2Vec2> oneWayNormals;
+
+ // Interactive drag: a single kinematic "mouse body" + motor joint pulling one
+ // target body toward the cursor (Box2D v3 has no dedicated mouse joint).
+ b2BodyId mouseBodyId = b2_nullBodyId;
+ b2JointId mouseJointId = b2_nullJointId;
+
std::vector<float> dynamicTransformBuffer;
std::vector<float> collisionEnterBuffer;
@@ -43,6 +53,9 @@ struct PhysicsContext {
entityToBody.clear();
entityToShapes.clear();
entityToJoint.clear();
+ oneWayNormals.clear();
+ mouseBodyId = b2_nullBodyId;
+ mouseJointId = b2_nullJointId;
dynamicBodyEntities.clear();
dynamicTransformBuffer.clear();
collisionEnterBuffer.clear();
diff --git a/src/esengine/bindings/PhysicsJoints.cpp b/src/esengine/bindings/PhysicsJoints.cpp
index aaef749aa..8d270773b 100644
--- a/src/esengine/bindings/PhysicsJoints.cpp
+++ b/src/esengine/bindings/PhysicsJoints.cpp
@@ -430,4 +430,142 @@ float physics_getWheelJointMotorTorque(uint32_t entityId) {
return b2WheelJoint_GetMotorTorque(jid);
}
+// -----------------------------------------------------------------------------
+// Motor joint — drives bodyB toward a relative linear/angular velocity (or a
+// spring-held offset) against bodyA. Good for conveyors, driven platforms, and
+// the "move toward a target" behaviour the mouse-drag helper below reuses.
+// -----------------------------------------------------------------------------
+
+EMSCRIPTEN_KEEPALIVE
+int physics_createMotorJoint(uint32_t entityIdA, uint32_t entityIdB,
+ float linearVelX, float linearVelY, float maxVelocityForce,
+ float angularVelocity, float maxVelocityTorque,
+ float linearHertz, float linearDampingRatio, float maxSpringForce,
+ float angularHertz, float angularDampingRatio, float maxSpringTorque,
+ int collideConnected) {
+ if (!b2World_IsValid(g_ctx.worldId)) return 0;
+
+ auto itA = g_ctx.entityToBody.find(entityIdA);
+ auto itB = g_ctx.entityToBody.find(entityIdB);
+ if (itA == g_ctx.entityToBody.end() || itB == g_ctx.entityToBody.end()) return 0;
+ if (!b2Body_IsValid(itA->second) || !b2Body_IsValid(itB->second)) return 0;
+
+ b2MotorJointDef jointDef = b2DefaultMotorJointDef();
+ jointDef.base.bodyIdA = itA->second;
+ jointDef.base.bodyIdB = itB->second;
+ jointDef.linearVelocity = {linearVelX, linearVelY};
+ jointDef.maxVelocityForce = maxVelocityForce;
+ jointDef.angularVelocity = angularVelocity;
+ jointDef.maxVelocityTorque = maxVelocityTorque;
+ jointDef.linearHertz = linearHertz;
+ jointDef.linearDampingRatio = linearDampingRatio;
+ jointDef.maxSpringForce = maxSpringForce;
+ jointDef.angularHertz = angularHertz;
+ jointDef.angularDampingRatio = angularDampingRatio;
+ jointDef.maxSpringTorque = maxSpringTorque;
+ jointDef.base.collideConnected = collideConnected != 0;
+
+ b2JointId jointId = b2CreateMotorJoint(g_ctx.worldId, &jointDef);
+ g_ctx.entityToJoint[entityIdB] = jointId;
+ return 1;
+}
+
+EMSCRIPTEN_KEEPALIVE
+void physics_setMotorJointLinearVelocity(uint32_t entityId, float vx, float vy) {
+ auto jid = findValidJoint(entityId);
+ if (!B2_IS_NULL(jid)) b2MotorJoint_SetLinearVelocity(jid, {vx, vy});
+}
+
+EMSCRIPTEN_KEEPALIVE
+void physics_setMotorJointAngularVelocity(uint32_t entityId, float omega) {
+ auto jid = findValidJoint(entityId);
+ if (!B2_IS_NULL(jid)) b2MotorJoint_SetAngularVelocity(jid, omega);
+}
+
+EMSCRIPTEN_KEEPALIVE
+void physics_setMotorJointMaxVelocityForce(uint32_t entityId, float force) {
+ auto jid = findValidJoint(entityId);
+ if (!B2_IS_NULL(jid)) b2MotorJoint_SetMaxVelocityForce(jid, force);
+}
+
+EMSCRIPTEN_KEEPALIVE
+void physics_setMotorJointMaxVelocityTorque(uint32_t entityId, float torque) {
+ auto jid = findValidJoint(entityId);
+ if (!B2_IS_NULL(jid)) b2MotorJoint_SetMaxVelocityTorque(jid, torque);
+}
+
+// -----------------------------------------------------------------------------
+// Mouse (drag) joint — Box2D v3 has no dedicated mouse joint, so this is the
+// canonical replacement from Box2D's own sample: a kinematic "mouse body" plus a
+// spring motor joint pulling the target toward the cursor. Only one is live at a
+// time (stored on the context); creating a new one tears down the previous.
+// -----------------------------------------------------------------------------
+
+EMSCRIPTEN_KEEPALIVE
+int physics_createMouseJoint(uint32_t entityId, float targetX, float targetY,
+ float hertz, float dampingRatio, float maxForce) {
+ if (!b2World_IsValid(g_ctx.worldId)) return 0;
+
+ auto it = g_ctx.entityToBody.find(entityId);
+ if (it == g_ctx.entityToBody.end() || !b2Body_IsValid(it->second)) return 0;
+
+ if (b2Joint_IsValid(g_ctx.mouseJointId)) b2DestroyJoint(g_ctx.mouseJointId, false);
+ if (b2Body_IsValid(g_ctx.mouseBodyId)) b2DestroyBody(g_ctx.mouseBodyId);
+
+ b2BodyDef bodyDef = b2DefaultBodyDef();
+ bodyDef.type = b2_kinematicBody;
+ bodyDef.position = {targetX, targetY};
+ bodyDef.enableSleep = false;
+ g_ctx.mouseBodyId = b2CreateBody(g_ctx.worldId, &bodyDef);
+
+ b2MotorJointDef jointDef = b2DefaultMotorJointDef();
+ jointDef.base.bodyIdA = g_ctx.mouseBodyId;
+ jointDef.base.bodyIdB = it->second;
+ jointDef.base.localFrameB.p = b2Body_GetLocalPoint(it->second, {targetX, targetY});
+ jointDef.linearHertz = hertz;
+ jointDef.linearDampingRatio = dampingRatio;
+
+ // Auto-size the spring force from the body's weight (Box2D's sample formula) when
+ // the caller passes maxForce <= 0. Top-down worlds have no gravity, so fall back
+ // to a nominal g so the drag still has bite. Also cap angular drift like the sample.
+ b2MassData massData = b2Body_GetMassData(it->second);
+ if (maxForce <= 0.0f) {
+ float g = b2Length(b2World_GetGravity(g_ctx.worldId));
+ maxForce = 100.0f * massData.mass * (g > 0.0f ? g : 10.0f);
+ }
+ jointDef.maxSpringForce = maxForce;
+ if (massData.mass > 0.0f) {
+ float lever = sqrtf(massData.rotationalInertia / massData.mass);
+ jointDef.maxVelocityTorque = 0.25f * lever * (maxForce / 100.0f);
+ }
+
+ g_ctx.mouseJointId = b2CreateMotorJoint(g_ctx.worldId, &jointDef);
+
+ b2Body_SetAwake(it->second, true);
+ return 1;
+}
+
+EMSCRIPTEN_KEEPALIVE
+void physics_setMouseTarget(float targetX, float targetY) {
+ if (!b2Body_IsValid(g_ctx.mouseBodyId)) return;
+ b2Body_SetTransform(g_ctx.mouseBodyId, {targetX, targetY}, b2Rot_identity);
+ if (b2Joint_IsValid(g_ctx.mouseJointId)) {
+ b2BodyId bodyB = b2Joint_GetBodyB(g_ctx.mouseJointId);
+ if (b2Body_IsValid(bodyB)) b2Body_SetAwake(bodyB, true);
+ }
+}
+
+EMSCRIPTEN_KEEPALIVE
+void physics_destroyMouseJoint() {
+ if (b2Joint_IsValid(g_ctx.mouseJointId)) b2DestroyJoint(g_ctx.mouseJointId, false);
+ if (b2Body_IsValid(g_ctx.mouseBodyId)) b2DestroyBody(g_ctx.mouseBodyId);
+ g_ctx.mouseJointId = b2_nullJointId;
+ g_ctx.mouseBodyId = b2_nullBodyId;
+}
+
+EMSCRIPTEN_KEEPALIVE
+int physics_hasMouseJoint() {
+ return b2Joint_IsValid(g_ctx.mouseJointId) ? 1 : 0;
+}
+
} // extern "C"
diff --git a/src/esengine/bindings/PhysicsModuleEntry.cpp b/src/esengine/bindings/PhysicsModuleEntry.cpp
index d09f56ad2..fe37a47e4 100644
--- a/src/esengine/bindings/PhysicsModuleEntry.cpp
+++ b/src/esengine/bindings/PhysicsModuleEntry.cpp
@@ -3,6 +3,37 @@
#include "PhysicsContext.hpp"
#include <algorithm>
+#include <cmath>
+
+// How closely the contact normal must align with a platform's solid normal for the
+// contact to survive (matches Box2D's own one-sided-platform sample).
+static constexpr float ONE_WAY_ALIGN_THRESHOLD = 0.95f;
+
+// Pre-solve callback: cancels contacts that approach a one-way platform from its
+// pass-through side. Box2D only invokes this for contacts whose shapes opted in via
+// b2Shape_EnablePreSolveEvents, so it costs nothing when no one-way platforms exist.
+// Must be thread-safe and side-effect free: it only reads oneWayNormals (never
+// mutated during a step) plus the passed-in contact geometry.
+static bool preSolveOneWayPlatform(b2ShapeId shapeIdA, b2ShapeId shapeIdB,
+ b2Vec2 point, b2Vec2 normal, void* context) {
+ (void)point;
+ (void)context;
+ // The manifold normal points from shape A to shape B. A one-way platform keeps a
+ // contact only while the *other* shape sits on the platform's solid side.
+ auto itA = g_ctx.oneWayNormals.find(entityFromShape(shapeIdA));
+ if (itA != g_ctx.oneWayNormals.end()) {
+ // Platform = A; direction toward the other shape (B) is +normal.
+ float d = normal.x * itA->second.x + normal.y * itA->second.y;
+ if (d <= ONE_WAY_ALIGN_THRESHOLD) return false;
+ }
+ auto itB = g_ctx.oneWayNormals.find(entityFromShape(shapeIdB));
+ if (itB != g_ctx.oneWayNormals.end()) {
+ // Platform = B; direction toward the other shape (A) is -normal.
+ float d = normal.x * itB->second.x + normal.y * itB->second.y;
+ if (d >= -ONE_WAY_ALIGN_THRESHOLD) return false;
+ }
+ return true;
+}
extern "C" {
@@ -19,6 +50,7 @@ void physics_init(float gx, float gy, float timestep, int substeps,
worldDef.contactDampingRatio = contactDampingRatio;
worldDef.contactSpeed = contactSpeed;
g_ctx.worldId = b2CreateWorld(&worldDef);
+ b2World_SetPreSolveCallback(g_ctx.worldId, preSolveOneWayPlatform, nullptr);
g_ctx.fixedTimestep = timestep;
g_ctx.subStepCount = substeps;
@@ -47,6 +79,30 @@ void physics_shutdown() {
g_ctx.reset();
}
+// One-way (one-sided) platform: with enable != 0, contacts against this entity's
+// shapes are cancelled unless the other body approaches from the (nx, ny) solid
+// side (physics space; normalized here, falling back to +Y). enable == 0 clears it.
+EMSCRIPTEN_KEEPALIVE
+void physics_setOneWayPlatform(uint32_t entityId, float nx, float ny, int enable) {
+ if (enable != 0) {
+ float len = sqrtf(nx * nx + ny * ny);
+ g_ctx.oneWayNormals[entityId] = (len > 0.0f)
+ ? b2Vec2{nx / len, ny / len}
+ : b2Vec2{0.0f, 1.0f};
+ } else {
+ g_ctx.oneWayNormals.erase(entityId);
+ }
+
+ auto it = g_ctx.entityToShapes.find(entityId);
+ if (it != g_ctx.entityToShapes.end()) {
+ for (b2ShapeId shapeId : it->second) {
+ if (b2Shape_IsValid(shapeId)) {
+ b2Shape_EnablePreSolveEvents(shapeId, enable != 0);
+ }
+ }
+ }
+}
+
// Body Management
EMSCRIPTEN_KEEPALIVE