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): drive CharacterController with Box2D's native kinematic mover
yhh3e55939de425
diff --git a/docs/astro/src/content/docs/guides/physics.mdx b/docs/astro/src/content/docs/guides/physics.mdxindex bd449f45e..a9a4820e2 100644--- a/docs/astro/src/content/docs/guides/physics.mdx+++ b/docs/astro/src/content/docs/guides/physics.mdx@@ -212,8 +212,11 @@ Destroy any joint with `destroyJoint(bodyA)`.## Character controllerFor a player that walks along surfaces instead of tumbling like a dynamic body, add-a `CharacterController`. Set its `velocity` from gameplay each step; the system-resolves a kinematic move-and-slide, writes the result back, and reports what it+a `CharacterController`. Set its `velocity` from gameplay each step; the controller+advances it one step with Box2D's **native kinematic mover** (`b2World_CollideMover`++ `b2SolvePlanes`) — it collides the body into contact *planes* and solves a+depenetrating slide, so a character resting on the ground slides and jumps cleanly+instead of sticking to it. It writes the resolved pose back and reports what ittouched:```typescript@@ -227,20 +230,29 @@ const drive = defineSystem([Query(Mut(CharacterController))], (q) => {});```+Give the entity a collider (the mover shape is derived from it — a box becomes a+capsule inscribed along its longer axis) and, if other bodies should collide with+the character, a **Kinematic** `RigidBody`. The mover excludes the character's own+body automatically, so its `maskBits` need not avoid its own collision layer. Drive+`velocity` from a fixed-timestep system so motion is frame-rate independent; read the+`isOnFloor` edge for jumps (delivered correctly to `FixedUpdate` — see+[Input](/docs/guides/input/#fixed-timestep-physics)).+| Property | Type | Default | Description ||---|---|---|---|| `velocity` | Vec2 | `{0, 0}` | Desired velocity in world pixels/second (set each step). || `up` | Vec2 | `{0, 1}` | Up direction for floor/ceiling classification. || `floorMaxAngle` | number | `0.785` | Max walkable slope from `up`, radians (45°). |-| `maxSlides` | number | `4` | Slide iterations per move (corners need more). |-| `skinWidth` | number | `1` | Gap kept from surfaces (px) to avoid sticking. |-| `snapLength` | number | `0` | Down-probe (px) to stay glued to slopes/stairs; `0` = off. |-| `slideOnCeiling` | boolean | `true` | Slide along a ceiling vs. stop the move. || `maskBits` | number | `0xFFFF` | Layers that block the character. || `isOnFloor` / `isOnWall` / `isOnCeiling` | boolean | — | **Output**: what was touched this move. || `floorNormal` | Vec2 | — | **Output**: normal of the last floor touched. || `realVelocity` | Vec2 | — | **Output**: actual displacement / dt after collisions. |+<Aside type="note">`maxSlides`, `skinWidth`, `snapLength`, and `slideOnCeiling` remain on+the component for the standalone `moveAndSlide` resolver (`esengine/physics`); the+native mover the live controller uses does its own iteration and gap handling, so it+ignores them. Stair/slope floor-snap (`snapLength`) is a planned mover addition.</Aside>+## Best practices- **Fixed timestep**: apply continuous forces and read `PhysicsEvents` *every frame*,diff --git a/docs/astro/src/content/docs/zh-cn/guides/physics.mdx b/docs/astro/src/content/docs/zh-cn/guides/physics.mdxindex 537534876..aea56807e 100644--- a/docs/astro/src/content/docs/zh-cn/guides/physics.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/physics.mdx@@ -205,7 +205,9 @@ physics.destroyJoint(bodyA);## 角色控制器想让玩家沿着表面行走、而不是像动态刚体那样翻滚,加一个 `CharacterController`。每步从玩法设它-的 `velocity`;系统会解析一次运动学 move-and-slide,把结果写回,并报告它碰到了什么:+的 `velocity`;控制器用 Box2D 的**原生运动学 mover**(`b2World_CollideMover` ++`b2SolvePlanes`)推进一步——把身体碰撞成接触*平面*,再解出一次去穿插的滑动,所以贴地的角色能+干净地移动和起跳,而不是粘在地面上。它把结果写回,并报告碰到了什么:```typescriptimport { defineSystem, Query, Mut, CharacterController } from 'esengine';@@ -218,20 +220,25 @@ const drive = defineSystem([Query(Mut(CharacterController))], (q) => {});```+给实体加一个碰撞体(mover 形状由它推导——盒子会内接成沿长轴的胶囊);若希望别的刚体能撞到角色,+再加一个**运动学(Kinematic)** `RigidBody`。mover 会自动排除角色自身的刚体,所以它的 `maskBits`+不必刻意避开自身的碰撞层。用固定步长的系统驱动 `velocity` 让运动与帧率无关;跳跃读 `isOnFloor`+边沿(会正确投递到 `FixedUpdate`——见 [输入](/docs/zh-cn/guides/input/#固定步长物理))。+| 属性 | 类型 | 默认 | 说明 ||---|---|---|---|| `velocity` | Vec2 | `{0, 0}` | 期望速度(世界像素/秒,每步设置)。 || `up` | Vec2 | `{0, 1}` | 用于地面/天花板分类的上方向。 || `floorMaxAngle` | number | `0.785` | 相对 `up` 的最大可行走坡度,弧度(45°)。 |-| `maxSlides` | number | `4` | 每次移动的滑动迭代次数(拐角需要更多)。 |-| `skinWidth` | number | `1` | 与表面保持的间隙(px),避免粘住。 |-| `snapLength` | number | `0` | 向下探测(px)以贴住斜坡/台阶;`0` = 关。 |-| `slideOnCeiling` | boolean | `true` | 沿天花板滑动 vs 停止移动。 || `maskBits` | number | `0xFFFF` | 阻挡角色的层。 || `isOnFloor` / `isOnWall` / `isOnCeiling` | boolean | — | **输出**:这次移动碰到了什么。 || `floorNormal` | Vec2 | — | **输出**:最后接触地面的法线。 || `realVelocity` | Vec2 | — | **输出**:碰撞后的实际位移 / dt。 |+<Aside type="note">`maxSlides`、`skinWidth`、`snapLength`、`slideOnCeiling` 仍保留在组件上,+供独立的 `moveAndSlide` 解析器(`esengine/physics`)使用;实际控制器用的原生 mover 自带迭代与+间隙处理,会忽略它们。斜坡/台阶的地面吸附(`snapLength`)是 mover 计划中的补充。</Aside>+## 最佳实践- **固定时间步**:*每帧*施加持续力、读 `PhysicsEvents`,因为物理独立于帧 delta 做子步。diff --git a/sdk/src/physics/CharacterController.ts b/sdk/src/physics/CharacterController.tsindex 99acb3fea..4c2378a3f 100644--- a/sdk/src/physics/CharacterController.ts+++ b/sdk/src/physics/CharacterController.ts@@ -2,16 +2,20 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file CharacterController.ts- * @brief Kinematic move-and-slide character controller (Godot CharacterBody2D- * semantics) built on the existing Box2D shape-cast queries.+ * @brief Kinematic character controller (Godot CharacterBody2D semantics) on top+ * of Box2D v3's native kinematic mover.*- * The controller is gameplay logic, so it lives entirely in the SDK and never- * touches C++: it reads the entity's own collider for the cast shape, sweeps it- * through the world with `Physics.shapeCast*`, and resolves collisions by sliding- * along surfaces. It writes the resolved pose to `Transform`; if the entity also- * carries a Kinematic `RigidBody`, `PhysicsStepSystem` then pushes that Transform- * into Box2D so dynamic bodies see the character. Movement itself is query-driven,- * so a body is recommended (for others to collide with) but not required.+ * The controller reads the entity's own collider, derives a capsule mover from it,+ * and advances one step via `Physics.moveCharacter` — Box2D's `b2World_CollideMover`+ * + `b2SolvePlanes`, which collides the capsule into contact *planes* and solves a+ * depenetrating slide. That resolves a character resting on the ground with valid+ * normals (a generic shape cast reports the resting contact as a zero-normal+ * fraction-0 hit and wedges). It writes the resolved pose to `Transform`; if the+ * entity also carries a Kinematic `RigidBody`, `PhysicsStepSystem` then pushes that+ * Transform into Box2D so dynamic bodies see the character.+ *+ * `moveAndSlide` below is the earlier pure JS resolver, kept as a standalone utility+ * (and for its tests); the live system uses the native mover.** Units: `velocity`/positions are world pixels (matching `Transform`); collider* dimensions are meters and are scaled to pixels via `Physics.getPixelsPerUnit()`.@@ -249,33 +253,32 @@ function resolveCastShape(world: World, entity: Entity, ppu: number): CastShapereturn null;}-/**- * Build the nearest-blocking-hit cast for one character: sweep its shape, drop the- * character's own body, and keep the lowest-fraction hit.- */-function makeCast(physics: Physics, self: Entity, shape: CastShape, maskBits: number): SlideCast {- const t: Vec2 = { x: 0, y: 0 };- const c: Vec2 = { x: 0, y: 0 };- return (ox, oy, dx, dy) => {- c.x = ox + shape.ox; c.y = oy + shape.oy;- t.x = dx; t.y = dy;- let hits;- if (shape.kind === 'box') hits = physics.shapeCastBox(c, { x: shape.hx, y: shape.hy }, 0, t, maskBits);- else if (shape.kind === 'circle') hits = physics.shapeCastCircle(c, shape.r, t, maskBits);- else hits = physics.shapeCastCapsule({ x: c.x, y: c.y + shape.halfH }, { x: c.x, y: c.y - shape.halfH }, shape.r, t, maskBits);-- let best: SlideHit | null = null;- for (const h of hits) {- if (h.entity === self) continue;- if (best === null || h.fraction < best.fraction) best = { nx: h.normal.x, ny: h.normal.y, fraction: h.fraction };- }- return best;- };+/** The capsule the native mover sweeps, derived from the collider (pixels). A box+ * becomes a capsule inscribed along its longer axis; a circle a zero-length capsule. */+interface MoverCapsule { c1: Vec2; c2: Vec2; radius: number }++function moverCapsuleFromShape(s: CastShape): MoverCapsule {+ if (s.kind === 'circle') {+ return { c1: { x: s.ox, y: s.oy }, c2: { x: s.ox, y: s.oy }, radius: s.r };+ }+ if (s.kind === 'capsule') {+ return { c1: { x: s.ox, y: s.oy + s.halfH }, c2: { x: s.ox, y: s.oy - s.halfH }, radius: s.r };+ }+ // Box: place the capsule spine along the longer axis, radius = shorter half-extent.+ if (s.hy >= s.hx) {+ const half = s.hy - s.hx;+ return { c1: { x: s.ox, y: s.oy + half }, c2: { x: s.ox, y: s.oy - half }, radius: s.hx };+ }+ const half = s.hx - s.hy;+ return { c1: { x: s.ox + half, y: s.oy }, c2: { x: s.ox - half, y: s.oy }, radius: s.hy };}/**- * Register the move-and-slide system. Runs in FixedUpdate ahead of the physics- * step so the resolved Transform is what gets pushed into a kinematic body.+ * 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.+ * Movement is delegated to Box2D's native kinematic mover (collide-into-planes ++ * depenetrating slide), which — unlike a generic shape cast — resolves a character+ * resting on the ground with valid contact normals instead of wedging on it.*/export function registerCharacterControllerSystem(app: App): void {app.addSystemToSchedule(@@ -296,6 +299,7 @@ export function registerCharacterControllerSystem(app: App): void {for (const [entity, cc] of query) {const shape = resolveCastShape(world, entity, ppu);if (!shape) continue;+ const mover = moverCapsuleFromShape(shape);// Transform is C++-backed: get() yields a converted copy, so the// resolved pose must be written back with set() (mutating the copy@@ -303,30 +307,21 @@ export function registerCharacterControllerSystem(app: App): void {const transform = world.get(entity, Transform) as TransformData;const startX = transform.position.x;const startY = transform.position.y;- const cast = makeCast(physics, entity, shape, cc.maskBits);-- const r = moveAndSlide({- startX, startY,- motionX: cc.velocity.x * dt,- motionY: cc.velocity.y * dt,- velX: cc.velocity.x,- velY: cc.velocity.y,- upX: cc.up.x, upY: cc.up.y,- floorMaxAngle: cc.floorMaxAngle,- maxSlides: cc.maxSlides,- skinWidth: cc.skinWidth,- snapLength: cc.snapLength,- slideOnCeiling: cc.slideOnCeiling,- wasOnFloor: cc.isOnFloor,- }, cast);++ const r = physics.moveCharacter(+ transform.position, mover.c1, mover.c2, mover.radius,+ cc.velocity, dt, cc.up, Math.cos(cc.floorMaxAngle),+ cc.maskBits, entity, ppu,+ );+ if (!r) continue;// Write both local and world position: PhysicsStepSystem runs next// in this same FixedUpdate and pushes worldPosition into a kinematic// body, before TransformSystem re-derives world from local.- transform.position.x = r.x;- transform.position.y = r.y;- transform.worldPosition.x = r.x;- transform.worldPosition.y = r.y;+ transform.position.x = startX + r.dx;+ transform.position.y = startY + r.dy;+ transform.worldPosition.x = transform.position.x;+ transform.worldPosition.y = transform.position.y;world.set(entity, Transform, transform);cc.velocity.x = r.velX;@@ -336,8 +331,8 @@ export function registerCharacterControllerSystem(app: App): void {cc.isOnCeiling = r.isOnCeiling;cc.floorNormal.x = r.floorNormalX;cc.floorNormal.y = r.floorNormalY;- cc.realVelocity.x = (r.x - startX) * invDt;- cc.realVelocity.y = (r.y - startY) * invDt;+ cc.realVelocity.x = r.dx * invDt;+ cc.realVelocity.y = r.dy * invDt;}},{ name: 'CharacterControllerSystem', runBefore: ['PhysicsStepSystem'] },diff --git a/sdk/src/physics/Physics.ts b/sdk/src/physics/Physics.tsindex c9d5607db..d358cf864 100644--- a/sdk/src/physics/Physics.ts+++ b/sdk/src/physics/Physics.ts@@ -21,6 +21,7 @@ import {type RaycastHit,type ShapeCastHit,type MassData,+ type MoverResult,} from './PhysicsTypes';// =============================================================================@@ -242,6 +243,37 @@ export class Physics {return this.readShapeCastBuffer_(count, ppu);}+ /**+ * Advance a kinematic capsule character one step against the world using Box2D's+ * native mover (collide-into-planes + depenetrating slide). Unlike a raw shape+ * cast this resolves resting/touching contacts with valid normals, so a grounded+ * character slides instead of wedging. Capsule endpoints/radius and `pos`/`velocity`+ * are world pixels; `dt` seconds; `up` a unit vector; `floorCos = cos(floorMaxAngle)`.+ * `self` is excluded from the collision. Returns null if the module isn't ready.+ */+ moveCharacter(+ pos: Vec2, c1: Vec2, c2: Vec2, radius: number,+ velocity: Vec2, dt: number, up: Vec2, floorCos: number,+ maskBits: number, self: Entity, ppu = this.ppu_,+ ): MoverResult | null {+ const invPpu = 1 / ppu;+ const ok = this.module_._physics_moveCharacter(+ pos.x * invPpu, pos.y * invPpu,+ c1.x * invPpu, c1.y * invPpu, c2.x * invPpu, c2.y * invPpu, radius * invPpu,+ velocity.x * invPpu, velocity.y * invPpu, dt,+ up.x, up.y, floorCos, maskBits, self >>> 0,+ );+ if (!ok) return null;+ const base = this.module_._physics_getMoveCharacterBuffer() >> 2;+ const h = this.module_.HEAPF32;+ return {+ dx: h[base] * ppu, dy: h[base + 1] * ppu,+ velX: h[base + 2] * ppu, velY: h[base + 3] * ppu,+ isOnFloor: h[base + 4] !== 0, isOnWall: h[base + 5] !== 0, isOnCeiling: h[base + 6] !== 0,+ floorNormalX: h[base + 7], floorNormalY: h[base + 8],+ };+ }+overlapAABB(min: Vec2, max: Vec2, maskBits = 0xFFFF, ppu = this.ppu_): Entity[] {const invPpu = 1 / ppu;const count = this.module_._physics_overlapAABB(diff --git a/sdk/src/physics/PhysicsModuleLoader.ts b/sdk/src/physics/PhysicsModuleLoader.tsindex daa334bf2..f82ddea92 100644--- a/sdk/src/physics/PhysicsModuleLoader.ts+++ b/sdk/src/physics/PhysicsModuleLoader.ts@@ -140,6 +140,11 @@ export interface PhysicsWasmModule {radius: number, translationX: number, translationY: number, maskBits: number): number;_physics_getShapeCastBuffer(): number;+ _physics_moveCharacter(px: number, py: number, c1x: number, c1y: number, c2x: number, c2y: number,+ radius: number, velX: number, velY: number, dt: number, upX: number, upY: number, floorCos: number,+ maskBits: number, selfEntity: number): number;+ _physics_getMoveCharacterBuffer(): number;+_physics_overlapAABB(minX: number, minY: number, maxX: number, maxY: number, maskBits: number): number;_physics_getBodyMass(entityId: number): number;diff --git a/sdk/src/physics/PhysicsTypes.ts b/sdk/src/physics/PhysicsTypes.tsindex 4e6e3874e..4eaf3ffbb 100644--- a/sdk/src/physics/PhysicsTypes.ts+++ b/sdk/src/physics/PhysicsTypes.ts@@ -97,6 +97,20 @@ export interface RaycastHit {export type ShapeCastHit = RaycastHit;+/** One step of the native kinematic mover: resolved displacement (pixels), slid+ * velocity (pixels/s), and the surface contact classification. */+export interface MoverResult {+ dx: number;+ dy: number;+ velX: number;+ velY: number;+ isOnFloor: boolean;+ isOnWall: boolean;+ isOnCeiling: boolean;+ floorNormalX: number;+ floorNormalY: number;+}+export interface MassData {mass: number;inertia: number;diff --git a/sdk/tests/mover-smoke.mjs b/sdk/tests/mover-smoke.mjsnew file mode 100644index 000000000..32392fa19--- /dev/null+++ b/sdk/tests/mover-smoke.mjs@@ -0,0 +1,60 @@+// Headless validation of the native character mover (physics_moveCharacter).+// Loads the built physics wasm directly, builds a static ground, and checks that a+// resting character slides horizontally (the wedge bug) and a falling one lands.+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 });++// Static ground: box 8×0.4 m centered at (0,-2.5) → top surface at y=-2.3.+const GROUND = 2, SELF = 9;+m._physics_init(0, -9.81, 1 / 60, 4, 30, 10, 3);+m._physics_createBody(GROUND, 0 /*static*/, 0, -2.5, 0, 1, 0, 0, 0, 0);+m._physics_addBoxShape(GROUND, 4.0, 0.2, 0, 0, 0, 1, 0.3, 0, 0, /*cat*/1, /*mask*/0xffff);++const buf = () => {+ const b = m._physics_getMoveCharacterBuffer() >> 2;+ const h = m.HEAPF32;+ return { dx: h[b], dy: h[b + 1], vx: h[b + 2], vy: h[b + 3], floor: h[b + 4], wall: h[b + 5], ceil: h[b + 6] };+};+// capsule from a 0.16×0.24 box: spine ±0.08 on Y, radius 0.16+const move = (py, vx, vy) => {+ const ok = m._physics_moveCharacter(0, py, 0, 0.08, 0, -0.08, 0.16, vx, vy, 1 / 60, 0, 1, Math.cos(Math.PI / 4), 0xfffd, SELF);+ return ok ? buf() : null;+};++let pass = true;+const check = (name, cond, detail) => { console.log(`${cond ? 'PASS' : 'FAIL'} ${name} ${detail}`); if (!cond) pass = false; };++// 1) Resting on the ground (center at -2.06 → feet at -2.30), pushing right.+const rest = move(-2.06, 3.2, -0.5);+check('resting slides horizontally', rest && rest.dx > 0.02, `dx=${rest?.dx.toFixed(4)} (want >0.02)`);+check('resting reads on-floor', rest && rest.floor === 1, `floor=${rest?.floor}`);+check('resting keeps horizontal velocity', rest && rest.vx > 1.0, `vx=${rest?.vx.toFixed(3)}`);++// 2) Falling from well above the ground — moves down freely, not grounded.+const air = move(0.5, 0, -5);+check('airborne falls', air && air.dy < -0.05, `dy=${air?.dy.toFixed(4)} (want <-0.05)`);+check('airborne not grounded', air && air.floor === 0, `floor=${air?.floor}`);++// 3) Realistic fall: start 1.3m above the ground, integrate gravity each frame,+// confirm it lands, grounds, and settles at the surface (feet ≈ -2.30 → center ≈ -2.06).+let py = -1.0, vy = 0, grounded = false;+for (let i = 0; i < 180; i++) {+ vy += -16 * (1 / 60); // game gravity ≈ -1600 px/s² = -16 m/s²+ const r = move(py, 0, vy);+ py += r.dy;+ vy = r.vy; // mover clips downward velocity on contact+ if (r.floor) grounded = true;+}+check('fall lands and grounds', grounded, `grounded=${grounded}`);+check('rests at the surface', Math.abs(py - -2.06) < 0.05, `center=${py.toFixed(3)} (want ≈-2.06)`);+check('does not sink through', py > -2.35, `center=${py.toFixed(3)} (floor top ~-2.30)`);++console.log(pass ? '\nMOVER_SMOKE PASS' : '\nMOVER_SMOKE FAIL');+process.exit(pass ? 0 : 1);diff --git a/src/esengine/bindings/PhysicsQueries.cpp b/src/esengine/bindings/PhysicsQueries.cppindex 21dd5e5b5..935ced9f3 100644--- a/src/esengine/bindings/PhysicsQueries.cpp+++ b/src/esengine/bindings/PhysicsQueries.cpp@@ -2,6 +2,8 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team#include "PhysicsContext.hpp"+#include <cfloat>+static float raycastCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) {if (g_raycastBuffer.size() / RAYCAST_STRIDE >= MAX_RAYCAST_HITS) return 0.0f;@@ -44,6 +46,33 @@ static float shapeCastCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, freturn 1.0f;}+// —— Kinematic character mover (Box2D v3 native: CollideMover + SolvePlanes) ——+// The generic shape cast reports a resting/touching contact as fraction 0 with a+// zero normal, which stalls a hand-rolled move-and-slide. The mover collides the+// capsule against the world into *planes* (each with a valid normal) and solves a+// depenetrating slide — the intended path for characters standing on ground.+static constexpr int MAX_MOVER_PLANES = 32;+static b2CollisionPlane g_moverPlanes[MAX_MOVER_PLANES];+static int g_moverPlaneCount = 0;+static uint32_t g_moverSelfEntity = 0xFFFFFFFF;+static float g_moverBuffer[9] = {};++static bool moverPlaneCallback(b2ShapeId shapeId, const b2PlaneResult* pr, void* context) {+ (void)context;+ if (!pr->hit) return true;+ // Never collide the mover with its own body (entity filter — robust regardless+ // of the collision-category setup).+ if (entityFromShape(shapeId) == g_moverSelfEntity) return true;+ if (g_moverPlaneCount < MAX_MOVER_PLANES) {+ g_moverPlanes[g_moverPlaneCount].plane = pr->plane;+ g_moverPlanes[g_moverPlaneCount].pushLimit = FLT_MAX;+ g_moverPlanes[g_moverPlaneCount].push = 0.0f;+ g_moverPlanes[g_moverPlaneCount].clipVelocity = true;+ g_moverPlaneCount++;+ }+ return true;+}+extern "C" {EMSCRIPTEN_KEEPALIVE@@ -168,4 +197,65 @@ int physics_overlapAABB(float minX, float minY, float maxX, float maxY, uint32_treturn static_cast<int>(g_overlapBuffer.size());}+// Move a capsule character one step. All lengths are meters (the JS wrapper scales+// px⇄m). Writes the result buffer [dx, dy, velX, velY, onFloor, onWall, onCeiling,+// floorNx, floorNy] and returns 1 on success (0 if the world is gone).+EMSCRIPTEN_KEEPALIVE+int physics_moveCharacter(float px, float py, float c1x, float c1y, float c2x, float c2y, float radius,+ float velX, float velY, float dt, float upX, float upY, float floorCos,+ uint32_t maskBits, uint32_t selfEntity) {+ if (!b2World_IsValid(g_ctx.worldId)) return 0;+ g_moverSelfEntity = selfEntity;++ b2Vec2 pos = {px, py};+ b2Vec2 up = {upX, upY};+ b2Vec2 target = {px + velX * dt, py + velY * dt};++ b2QueryFilter filter = b2DefaultQueryFilter();+ filter.maskBits = static_cast<uint64_t>(maskBits);++ const float tolerance = 0.001f;+ for (int iteration = 0; iteration < 5; ++iteration) {+ g_moverPlaneCount = 0;+ b2Capsule mover;+ mover.center1 = {pos.x + c1x, pos.y + c1y};+ mover.center2 = {pos.x + c2x, pos.y + c2y};+ mover.radius = radius;+ b2World_CollideMover(g_ctx.worldId, &mover, filter, moverPlaneCallback, nullptr);+ b2PlaneSolverResult result = b2SolvePlanes(b2Sub(target, pos), g_moverPlanes, g_moverPlaneCount);+ pos = b2Add(pos, result.translation);+ if (b2LengthSquared(result.translation) < tolerance * tolerance) break;+ }++ b2Vec2 vel = {velX, velY};+ b2Vec2 newVel = b2ClipVector(vel, g_moverPlanes, g_moverPlaneCount);++ // Classify the final contact planes against the up axis.+ bool onFloor = false, onWall = false, onCeiling = false;+ float fnx = 0.0f, fny = 0.0f;+ for (int i = 0; i < g_moverPlaneCount; ++i) {+ b2Vec2 n = g_moverPlanes[i].plane.normal;+ float d = n.x * upX + n.y * upY;+ if (d >= floorCos) { onFloor = true; fnx = n.x; fny = n.y; }+ else if (d <= -floorCos) { onCeiling = true; }+ else { onWall = true; }+ }++ g_moverBuffer[0] = pos.x - px;+ g_moverBuffer[1] = pos.y - py;+ g_moverBuffer[2] = newVel.x;+ g_moverBuffer[3] = newVel.y;+ g_moverBuffer[4] = onFloor ? 1.0f : 0.0f;+ g_moverBuffer[5] = onWall ? 1.0f : 0.0f;+ g_moverBuffer[6] = onCeiling ? 1.0f : 0.0f;+ g_moverBuffer[7] = fnx;+ g_moverBuffer[8] = fny;+ return 1;+}++EMSCRIPTEN_KEEPALIVE+uintptr_t physics_getMoveCharacterBuffer() {+ return reinterpret_cast<uintptr_t>(g_moverBuffer);+}+} // extern "C"