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
feat(physics): a side-on character runs, jumps and forgives, on a mover that handles slopes, ledges and platforms
yhhab176cb24b0a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9f5e7e656..8dcf95a35 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **A side-on character comes ready to run and jump.** `PlatformerController2D` beside a `CharacterController2D` reads the keyboard or a game's input, and has coyote time, a jump buffer, jump cut, air jumps and a drop through one-way platforms. `CharacterController2D` gains `stepHeight`, `followPlatform` (it rides what it stands on, sideways too), `dynamicBodies` (block, push or ignore them), `constantSlopeSpeed` and `dropThrough`, and reports `floorEntity` and `floorVelocity`. The 2D platformer template and example use it.- **A 2D character can be rigged in the editor, with no other program.** Right-click an image to create an `.esrig`, then cut it into parts, drag out bones, cover the parts with a mesh, bind by distance and paint weights with add, remove and smooth brushes, and push vertices into named deforms, all on one canvas that can try poses without changing the rig. Saving writes an `.esmesh` and an `.esprefab` beside it, so a built game carries no authoring data. Bones are ordinary entities, so clips, the Animator's blends, layers and masks all reach them, and a deform is a `MeshMorph` weight clips can key.- **2D bones can reach for things and follow each other.** `IK2D` on the last bone of a limb bends it to a target after the animation has played, exactly for two bones and iteratively for more, with a weight clips can key. `BoneConstraint2D` limits a joint's rotation, which a chain through it keeps to, or copies another entity's rotation or position, or looks at it. Both follow a character mirrored by a negative scale. `esengine/rig2d` also makes all of this from code.- **A tile layer can be dug, blown up and rebuilt while the game runs.** `createDestructibleTilemap` in `esengine/tilemap` gives a layer tiles with hardness that wear down over several blows, circular explosions with falloff that walls can shelter from, and placing and filling, with one list of what changed for drops and effects. The neighbouring autotiles re-resolve, `createNavGrid` or `syncNavGrid` keeps a navigation grid in step one cell at a time, and `toJSON` and `load` save only the cells that differ from the map it started as, refusing a damaged save whole. On a streamed world, `publishChunk` lays a player's changes over what the generator made, so a chunk let go and made again comes back as it was left.@@ -23,11 +24,15 @@ published separately; it ships inside the editor.### Changed+- **A 2D character stands still on a walkable slope, and a steeper one is a wall.** It used to drift down any slope and could walk up one past `floorMaxAngle`. `stopOnSlope` and `blockSteepSlopes` turn each back off.- **Editing a tile no longer replaces the colliders around it.** A tile edit used to destroy and remake every collider in its chunk, which ended a body's contact with the floor it stood on and woke what was asleep there. Now only the colliders whose shape changed are replaced.- **A row of tiles being edited uploads a piece of itself.** One changed tile re-uploaded its whole row of chunks, over a megabyte when the row is full. A row that changes is now held in pieces of four chunks, so an edit uploads about an eighth of that, for up to seven more draws in that row until it has rested. A static map is drawn as before.### Fixed+- **A trigger no longer stops a 2D character.** The mover took a sensor for a wall and for a floor.+- **A 2D character honours one-way platforms.** It was stopped from below by the mover as if they were solid.+- **A 2D character under a parent moves in the world.** Its local position was handed to the mover as a world position.- **A skinned mesh is not culled for where its entity stands.** A skinned mesh is placed by its joints, and was culled by its entity's box in the bind pose, so a body an animation carried away from its root vanished when that box left the view, in 2D and 3D alike. It is now culled around its joints.- **A texture stays on a scene that rescans as it is placed.** Two project rescans in a row started two loads of one texture, and the second to finish could release the one the scene was drawing with. The entity then drew white and stayed white, since the load counted as started and nothing asked again. An asset now loads one at a time and loads again afterwards when it was asked for meanwhile.- **A tile's custom properties in an `.estileset` reach the game.** `getTileProperty` answered nothing on a layer painted from an `.estileset`; only Tiled maps carried them. Replacing a tileset blanks the properties of the old one.diff --git a/desktop b/desktopindex 1b8d53fa6..d42be8143 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 1b8d53fa641997ec9b8af6eac93400a3ca4838b8+Subproject commit d42be8143ad2e44d5eb2dd72cea70c5f5de10a0ediff --git a/docs/astro/src/content/docs/gameplay/physics.mdx b/docs/astro/src/content/docs/gameplay/physics.mdxindex 5dd50c580..139036a87 100644--- a/docs/astro/src/content/docs/gameplay/physics.mdx+++ b/docs/astro/src/content/docs/gameplay/physics.mdx@@ -468,15 +468,68 @@ body automatically, so its `maskBits` need not avoid its own collision layer. Dr| `snapLength` | number | `0` | Down-probe length (pixels) that glues the body to descending stairs/slopes; `0` disables it. Skipped while rising, so a jump still leaves the ground. || `slideOnCeiling` | boolean | `true` | When `false`, a ceiling hit cancels the upward velocity instead of sliding along it. || `maskBits` | number | `0xFFFF` | Layers that block the character. |+| `stepHeight` | number | `0` | The highest ledge it walks up without jumping (pixels). `0` leaves only what its rounded foot rides over. |+| `stopOnSlope` | boolean | `true` | Stand still on a walkable slope, and walk along it rather than into it. |+| `constantSlopeSpeed` | boolean | `false` | Keep the asked speed along the slope. Off, the speed across the ground is what stays, so a climb takes as long as the same distance on the flat. |+| `blockSteepSlopes` | boolean | `true` | A slope past `floorMaxAngle` is a wall: walking into it does not climb it, and it slides down. |+| `followPlatform` | boolean | `true` | Ride what it stands on, sideways as well as up and down. |+| `dynamicBodies` | enum | `Block` | What a dynamic body does to it: `Block` stops it, `Push` stops it and is pushed with up to `pushForce`, `Ignore` lets it through. |+| `pushForce` | number | `40` | The force of a push, newtons. |+| `dropThrough` | boolean | `false` | Pass through one-way platforms while on. || `isOnFloor` / `isOnWall` / `isOnCeiling` | boolean | — | **Output**: what was touched this move. || `floorNormal` | Vec2 | — | **Output**: normal of the last floor touched. |+| `floorEntity` | Entity | — | **Output**: what it stands on, `0` for nothing. |+| `floorVelocity` | Vec2 | — | **Output**: how fast that is carrying it, pixels/second. || `realVelocity` | Vec2 | — | **Output**: actual displacement / dt after collisions. |<Aside type="note">`skinWidth`, `maxSlides`, `snapLength`, and `slideOnCeiling` are honored bythe live native mover **and** by the standalone `moveAndSlide` resolver (`esengine/physics`),so they behave the same whichever path you use. The defaults suit a standard character; thecommon tweak is a small `snapLength` (a few pixels) to keep the character glued to descending-stairs and slopes.</Aside>+stairs and slopes. The options after `maskBits` are the live mover's alone; `moveAndSlide` has none of them.</Aside>++A trigger never stops a character: a sensor has nothing to say about where it may go.++### Platformer controller++`CharacterController2D` moves what it is told to. For a side-on game add a+`PlatformerController2D` beside it, and no system of your own: it reads the keyboard, runs,+jumps and falls, with the forgiveness a platformer is judged on. A jump pressed+`jumpBuffer` seconds before landing still happens, and so does one pressed `coyoteTime`+seconds after running off a ledge.++```typescript+import { Transform, CapsuleCollider2D, CharacterController2D, CharacterDynamicBodies, PlatformerController2D } from 'esengine';++const player = world.spawn();+world.insert(player, Transform, { position: { x: 0, y: 100, z: 0 } });+world.insert(player, CapsuleCollider2D, { radius: 0.1, halfHeight: 0.15 });+world.insert(player, CharacterController2D, { stepHeight: 12, snapLength: 8, dynamicBodies: CharacterDynamicBodies.Push });+world.insert(player, PlatformerController2D, { moveSpeed: 260, jumpSpeed: 620 });+```++It moves with A/D or the arrows, jumps with Space, W or Up, and drops through a one-way+platform with Down or S and jump. Set `readKeyboard: false` to drive it from a game, a+touch screen or an AI instead: write `moveInput` and `jumpHeld`, and set `jumpPressed` or+`dropPressed` for the next fixed step to consume. A press is latched per rendered frame,+so a tap between two fixed steps is not lost.++| Property | Type | Default | Description |+|---|---|---|---|+| `moveSpeed` | number | `260` | Top running speed, pixels/second. |+| `groundAcceleration` / `airAcceleration` | number | `2400` / `1500` | How fast it reaches that speed. |+| `groundDeceleration` / `airDeceleration` | number | `3000` / `900` | How fast it sheds it when the input centres. |+| `gravity` | number | `1600` | Downward acceleration, pixels/second². |+| `fallGravityScale` | number | `1.25` | Gravity multiplier while falling. Above 1 lands faster than it rose. |+| `maxFallSpeed` | number | `1000` | The fastest it falls. |+| `jumpSpeed` | number | `620` | Upward speed a jump starts with; `0` disables jumping. |+| `jumpCut` | number | `0.5` | How much of a rising speed survives letting go of jump. `1` makes every jump full height. |+| `coyoteTime` | number | `0.1` | Seconds after leaving the ground that a jump still counts as from the ground. |+| `jumpBuffer` | number | `0.12` | Seconds a jump pressed too early is remembered, to happen on landing. |+| `airJumps` | number | `0` | Extra jumps before landing again. |+| `dropTime` | number | `0.2` | Seconds a drop through a one-way platform lasts. |+| `keepPlatformVelocity` | boolean | `true` | A jump keeps the velocity of the platform it left. |+| `readKeyboard` | boolean | `true` | Read the keyboard itself. |## Debug drawdiff --git a/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdxindex 2cc4fd4f2..a1f62fa44 100644--- a/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx+++ b/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx@@ -116,6 +116,14 @@ const spawnBall = defineSystem([Commands()], (cmds) => {| `isSensor` | boolean | `false` | 检测重叠但无物理响应(触发器)。 || `categoryBits` | number | `0x0001` | 该碰撞体所在的碰撞层。 || `maskBits` | number | `0xFFFF` | 它与哪些层碰撞。 |+| `stepHeight` | number | `0` | 不用跳就能走上去的最高台阶(像素)。`0` 表示只有圆形脚底自己能滑过去的高度。 |+| `stopOnSlope` | boolean | `true` | 在可行走的斜坡上站住不动,并沿坡面走,而不是往坡里走。 |+| `constantSlopeSpeed` | boolean | `false` | 沿坡面保持要求的速度。关闭时保持的是水平速度,上坡和走同样水平距离的平地用时相同。 |+| `blockSteepSlopes` | boolean | `true` | 超过 `floorMaxAngle` 的斜坡算作墙:走过去爬不上去,还会滑下来。 |+| `followPlatform` | boolean | `true` | 跟随脚下的物体移动,水平和上下都跟。 |+| `dynamicBodies` | enum | `Block` | 动态刚体对角色的作用:`Block` 挡住角色,`Push` 挡住并被以不超过 `pushForce` 的力推动,`Ignore` 直接穿过。 |+| `pushForce` | number | `40` | 推动的力,牛顿。 |+| `dropThrough` | boolean | `false` | 开启期间穿过单向平台。 || `enabled` | boolean | `true` | 关掉该形状。刚体的速度、关节和其它碰撞体都留着,只有这一个不再存在——没有东西会撞上它,查询、射线和角色控制器的扫掠也都找不到它。 || 组件 | 形状参数 |@@ -434,12 +442,53 @@ app.addSystemToSchedule(Schedule.FixedUpdate, drive); // moveX / jumpPressed:| `maskBits` | number | `0xFFFF` | 阻挡角色的层。 || `isOnFloor` / `isOnWall` / `isOnCeiling` | boolean | — | **输出**:这次移动碰到了什么。 || `floorNormal` | Vec2 | — | **输出**:最后接触地面的法线。 |+| `floorEntity` | Entity | — | **输出**:脚下的实体,没有则为 `0`。 |+| `floorVelocity` | Vec2 | — | **输出**:它带着角色移动的速度,像素/秒。 || `realVelocity` | Vec2 | — | **输出**:碰撞后的实际位移 / dt。 |<Aside type="note">`skinWidth`、`maxSlides`、`snapLength`、`slideOnCeiling` 由运行时原生 mover**以及**独立的 `moveAndSlide` 解析器(`esengine/physics`)共同遵循,两条路径行为一致。默认值适合普通角色;最常见的微调是给 `snapLength` 一个较小值(几个像素),让角色贴住下行的台阶和斜坡。</Aside>+`maskBits` 之后的这些选项只有实时 mover 支持,`moveAndSlide` 没有。触发器永远挡不住角色。++### 平台跳跃控制器++`CharacterController2D` 只按你给的速度移动。横版游戏在它旁边加一个 `PlatformerController2D`+就够了,不用写自己的系统:它读键盘、跑、跳、下落,并提供平台跳跃手感所依赖的宽容判定——+落地前 `jumpBuffer` 秒内按下的跳跃仍会触发,跑出边缘后 `coyoteTime` 秒内按下的跳跃也算从地面起跳。++```typescript+import { Transform, CapsuleCollider2D, CharacterController2D, CharacterDynamicBodies, PlatformerController2D } from 'esengine';++const player = world.spawn();+world.insert(player, Transform, { position: { x: 0, y: 100, z: 0 } });+world.insert(player, CapsuleCollider2D, { radius: 0.1, halfHeight: 0.15 });+world.insert(player, CharacterController2D, { stepHeight: 12, snapLength: 8, dynamicBodies: CharacterDynamicBodies.Push });+world.insert(player, PlatformerController2D, { moveSpeed: 260, jumpSpeed: 620 });+```++用 A/D 或方向键移动,Space、W 或上方向键跳跃,下方向键或 S 加跳跃穿过单向平台。把+`readKeyboard` 设为 `false` 后可由游戏、触屏或 AI 驱动:写 `moveInput` 和 `jumpHeld`,设置+`jumpPressed` 或 `dropPressed` 由下一个固定步消费。按键按渲染帧锁存,两个固定步之间的轻按不会丢。++| 属性 | 类型 | 默认 | 说明 |+|---|---|---|---|+| `moveSpeed` | number | `260` | 最高奔跑速度,像素/秒。 |+| `groundAcceleration` / `airAcceleration` | number | `2400` / `1500` | 达到该速度的加速度。 |+| `groundDeceleration` / `airDeceleration` | number | `3000` / `900` | 输入归零时的减速度。 |+| `gravity` | number | `1600` | 向下的加速度,像素/秒²。 |+| `fallGravityScale` | number | `1.25` | 下落时的重力倍率。大于 1 时落得比升得快。 |+| `maxFallSpeed` | number | `1000` | 最大下落速度。 |+| `jumpSpeed` | number | `620` | 起跳的向上速度;`0` 表示不能跳。 |+| `jumpCut` | number | `0.5` | 松开跳跃键后上升速度保留的比例。`1` 表示每次都跳满。 |+| `coyoteTime` | number | `0.1` | 离地后多少秒内起跳仍算从地面起跳。 |+| `jumpBuffer` | number | `0.12` | 提前按下的跳跃被记住多少秒,落地时触发。 |+| `airJumps` | number | `0` | 落地前的额外跳跃次数。 |+| `dropTime` | number | `0.2` | 穿过单向平台持续多少秒。 |+| `keepPlatformVelocity` | boolean | `true` | 起跳时保留所离开平台的速度。 |+| `readKeyboard` | boolean | `true` | 自己读键盘。 |+## 调试绘制物理插件会安装一个 **`Physics2DDebugDraw`** 资源——一个游戏内叠加层,通过diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 62cbf9099..491718501 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 176,- "experimental": 2918,+ "experimental": 2921,"deprecated": 3},- "total": 3209,+ "total": 3212,"subsystems": [{"id": "mobile-controls",diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex 9bc56b03c..ef1bc629d 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -191,6 +191,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {DistanceJoint3D: { category: 'physics', summary: 'Keeps two 3D bodies a distance apart: a rope, a rod, or a spring when a frequency is given.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },FixedJoint3D: { category: 'physics', summary: 'Locks two 3D bodies together in the pose they were placed in — no freedom at all.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },CharacterController2D: { category: 'physics', summary: 'Kinematic character movement that slides along walls, climbs slopes and reports ground contact.', doc: 'gameplay/physics', anchor: 'character-controller', anchorZh: '角色控制器' },+ PlatformerController2D: { category: 'physics', summary: 'Runs and jumps a CharacterController2D from the keyboard or a game, with coyote time, a jump buffer and dropping through one-way platforms.', doc: 'gameplay/physics', anchor: 'platformer-controller' },OneWayPlatform2D: { category: 'physics', summary: 'Makes a collider solid from one side only, so a body passes up through it and lands on top.', doc: 'gameplay/physics', anchor: 'one-way-platforms', anchorZh: '单向平台' },DistanceJoint2D: { category: 'physics', summary: 'Holds two bodies a fixed (or spring-limited) distance apart.', doc: 'gameplay/physics', anchor: 'joints', anchorZh: '关节' },HingeJoint2D: { category: 'physics', summary: 'Pins two bodies at a point and lets them rotate — a hinge, with optional limits and a motor.', doc: 'gameplay/physics', anchor: 'joints', anchorZh: '关节' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 8d5ce5b98..9ada30ca8 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -972,6 +972,63 @@"default": "65535","advanced": true},+ {+ "key": "stepHeight",+ "type": "number",+ "default": "0",+ "doc": "The highest ledge it walks up without jumping; 0 = only what its rounded foot rides over",+ "range": "≥ 0, step 1"+ },+ {+ "key": "stopOnSlope",+ "type": "boolean",+ "default": "true",+ "doc": "Stand still on a walkable slope, and walk it without gravity slowing or speeding it"+ },+ {+ "key": "constantSlopeSpeed",+ "type": "boolean",+ "default": "false",+ "doc": "Keep the speed asked for along a slope, rather than the speed across the ground",+ "advanced": true+ },+ {+ "key": "blockSteepSlopes",+ "type": "boolean",+ "default": "true",+ "doc": "A slope past the walkable angle is a wall to walk into. Off, it walks straight up"+ },+ {+ "key": "followPlatform",+ "type": "boolean",+ "default": "true",+ "doc": "Move with what it stands on"+ },+ {+ "key": "dynamicBodies",+ "type": "enum",+ "default": "Block",+ "doc": "How it meets dynamic bodies",+ "values": [+ "Block",+ "Push",+ "Ignore"+ ]+ },+ {+ "key": "pushForce",+ "type": "number",+ "default": "40",+ "doc": "The most force it pushes with",+ "range": "≥ 0"+ },+ {+ "key": "dropThrough",+ "type": "boolean",+ "default": "false",+ "doc": "Pass through one-way platforms while on",+ "advanced": true+ },{"key": "isOnFloor","type": "boolean",@@ -1001,6 +1058,18 @@"type": "Vec2","default": "(0, 0)","advanced": true+ },+ {+ "key": "floorEntity",+ "type": "Entity",+ "default": "none",+ "advanced": true+ },+ {+ "key": "floorVelocity",+ "type": "Vec2",+ "default": "(0, 0)",+ "advanced": true}],"animatable": [@@ -1013,10 +1082,16 @@"skinWidth","snapLength","maskBits",+ "stepHeight",+ "dynamicBodies",+ "pushForce","floorNormal.x","floorNormal.y","realVelocity.x",- "realVelocity.y"+ "realVelocity.y",+ "floorEntity",+ "floorVelocity.x",+ "floorVelocity.y"]},{@@ -5070,6 +5145,167 @@"seaOpacity"]},+ {+ "name": "PlatformerController2D",+ "source": "ts",+ "fields": [+ {+ "key": "moveSpeed",+ "type": "number",+ "default": "260",+ "range": "≥ 0"+ },+ {+ "key": "groundAcceleration",+ "type": "number",+ "default": "2400",+ "range": "≥ 0",+ "advanced": true+ },+ {+ "key": "airAcceleration",+ "type": "number",+ "default": "1500",+ "range": "≥ 0",+ "advanced": true+ },+ {+ "key": "groundDeceleration",+ "type": "number",+ "default": "3000",+ "range": "≥ 0",+ "advanced": true+ },+ {+ "key": "airDeceleration",+ "type": "number",+ "default": "900",+ "range": "≥ 0",+ "advanced": true+ },+ {+ "key": "gravity",+ "type": "number",+ "default": "1600",+ "range": "≥ 0"+ },+ {+ "key": "fallGravityScale",+ "type": "number",+ "default": "1.25",+ "doc": "Gravity multiplier while falling. Above 1 lands faster than it rose.",+ "range": "≥ 0, step 0.05",+ "advanced": true+ },+ {+ "key": "maxFallSpeed",+ "type": "number",+ "default": "1000",+ "range": "≥ 0",+ "advanced": true+ },+ {+ "key": "jumpSpeed",+ "type": "number",+ "default": "620",+ "doc": "Upward speed a jump starts with. 0 = cannot jump.",+ "range": "≥ 0"+ },+ {+ "key": "jumpCut",+ "type": "number",+ "default": "0.5",+ "doc": "How much of a rising speed survives letting go of jump. 1 makes every jump full height.",+ "range": "0–1, step 0.05"+ },+ {+ "key": "coyoteTime",+ "type": "number",+ "default": "0.1",+ "doc": "After leaving the ground, how long a jump still counts as from the ground.",+ "range": "≥ 0, step 0.01"+ },+ {+ "key": "jumpBuffer",+ "type": "number",+ "default": "0.12",+ "doc": "How long a jump pressed too early is remembered, to happen on landing.",+ "range": "≥ 0, step 0.01"+ },+ {+ "key": "airJumps",+ "type": "number",+ "default": "0",+ "doc": "Extra jumps before landing again.",+ "range": "≥ 0, step 1"+ },+ {+ "key": "dropTime",+ "type": "number",+ "default": "0.2",+ "doc": "How long a drop through a one-way platform lasts.",+ "range": "≥ 0, step 0.01"+ },+ {+ "key": "keepPlatformVelocity",+ "type": "boolean",+ "default": "true"+ },+ {+ "key": "readKeyboard",+ "type": "boolean",+ "default": "true",+ "doc": "Move with A/D or the arrows, jump with Space, W or Up, drop with Down or S and jump. Off, a game writes the inputs itself."+ },+ {+ "key": "moveInput",+ "type": "number",+ "default": "0",+ "range": "-1–1, step 0.1",+ "advanced": true+ },+ {+ "key": "jumpHeld",+ "type": "boolean",+ "default": "false",+ "advanced": true+ },+ {+ "key": "jumpPressed",+ "type": "boolean",+ "default": "false",+ "advanced": true+ },+ {+ "key": "dropPressed",+ "type": "boolean",+ "default": "false",+ "advanced": true+ },+ {+ "key": "enabled",+ "type": "boolean",+ "default": "true"+ }+ ],+ "animatable": [+ "moveSpeed",+ "groundAcceleration",+ "airAcceleration",+ "groundDeceleration",+ "airDeceleration",+ "gravity",+ "fallGravityScale",+ "maxFallSpeed",+ "jumpSpeed",+ "jumpCut",+ "coyoteTime",+ "jumpBuffer",+ "airJumps",+ "dropTime",+ "moveInput"+ ]+ },{"name": "PointJoint3D","source": "ts",diff --git a/examples/platformer/assets/scenes/main.esscene b/examples/platformer/assets/scenes/main.essceneindex 03457c881..af52e4df3 100644--- a/examples/platformer/assets/scenes/main.esscene+++ b/examples/platformer/assets/scenes/main.esscene@@ -443,10 +443,6 @@"layer": 1}},- {- "type": "Player",- "data": {}- },{"type": "RigidBody2D","data": {@@ -469,6 +465,13 @@"data": {"maskBits": 65533}+ },+ {+ "type": "PlatformerController2D",+ "data": {+ "moveSpeed": 320,+ "jumpSpeed": 640+ }}],"visible": truediff --git a/examples/platformer/src/components.ts b/examples/platformer/src/components.tsindex 8724fd70b..b2e6d0be5 100644--- a/examples/platformer/src/components.ts+++ b/examples/platformer/src/components.ts@@ -1,10 +1,5 @@import { defineComponent } from 'esengine';-export const Player = defineComponent('Player', {- speed: 320,- jumpForce: 640,-});-export const Coin = defineComponent('Coin', {baseY: 0,bobTimer: 0,diff --git a/examples/platformer/src/main.ts b/examples/platformer/src/main.tsindex 6ddca396f..de15aec96 100644--- a/examples/platformer/src/main.ts+++ b/examples/platformer/src/main.ts@@ -1,11 +1,9 @@import { addSystemToSchedule, Schedule } from 'esengine';import './components';-import { playerSystem } from './systems/player';import { coinBobSystem, coinPickupSystem } from './systems/coin';import { scoreSystem } from './systems/score';-addSystemToSchedule(Schedule.FixedPreUpdate, playerSystem);addSystemToSchedule(Schedule.Update, coinPickupSystem);addSystemToSchedule(Schedule.Update, coinBobSystem);addSystemToSchedule(Schedule.Update, scoreSystem);diff --git a/examples/platformer/src/systems/player.ts b/examples/platformer/src/systems/player.tsdeleted file mode 100644index 80919568a..000000000--- a/examples/platformer/src/systems/player.ts+++ /dev/null@@ -1,27 +0,0 @@-import {- defineSystem, Query, Mut, Res, Time, Input,- CharacterController2D,-} from 'esengine';-import { Player } from '../components';--const GRAVITY = -1600;--export const playerSystem = defineSystem(- [Query(Mut(CharacterController2D), Player), Res(Time), Res(Input)],- (players, time, input) => {- for (const [_entity, cc, player] of players) {- let moveX = 0;- if (input.isKeyDown('ArrowLeft') || input.isKeyDown('KeyA')) moveX -= 1;- if (input.isKeyDown('ArrowRight') || input.isKeyDown('KeyD')) moveX += 1;- cc.velocity.x = moveX * player.speed;-- cc.velocity.y += GRAVITY * time.fixedDelta;-- const jump = input.isKeyPressed('Space')- || input.isKeyPressed('ArrowUp')- || input.isKeyPressed('KeyW');- if (cc.isOnFloor && jump) cc.velocity.y = player.jumpForce;- }- },- { name: 'PlayerSystem' }-);diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.tsindex fe2ed0a26..2eaeaa678 100644--- a/pipeline/src/project/targetSupport.ts+++ b/pipeline/src/project/targetSupport.ts@@ -57,7 +57,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>postprocess: ['PostProcessVolume'],physics: ['RigidBody2D', 'BoxCollider2D', 'CircleCollider2D', 'CapsuleCollider2D', 'SegmentCollider2D',- 'PolygonCollider2D', 'ChainCollider2D', 'OneWayPlatform2D', 'CharacterController2D',+ 'PolygonCollider2D', 'ChainCollider2D', 'OneWayPlatform2D', 'CharacterController2D', 'PlatformerController2D','HingeJoint2D', 'DistanceJoint2D', 'SliderJoint2D', 'FixedJoint2D', 'WheelJoint2D', 'MotorJoint2D',],physics3d: [diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex abaf42c1c..6b09f3eba 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 2067 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 2070 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2537,17 +2537,27 @@ ComponentDef<CharacterController2DData>## CharacterController2DData — interface @beta```+blockSteepSlopes: boolean+constantSlopeSpeed: boolean+dropThrough: boolean+dynamicBodies: number+floorEntity: numberfloorMaxAngle: numberfloorNormal: Vec2+floorVelocity: Vec2+followPlatform: booleanisOnCeiling: booleanisOnFloor: booleanisOnWall: booleanmaskBits: numbermaxSlides: number+pushForce: numberrealVelocity: Vec2skinWidth: numberslideOnCeiling: booleansnapLength: number+stepHeight: number+stopOnSlope: booleanup: Vec2velocity: Vec2```@@ -2574,6 +2584,11 @@ stepHeight: numbervelocity: Vec3```+## CharacterDynamicBodies — const @experimental+```+{ readonly Block: 0; readonly Push: 1; readonly Ignore: 2; }+```+## Children — const @public```BuiltinComponentDef<ChildrenData>@@ -7165,7 +7180,7 @@ _physics_hasJoint: (entityId: number) => number_physics_hasMouseJoint: () => number_physics_init: (gx: number, gy: number, timestep: number, substeps: number, contactHertz: number, contactDampingRatio: number, contactSpeed: number) => void_physics_isAwake: (entityId: number) => 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, skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number) => 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, skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number, carryX: number, carryY: number, flags: number, stepHeight: number) => number_physics_overlapAABB: (minX: number, minY: number, maxX: number, maxY: number, maskBits: number) => number_physics_overlapCircle: (centerX: number, centerY: number, radius: number, maskBits: number) => number_physics_raycast: (originX: number, originY: number, dirX: number, dirY: number, maxDistance: number, maskBits: number) => number@@ -7645,6 +7660,36 @@ dispose: () => voidname: string```+## PlatformerController2D — const @experimental+```+ComponentDef<PlatformerController2DData>+```++## PlatformerController2DData — interface @experimental+```+airAcceleration: number+airDeceleration: number+airJumps: number+coyoteTime: number+dropPressed: boolean+dropTime: number+enabled: boolean+fallGravityScale: number+gravity: number+groundAcceleration: number+groundDeceleration: number+jumpBuffer: number+jumpCut: number+jumpHeld: boolean+jumpPressed: boolean+jumpSpeed: number+keepPlatformVelocity: boolean+maxFallSpeed: number+moveInput: number+moveSpeed: number+readKeyboard: boolean+```+## PlayConfig — interface @experimental```bus: string | undefineddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex a1739fe03..d1f88472d 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 169 beta · 2086 experimental · 3 deprecated+Symbols: 115 public · 169 beta · 2089 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2537,17 +2537,27 @@ ComponentDef<CharacterController2DData>## CharacterController2DData — interface @beta```+blockSteepSlopes: boolean+constantSlopeSpeed: boolean+dropThrough: boolean+dynamicBodies: number+floorEntity: numberfloorMaxAngle: numberfloorNormal: Vec2+floorVelocity: Vec2+followPlatform: booleanisOnCeiling: booleanisOnFloor: booleanisOnWall: booleanmaskBits: numbermaxSlides: number+pushForce: numberrealVelocity: Vec2skinWidth: numberslideOnCeiling: booleansnapLength: number+stepHeight: number+stopOnSlope: booleanup: Vec2velocity: Vec2```@@ -2574,6 +2584,11 @@ stepHeight: numbervelocity: Vec3```+## CharacterDynamicBodies — const @experimental+```+{ readonly Block: 0; readonly Push: 1; readonly Ignore: 2; }+```+## Children — const @public```BuiltinComponentDef<ChildrenData>@@ -7371,7 +7386,7 @@ _physics_hasJoint: (entityId: number) => number_physics_hasMouseJoint: () => number_physics_init: (gx: number, gy: number, timestep: number, substeps: number, contactHertz: number, contactDampingRatio: number, contactSpeed: number) => void_physics_isAwake: (entityId: number) => 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, skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number) => 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, skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number, carryX: number, carryY: number, flags: number, stepHeight: number) => number_physics_overlapAABB: (minX: number, minY: number, maxX: number, maxY: number, maskBits: number) => number_physics_overlapCircle: (centerX: number, centerY: number, radius: number, maskBits: number) => number_physics_raycast: (originX: number, originY: number, dirX: number, dirY: number, maxDistance: number, maskBits: number) => number@@ -7851,6 +7866,36 @@ dispose: () => voidname: string```+## PlatformerController2D — const @experimental+```+ComponentDef<PlatformerController2DData>+```++## PlatformerController2DData — interface @experimental+```+airAcceleration: number+airDeceleration: number+airJumps: number+coyoteTime: number+dropPressed: boolean+dropTime: number+enabled: boolean+fallGravityScale: number+gravity: number+groundAcceleration: number+groundDeceleration: number+jumpBuffer: number+jumpCut: number+jumpHeld: boolean+jumpPressed: boolean+jumpSpeed: number+keepPlatformVelocity: boolean+maxFallSpeed: number+moveInput: number+moveSpeed: number+readKeyboard: boolean+```+## PlayConfig — interface @experimental```bus: string | undefineddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex b40b81c89..cffc0d7d9 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 166 beta · 2066 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2069 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2532,17 +2532,27 @@ ComponentDef<CharacterController2DData>## CharacterController2DData — interface @beta```+blockSteepSlopes: boolean+constantSlopeSpeed: boolean+dropThrough: boolean+dynamicBodies: number+floorEntity: numberfloorMaxAngle: numberfloorNormal: Vec2+floorVelocity: Vec2+followPlatform: booleanisOnCeiling: booleanisOnFloor: booleanisOnWall: booleanmaskBits: numbermaxSlides: number+pushForce: numberrealVelocity: Vec2skinWidth: numberslideOnCeiling: booleansnapLength: number+stepHeight: number+stopOnSlope: booleanup: Vec2velocity: Vec2```@@ -2569,6 +2579,11 @@ stepHeight: numbervelocity: Vec3```+## CharacterDynamicBodies — const @experimental+```+{ readonly Block: 0; readonly Push: 1; readonly Ignore: 2; }+```+## Children — const @public```BuiltinComponentDef<ChildrenData>@@ -7160,7 +7175,7 @@ _physics_hasJoint: (entityId: number) => number_physics_hasMouseJoint: () => number_physics_init: (gx: number, gy: number, timestep: number, substeps: number, contactHertz: number, contactDampingRatio: number, contactSpeed: number) => void_physics_isAwake: (entityId: number) => 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, skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number) => 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, skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number, carryX: number, carryY: number, flags: number, stepHeight: number) => number_physics_overlapAABB: (minX: number, minY: number, maxX: number, maxY: number, maskBits: number) => number_physics_overlapCircle: (centerX: number, centerY: number, radius: number, maskBits: number) => number_physics_raycast: (originX: number, originY: number, dirX: number, dirY: number, maxDistance: number, maskBits: number) => number@@ -7640,6 +7655,36 @@ dispose: () => voidname: string```+## PlatformerController2D — const @experimental+```+ComponentDef<PlatformerController2DData>+```++## PlatformerController2DData — interface @experimental+```+airAcceleration: number+airDeceleration: number+airJumps: number+coyoteTime: number+dropPressed: boolean+dropTime: number+enabled: boolean+fallGravityScale: number+gravity: number+groundAcceleration: number+groundDeceleration: number+jumpBuffer: number+jumpCut: number+jumpHeld: boolean+jumpPressed: boolean+jumpSpeed: number+keepPlatformVelocity: boolean+maxFallSpeed: number+moveInput: number+moveSpeed: number+readKeyboard: boolean+```+## PlayConfig — interface @experimental```bus: string | undefineddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 8ada46239..98569e3b4 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 2088 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 2091 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2532,17 +2532,27 @@ ComponentDef<CharacterController2DData>## CharacterController2DData — interface @beta```+blockSteepSlopes: boolean+constantSlopeSpeed: boolean+dropThrough: boolean+dynamicBodies: number+floorEntity: numberfloorMaxAngle: numberfloorNormal: Vec2+floorVelocity: Vec2+followPlatform: booleanisOnCeiling: booleanisOnFloor: booleanisOnWall: booleanmaskBits: numbermaxSlides: number+pushForce: numberrealVelocity: Vec2skinWidth: numberslideOnCeiling: booleansnapLength: number+stepHeight: number+stopOnSlope: booleanup: Vec2velocity: Vec2```@@ -2569,6 +2579,11 @@ stepHeight: numbervelocity: Vec3```+## CharacterDynamicBodies — const @experimental+```+{ readonly Block: 0; readonly Push: 1; readonly Ignore: 2; }+```+## Children — const @public```BuiltinComponentDef<ChildrenData>@@ -7456,7 +7471,7 @@ _physics_hasJoint: (entityId: number) => number_physics_hasMouseJoint: () => number_physics_init: (gx: number, gy: number, timestep: number, substeps: number, contactHertz: number, contactDampingRatio: number, contactSpeed: number) => void_physics_isAwake: (entityId: number) => 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, skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number) => 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, skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number, carryX: number, carryY: number, flags: number, stepHeight: number) => number_physics_overlapAABB: (minX: number, minY: number, maxX: number, maxY: number, maskBits: number) => number_physics_overlapCircle: (centerX: number, centerY: number, radius: number, maskBits: number) => number_physics_raycast: (originX: number, originY: number, dirX: number, dirY: number, maxDistance: number, maskBits: number) => number@@ -7936,6 +7951,36 @@ dispose: () => voidname: string```+## PlatformerController2D — const @experimental+```+ComponentDef<PlatformerController2DData>+```++## PlatformerController2DData — interface @experimental+```+airAcceleration: number+airDeceleration: number+airJumps: number+coyoteTime: number+dropPressed: boolean+dropTime: number+enabled: boolean+fallGravityScale: number+gravity: number+groundAcceleration: number+groundDeceleration: number+jumpBuffer: number+jumpCut: number+jumpHeld: boolean+jumpPressed: boolean+jumpSpeed: number+keepPlatformVelocity: boolean+maxFallSpeed: number+moveInput: number+moveSpeed: number+readKeyboard: boolean+```+## PlayConfig — interface @experimental```bus: string | undefineddiff --git a/sdk/etc/physics.api.md b/sdk/etc/physics.api.mdindex 5358df4f1..f76865a5e 100644--- a/sdk/etc/physics.api.md+++ b/sdk/etc/physics.api.md@@ -1,7 +1,7 @@# API surface — esengine/physics<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 5 beta · 69 experimental · 0 deprecated+Symbols: 0 public · 5 beta · 72 experimental · 0 deprecated## BodyType — enum @experimental```@@ -76,21 +76,36 @@ ComponentDef<CharacterController2DData>## CharacterController2DData — interface @beta```+blockSteepSlopes: boolean+constantSlopeSpeed: boolean+dropThrough: boolean+dynamicBodies: number+floorEntity: numberfloorMaxAngle: numberfloorNormal: Vec2+floorVelocity: Vec2+followPlatform: booleanisOnCeiling: booleanisOnFloor: booleanisOnWall: booleanmaskBits: numbermaxSlides: number+pushForce: numberrealVelocity: Vec2skinWidth: numberslideOnCeiling: booleansnapLength: number+stepHeight: number+stopOnSlope: booleanup: Vec2velocity: Vec2```+## CharacterDynamicBodies — const @experimental+```+{ readonly Block: 0; readonly Push: 1; readonly Ignore: 2; }+```+## CircleCollider2D — const @experimental```BuiltinComponentDef<CircleCollider2DData>@@ -349,7 +364,7 @@ getRevoluteMotorTorque: (entity: Entity) => numbergetWheelJointMotorTorque: (entity: Entity) => numberhasMouseJoint: () => booleanisAwake: (entity: Entity) => boolean-moveCharacter: (pos: Vec2, c1: Vec2, c2: Vec2, radius: number, velocity: Vec2, dt: number, up: Vec2, floorCos: number, maskBits: number, self: Entity, skinWidth?: number, maxSlides?: number, snapLength?: number, slideOnCeiling?: boolean, ppu?: number) => MoverResult | null+moveCharacter: (pos: Vec2, c1: Vec2, c2: Vec2, radius: number, velocity: Vec2, dt: number, up: Vec2, floorCos: number, maskBits: number, self: Entity, skinWidth?: number, maxSlides?: number, snapLength?: number, slideOnCeiling?: boolean, ppu?: number, options?: MoverOptions) => MoverResult | nulloverlapAABB: (min: Vec2, max: Vec2, maskBits?: number, ppu?: number) => Entity[]overlapCircle: (center: Vec2, radius: number, maskBits?: number, ppu?: number) => Entity[]raycast: (origin: Vec2, direction: Vec2, maxDistance: number, maskBits?: number, ppu?: number) => RaycastHit[]@@ -537,7 +552,7 @@ _physics_hasJoint: (entityId: number) => number_physics_hasMouseJoint: () => number_physics_init: (gx: number, gy: number, timestep: number, substeps: number, contactHertz: number, contactDampingRatio: number, contactSpeed: number) => void_physics_isAwake: (entityId: number) => 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, skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number) => 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, skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number, carryX: number, carryY: number, flags: number, stepHeight: number) => number_physics_overlapAABB: (minX: number, minY: number, maxX: number, maxY: number, maskBits: number) => number_physics_overlapCircle: (centerX: number, centerY: number, radius: number, maskBits: number) => number_physics_raycast: (originX: number, originY: number, dirX: number, dirY: number, maxDistance: number, maskBits: number) => number@@ -578,6 +593,36 @@ _physics_step: (dt: number) => void_physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, bullet: number) => void```+## PlatformerController2D — const @experimental+```+ComponentDef<PlatformerController2DData>+```++## PlatformerController2DData — interface @experimental+```+airAcceleration: number+airDeceleration: number+airJumps: number+coyoteTime: number+dropPressed: boolean+dropTime: number+enabled: boolean+fallGravityScale: number+gravity: number+groundAcceleration: number+groundDeceleration: number+jumpBuffer: number+jumpCut: number+jumpHeld: boolean+jumpPressed: boolean+jumpSpeed: number+keepPlatformVelocity: boolean+maxFallSpeed: number+moveInput: number+moveSpeed: number+readKeyboard: boolean+```+## PolygonCollider2D — const @experimental```ComponentDef<PolygonCollider2DData>diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex f055aab67..c003963c2 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 2079 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 2082 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2532,17 +2532,27 @@ ComponentDef<CharacterController2DData>## CharacterController2DData — interface @beta```+blockSteepSlopes: boolean+constantSlopeSpeed: boolean+dropThrough: boolean+dynamicBodies: number+floorEntity: numberfloorMaxAngle: numberfloorNormal: Vec2+floorVelocity: Vec2+followPlatform: booleanisOnCeiling: booleanisOnFloor: booleanisOnWall: booleanmaskBits: numbermaxSlides: number+pushForce: numberrealVelocity: Vec2skinWidth: numberslideOnCeiling: booleansnapLength: number+stepHeight: number+stopOnSlope: booleanup: Vec2velocity: Vec2```@@ -2569,6 +2579,11 @@ stepHeight: numbervelocity: Vec3```+## CharacterDynamicBodies — const @experimental+```+{ readonly Block: 0; readonly Push: 1; readonly Ignore: 2; }+```+## Children — const @public```BuiltinComponentDef<ChildrenData>@@ -7167,7 +7182,7 @@ _physics_hasJoint: (entityId: number) => number_physics_hasMouseJoint: () => number_physics_init: (gx: number, gy: number, timestep: number, substeps: number, contactHertz: number, contactDampingRatio: number, contactSpeed: number) => void_physics_isAwake: (entityId: number) => 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, skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number) => 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, skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number, carryX: number, carryY: number, flags: number, stepHeight: number) => number_physics_overlapAABB: (minX: number, minY: number, maxX: number, maxY: number, maskBits: number) => number_physics_overlapCircle: (centerX: number, centerY: number, radius: number, maskBits: number) => number_physics_raycast: (originX: number, originY: number, dirX: number, dirY: number, maxDistance: number, maskBits: number) => number@@ -7647,6 +7662,36 @@ dispose: () => voidname: string```+## PlatformerController2D — const @experimental+```+ComponentDef<PlatformerController2DData>+```++## PlatformerController2DData — interface @experimental+```+airAcceleration: number+airDeceleration: number+airJumps: number+coyoteTime: number+dropPressed: boolean+dropTime: number+enabled: boolean+fallGravityScale: number+gravity: number+groundAcceleration: number+groundDeceleration: number+jumpBuffer: number+jumpCut: number+jumpHeld: boolean+jumpPressed: boolean+jumpSpeed: number+keepPlatformVelocity: boolean+maxFallSpeed: number+moveInput: number+moveSpeed: number+readKeyboard: boolean+```+## PlayConfig — interface @experimental```bus: string | undefineddiff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.tsindex 8954b618c..d197fc768 100644--- a/sdk/src/core-runtime.ts+++ b/sdk/src/core-runtime.ts@@ -204,7 +204,9 @@ export {export {CharacterController2D,type CharacterController2DData,+ CharacterDynamicBodies,} from './physics/CharacterController2D';+export { PlatformerController2D, type PlatformerController2DData } from './physics/PlatformerController2D';export {readCollider2DShapes,diff --git a/sdk/src/physics/CharacterController2D.ts b/sdk/src/physics/CharacterController2D.tsindex c6bda91cf..76ebdc53c 100644--- a/sdk/src/physics/CharacterController2D.ts+++ b/sdk/src/physics/CharacterController2D.ts@@ -20,7 +20,7 @@* Units: `velocity`/positions are world pixels (matching `Transform`); collider* dimensions are meters and are scaled to pixels via `Physics2DAPI.getPixelsPerUnit()`.*/-import type { Vec2 } from '../types';+import type { Entity, Vec2 } from '../types';import { defineComponent } from '../ecs/component';// =============================================================================@@ -46,6 +46,22 @@ export interface CharacterController2DData {slideOnCeiling: boolean;/** Collision layers that block the character. */maskBits: number;+ /** The highest ledge it walks up without jumping (pixels); 0 = only what its rounded foot rides over. */+ stepHeight: number;+ /** Stand still on a walkable slope, and walk it without being slowed or sped by gravity. */+ stopOnSlope: boolean;+ /** Keep the speed asked for along a slope, rather than the speed across the ground. */+ constantSlopeSpeed: boolean;+ /** A slope past `floorMaxAngle` is a wall to walk into, and it slides down it. Off, it walks straight up. */+ blockSteepSlopes: boolean;+ /** Move with what it stands on. */+ followPlatform: boolean;+ /** How it meets dynamic bodies: a {@link CharacterDynamicBodies}. */+ dynamicBodies: number;+ /** Push: the most force it pushes with, in Newtons, as physics measures it. */+ pushForce: number;+ /** Pass through one-way platforms while this is on. */+ dropThrough: boolean;/** Output: touched a surface classified as floor this move. */isOnFloor: boolean;@@ -57,8 +73,22 @@ export interface CharacterController2DData {floorNormal: Vec2;/** Output: actual displacement / dt after collisions (pixels/second). */realVelocity: Vec2;+ /** Output: the entity it stands on; 0 when airborne. */+ floorEntity: Entity;+ /** Output: the velocity of what it stands on (pixels/second). */+ floorVelocity: Vec2;}+/** How a character meets dynamic bodies. @experimental */+export const CharacterDynamicBodies = {+ /** They stop it, and stay where they are. */+ Block: 0,+ /** They stop it, and it pushes them with up to `pushForce`. */+ Push: 1,+ /** It passes through. */+ Ignore: 2,+} as const;+/*** A kinematic mover for a player or an NPC: it sweeps rather than being pushed,* so it never tunnels and never inherits a rigid body's momentum.@@ -74,13 +104,38 @@ export const CharacterController2D = defineComponent<CharacterController2DData>(snapLength: 0,slideOnCeiling: true,maskBits: 0xFFFF,+ stepHeight: 0,+ stopOnSlope: true,+ constantSlopeSpeed: false,+ blockSteepSlopes: true,+ followPlatform: true,+ dynamicBodies: CharacterDynamicBodies.Block,+ pushForce: 40,+ dropThrough: false,isOnFloor: false,isOnWall: false,isOnCeiling: false,floorNormal: { x: 0, y: 0 },realVelocity: { x: 0, y: 0 },+ floorEntity: 0 as Entity,+ floorVelocity: { x: 0, y: 0 },}, {+ entityFields: ['floorEntity'],fields: {+ stepHeight: { min: 0, step: 1, unit: 'px', tooltip: 'The highest ledge it walks up without jumping; 0 = only what its rounded foot rides over' },+ stopOnSlope: { tooltip: 'Stand still on a walkable slope, and walk it without gravity slowing or speeding it' },+ constantSlopeSpeed: { advanced: true, tooltip: 'Keep the speed asked for along a slope, rather than the speed across the ground' },+ blockSteepSlopes: { tooltip: 'A slope past the walkable angle is a wall to walk into. Off, it walks straight up' },+ followPlatform: { tooltip: 'Move with what it stands on' },+ dynamicBodies: { enum: [+ { label: 'Block', value: CharacterDynamicBodies.Block },+ { label: 'Push', value: CharacterDynamicBodies.Push },+ { label: 'Ignore', value: CharacterDynamicBodies.Ignore },+ ], tooltip: 'How it meets dynamic bodies' },+ pushForce: { min: 0, unit: 'N', shownWhen: { field: 'dynamicBodies', values: [CharacterDynamicBodies.Push] }, tooltip: 'The most force it pushes with' },+ dropThrough: { advanced: true, tooltip: 'Pass through one-way platforms while on' },+ floorEntity: { advanced: true },+ floorVelocity: { advanced: true },floorMaxAngle: { min: 0, max: 1.5708, step: 0.01, unit: 'rad', tooltip: 'Max walkable slope from up (radians)' },maxSlides: { min: 1, max: 8, step: 1, advanced: true },skinWidth: { min: 0, step: 0.25, unit: 'px', advanced: true },diff --git a/sdk/src/physics/CharacterController2DSystem.ts b/sdk/src/physics/CharacterController2DSystem.tsindex 68775c4bd..c1dd2074a 100644--- a/sdk/src/physics/CharacterController2DSystem.ts+++ b/sdk/src/physics/CharacterController2DSystem.ts@@ -11,7 +11,7 @@*/import type { App } from '../app/app';import type { Entity, Vec2 } from '../types';-import { Transform, type TransformData } from '../ecs/component';+import { Parent, Transform, type ParentData, type TransformData } from '../ecs/component';import { Schedule, defineSystem, GetWorld } from '../ecs/system';import { Query, Mut } from '../ecs/query';import { Res, Time, type TimeData } from '../ecs/resource';@@ -22,11 +22,13 @@ import {BoxCollider2D, CircleCollider2D, CapsuleCollider2D, activeCollider,type BoxCollider2DData, type CircleCollider2DData, type CapsuleCollider2DData,} from './PhysicsComponents';+import { Input, type InputState } from '../input/input';+import { PlatformerController2D, platformerState, stepPlatformer, type PlatformerController2DData, type PlatformerState } from './PlatformerController2D';import { log } from '../util/logger';import type { MoverResult } from './PhysicsTypes';import type { World } from '../ecs/world';import {- CharacterController2D, moveAndSlide,+ CharacterController2D, CharacterDynamicBodies, moveAndSlide,type CharacterController2DData, type SlideHit,} from './CharacterController2D';@@ -34,6 +36,80 @@ import {// System// =============================================================================+const platformerStates = new WeakMap<World, Map<Entity, PlatformerState>>();++function platformerStateOf(world: World, entity: Entity, airJumps: number): PlatformerState {+ let states = platformerStates.get(world);+ if (!states) { states = new Map(); platformerStates.set(world, states); }+ let state = states.get(entity);+ if (!state) { state = platformerState(airJumps); states.set(entity, state); }+ return state;+}++/** Input per rendered frame, so a tap between two fixed steps is not lost; the character's wishes per fixed step, ahead of its move. */+function registerPlatformerController2DSystems(app: App): void {+ app.world.onDespawn((entity: Entity) => { platformerStates.get(app.world)?.delete(entity); });+ app.addSystemToSchedule(+ Schedule.Update,+ defineSystem(+ [Query(Mut(PlatformerController2D)), Res(Input)],+ (query: Iterable<[Entity, PlatformerController2DData]>, input: InputState) => {+ for (const [, p] of query) {+ if (!p.enabled || !p.readKeyboard) continue;+ const right = input.isKeyDown('KeyD') || input.isKeyDown('ArrowRight');+ const left = input.isKeyDown('KeyA') || input.isKeyDown('ArrowLeft');+ p.moveInput = (right ? 1 : 0) - (left ? 1 : 0);+ p.jumpHeld = input.isKeyDown('Space') || input.isKeyDown('KeyW') || input.isKeyDown('ArrowUp');+ const pressed = input.isKeyPressed('Space') || input.isKeyPressed('KeyW') || input.isKeyPressed('ArrowUp');+ const down = input.isKeyDown('KeyS') || input.isKeyDown('ArrowDown');+ if (pressed && down) p.dropPressed = true;+ else if (pressed) p.jumpPressed = true;+ }+ },+ { name: 'PlatformerController2DInputSystem' },+ ),+ { runIf: playModeOnly },+ );+ app.addSystemToSchedule(+ Schedule.FixedUpdate,+ defineSystem(+ [Query(Mut(PlatformerController2D), Mut(CharacterController2D)), Res(Time), GetWorld()],+ (query: Iterable<[Entity, PlatformerController2DData, CharacterController2DData]>, time: TimeData, world: World) => {+ const dt = time.fixedDelta;+ if (dt <= 0) return;+ for (const [entity, p, cc] of query) {+ if (!p.enabled) continue;+ const rx = cc.up.y, ry = -cc.up.x;+ const step = stepPlatformer(+ p, platformerStateOf(world, entity, p.airJumps),+ {+ onFloor: cc.isOnFloor, onCeiling: cc.isOnCeiling,+ floorVelocityX: cc.floorVelocity.x * rx + cc.floorVelocity.y * ry,+ floorVelocityY: cc.floorVelocity.x * cc.up.x + cc.floorVelocity.y * cc.up.y,+ },+ cc.velocity.x * rx + cc.velocity.y * ry, cc.velocity.x * cc.up.x + cc.velocity.y * cc.up.y,+ p.jumpPressed, p.dropPressed, dt,+ );+ p.jumpPressed = false;+ p.dropPressed = false;+ cc.velocity.x = rx * step.velocityX + cc.up.x * step.velocityY;+ cc.velocity.y = ry * step.velocityX + cc.up.y * step.velocityY;+ cc.dropThrough = step.dropThrough;+ // Off the floor this move, or it would still read as standing where it just jumped from.+ if (step.jumped) cc.isOnFloor = false;+ }+ },+ {+ name: 'PlatformerController2DSystem',+ runBefore: ['CharacterController2DSystem'],+ // The World is only the key its per-character state is kept under.+ touches: { reads: [], writes: [] },+ },+ ),+ { runIf: playModeOnly },+ );+}+/** The character's cast shape, in pixels, resolved from its collider. */type CastShape =| { kind: 'box'; hx: number; hy: number; ox: number; oy: number }@@ -83,6 +159,70 @@ function isFiniteMove(r: MoverResult): boolean {&& Number.isFinite(r.velX) && Number.isFinite(r.velY);}+const NO_CARRY: Vec2 = { x: 0, y: 0 };++/**+ * How fast what it stands on carries it, pixels per second. A body's velocity is what it moved by in the step before this one, whoever+ * moved it, which is exactly how far it has gone from under the character since the last move.+ */+function platformCarry(physics: Physics2DAPI, world: World, cc: CharacterController2DData, ppu: number): Vec2 {+ if (!cc.followPlatform || !cc.isOnFloor || !cc.floorEntity || !world.valid(cc.floorEntity)) return NO_CARRY;+ const velocity = physics.getLinearVelocity(cc.floorEntity);+ const spin = physics.getAngularVelocity(cc.floorEntity);+ if (velocity.x === 0 && velocity.y === 0 && spin === 0) return NO_CARRY;+ return { x: velocity.x * ppu, y: velocity.y * ppu };+}++/** Along a walkable slope, not into it: what keeps a character from sliding down one and from launching off its top. */+function slopeVelocity(cc: CharacterController2DData): Vec2 {+ if (!cc.stopOnSlope || !cc.isOnFloor) return cc.velocity;+ const ups = cc.velocity.x * cc.up.x + cc.velocity.y * cc.up.y;+ if (ups > 0) return cc.velocity;+ const nUp = cc.floorNormal.x * cc.up.x + cc.floorNormal.y * cc.up.y;+ if (nUp >= 0.9999 || nUp <= 0) return cc.velocity;+ const rx = cc.up.y, ry = -cc.up.x;+ const across = cc.velocity.x * rx + cc.velocity.y * ry;+ // The right along the slope: the ground's right with the part into the floor taken out.+ const into = rx * cc.floorNormal.x + ry * cc.floorNormal.y;+ let tx = rx - into * cc.floorNormal.x, ty = ry - into * cc.floorNormal.y;+ const scale = cc.constantSlopeSpeed ? 1 / (Math.hypot(tx, ty) || 1) : 1 / ((tx * rx + ty * ry) || 1);+ tx *= scale; ty *= scale;+ return { x: tx * across, y: ty * across };+}++/** What a slope walk leaves it with: the speed it asked for across the ground, unless something stopped it. */+function velocityAfterSlope(cc: CharacterController2DData, r: MoverResult): Vec2 {+ const rx = cc.up.y, ry = -cc.up.x;+ const asked = cc.velocity.x * rx + cc.velocity.y * ry;+ const across = r.isOnWall ? r.velX * rx + r.velY * ry : asked;+ return { x: rx * across, y: ry * across };+}++/** Lean into what it pressed against, up to its force, and only as far as the body is not already getting away. */+function pushBodies(physics: Physics2DAPI, hits: NonNullable<MoverResult['hits']>, cc: CharacterController2DData, ppu: number): void {+ for (const hit of hits) {+ const into = -(cc.velocity.x * hit.normalX + cc.velocity.y * hit.normalY);+ // A body underfoot holds the character up: pressing on it is standing, not pushing.+ if (hit.normalX * cc.up.x + hit.normalY * cc.up.y > 0.5) continue;+ const asked = Math.abs(cc.velocity.x) + Math.abs(cc.velocity.y);+ const speed = Math.max(into, asked * Math.abs(hit.normalX * cc.up.y - hit.normalY * cc.up.x));+ if (speed <= 0) continue;+ const velocity = physics.getLinearVelocity(hit.entity);+ const away = -(velocity.x * hit.normalX + velocity.y * hit.normalY) * ppu;+ if (away >= speed) continue;+ physics.applyForce(hit.entity, { x: -hit.normalX * cc.pushForce, y: -hit.normalY * cc.pushForce });+ }+}++/** A world displacement in the parent's own space, which is what a local position is measured in. */+function worldDeltaToLocal(world: World, entity: Entity, dx: number, dy: number): Vec2 {+ const parent = (world.get(entity, Parent) as ParentData).entity;+ if (!world.valid(parent) || !world.has(parent, Transform)) return { x: dx, y: dy };+ const up = world.get(parent, Transform) as TransformData;+ const angle = 2 * Math.atan2(up.worldRotation.z, up.worldRotation.w), c = Math.cos(angle), s = Math.sin(angle);+ return { x: (c * dx + s * dy) / (up.worldScale.x || 1), y: (-s * dx + c * dy) / (up.worldScale.y || 1) };+}+let warnedNonFiniteMove = false;function warnNonFiniteMove(entity: Entity, ppu: number, dt: number): void {@@ -101,6 +241,7 @@ function warnNonFiniteMove(entity: Entity, ppu: number, dt: number): void {*/export function registerCharacterController2DSystem(app: App): void {warnedNonFiniteMove = false;+ registerPlatformerController2DSystems(app);app.addSystemToSchedule(Schedule.FixedUpdate,defineSystem(@@ -123,20 +264,25 @@ export function registerCharacterController2DSystem(app: App): void {const shape = resolveCastShape(world, entity, ppu);if (!shape) continue;const mover = moverCapsuleFromShape(shape);+ const carry = platformCarry(physics, world, cc, ppu);+ const asked = slopeVelocity(cc);- // Transform is C++-backed: get() yields a converted copy, so the- // resolved pose must be written back with set() (mutating the copy- // alone would not persist).+ // The solver works in the world: a parent would otherwise put the capsule at its local position.+ // Transform is C++-backed, so get() is a copy and the resolved pose goes back through set().+ const parented = world.has(entity, Parent);+ if (parented) world.ensureTransformsComposed();const transform = world.get(entity, Transform) as TransformData;- const startX = transform.position.x;- const startY = transform.position.y;+ const from = parented ? transform.worldPosition : transform.position;const r = physics.moveCharacter(- transform.position, mover.c1, mover.c2, mover.radius,- cc.velocity, dt, cc.up, Math.cos(cc.floorMaxAngle),+ from, mover.c1, mover.c2, mover.radius,+ asked, dt, cc.up, Math.cos(cc.floorMaxAngle),cc.maskBits, entity,cc.skinWidth, cc.maxSlides, cc.snapLength, cc.slideOnCeiling,- ppu,+ ppu, {+ carry, dropThrough: cc.dropThrough, ignoreDynamic: cc.dynamicBodies === CharacterDynamicBodies.Ignore,+ blockSteepSlopes: cc.blockSteepSlopes, wasOnFloor: cc.isOnFloor, stepHeight: cc.stepHeight,+ },);if (!r) continue;// A non-finite move is not survivable: the next move starts from the@@ -147,14 +293,20 @@ export function registerCharacterController2DSystem(app: App): void {// 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 = startX + r.dx;- transform.position.y = startY + r.dy;- transform.worldPosition.x = transform.position.x;- transform.worldPosition.y = transform.position.y;+ const local = parented ? worldDeltaToLocal(world, entity, r.dx, r.dy) : { x: r.dx, y: r.dy };+ transform.position.x += local.x;+ transform.position.y += local.y;+ transform.worldPosition.x = from.x + r.dx;+ transform.worldPosition.y = from.y + r.dy;world.set(entity, Transform, transform);- cc.velocity.x = r.velX;- cc.velocity.y = r.velY;+ const kept = asked === cc.velocity ? null : velocityAfterSlope(cc, r);+ cc.velocity.x = kept ? kept.x : r.velX;+ cc.velocity.y = kept ? kept.y : r.velY;+ if (r.hits && cc.dynamicBodies === CharacterDynamicBodies.Push) pushBodies(physics, r.hits, cc, ppu);+ cc.floorEntity = (r.floorEntity ?? 0) as Entity;+ cc.floorVelocity.x = carry.x;+ cc.floorVelocity.y = carry.y;cc.isOnFloor = r.isOnFloor;cc.isOnWall = r.isOnWall;cc.isOnCeiling = r.isOnCeiling;@@ -171,7 +323,7 @@ export function registerCharacterController2DSystem(app: App): void {// a character has) and the pose it resolves; the solver's contacts// are physics-side state, not components.touches: {- reads: [BoxCollider2D._name, CircleCollider2D._name, CapsuleCollider2D._name],+ reads: [BoxCollider2D._name, CircleCollider2D._name, CapsuleCollider2D._name, Parent._name],writes: [Transform._name],},},diff --git a/sdk/src/physics/Physics2D.ts b/sdk/src/physics/Physics2D.tsindex 62800cb67..b95ba3cae 100644--- a/sdk/src/physics/Physics2D.ts+++ b/sdk/src/physics/Physics2D.ts@@ -22,6 +22,7 @@ import {type ShapeCastHit,type MassData,type MoverResult,+ type MoverOptions,} from './PhysicsTypes';// =============================================================================@@ -278,20 +279,29 @@ export class Physics2DAPI {velocity: Vec2, dt: number, up: Vec2, floorCos: number,maskBits: number, self: Entity,skinWidth = 0, maxSlides = 5, snapLength = 0, slideOnCeiling = true,- ppu = this.ppu_,+ ppu = this.ppu_, options: MoverOptions = {},): MoverResult | null {const invPpu = 1 / ppu;+ const flags = (options.dropThrough ? 1 : 0) | (options.ignoreDynamic ? 2 : 0)+ | (options.blockSteepSlopes ? 4 : 0) | (options.wasOnFloor ? 8 : 0);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,skinWidth * invPpu, maxSlides, snapLength * invPpu, slideOnCeiling ? 1 : 0,+ (options.carry?.x ?? 0) * invPpu, (options.carry?.y ?? 0) * invPpu, flags, (options.stepHeight ?? 0) * invPpu,);if (!ok) return null;const base = this.module_._physics_getMoveCharacterBuffer() >> 2;- const h = this.module_.HEAPF32;+ const h = this.module_.HEAPF32, bits = this.module_.HEAPU32;+ const floor = bits[base + 9]!, hitCount = h[base + 10]!;+ let hits: MoverResult['hits'];+ for (let i = 0; i < hitCount; i++) {+ (hits ??= []).push({ entity: bits[base + 11 + i * 3]! as Entity, normalX: h[base + 12 + i * 3]!, normalY: h[base + 13 + i * 3]! });+ }return {+ floorEntity: floor === 0xFFFFFFFF ? null : floor as Entity, hits,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,diff --git a/sdk/src/physics/PhysicsModuleLoader.ts b/sdk/src/physics/PhysicsModuleLoader.tsindex 6d2d70dce..e5b652420 100644--- a/sdk/src/physics/PhysicsModuleLoader.ts+++ b/sdk/src/physics/PhysicsModuleLoader.ts@@ -180,7 +180,8 @@ export interface PhysicsWasmModule {_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,- skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number): number;+ skinWidth: number, maxSlides: number, snapLength: number, slideOnCeiling: number,+ carryX: number, carryY: number, flags: number, stepHeight: number): number;_physics_getMoveCharacterBuffer(): number;_physics_overlapAABB(minX: number, minY: number, maxX: number, maxY: number, maskBits: number): number;diff --git a/sdk/src/physics/PhysicsTypes.ts b/sdk/src/physics/PhysicsTypes.tsindex e09138a45..650ade82e 100644--- a/sdk/src/physics/PhysicsTypes.ts+++ b/sdk/src/physics/PhysicsTypes.ts@@ -118,6 +118,26 @@ export interface MoverResult {isOnCeiling: boolean;floorNormalX: number;floorNormalY: number;+ /** The entity it stands on, or null when airborne. */+ floorEntity: Entity | null;+ /** The dynamic bodies it pressed against this move, with the normals facing it. Absent when none. */+ hits?: { entity: Entity; normalX: number; normalY: number }[];+}++/** What else a {@link MoverResult} move is asked to do. */+export interface MoverOptions {+ /** Moved with what it stands on, world pixels per second: no part of its own velocity, so what it reports back excludes it. */+ carry?: Vec2;+ /** Pass through every one-way surface: a drop. */+ dropThrough?: boolean;+ /** Pass through dynamic bodies. */+ ignoreDynamic?: boolean;+ /** Treat a slope too steep to stand on as a wall, not something to walk up. */+ blockSteepSlopes?: boolean;+ /** It stood on a floor before this move: only then can it step over a ledge. */+ wasOnFloor?: boolean;+ /** The highest ledge it steps over, world pixels. */+ stepHeight?: number;}export interface MassData {diff --git a/sdk/src/physics/PlatformerController2D.ts b/sdk/src/physics/PlatformerController2D.tsnew file mode 100644index 000000000..d76e5dba7--- /dev/null+++ b/sdk/src/physics/PlatformerController2D.ts@@ -0,0 +1,207 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file PlatformerController2D.ts+ * @brief What a side-on character wants: run, jump, drop through. CharacterController2D is what the world makes of it.+ *+ * @details The forgiveness a platformer is judged on lives here, and on its own clock. A jump pressed a moment before landing still+ * happens, and one pressed a moment after running off a ledge does too. Input is read per rendered frame and latched, so a tap+ * between two fixed steps is not lost, and consumed on the fixed step, where the character actually moves.+ */+import { defineComponent, type ComponentDef } from '../ecs/component';++/** The fields of the `PlatformerController2D` component. @experimental */+export interface PlatformerController2DData {+ /** Top running speed, world pixels per second. */+ moveSpeed: number;+ /** How fast it reaches that speed on the ground, and in the air. */+ groundAcceleration: number;+ airAcceleration: number;+ /** How fast it sheds it when the stick centres, on the ground and in the air. */+ groundDeceleration: number;+ airDeceleration: number;+ /** Downward acceleration, world pixels per second squared. */+ gravity: number;+ /** Gravity multiplier while falling. Above 1 lands faster than it rose, which reads as weight. */+ fallGravityScale: number;+ /** The fastest it falls. */+ maxFallSpeed: number;+ /** Upward speed a jump starts with; 0 disables jumping. */+ jumpSpeed: number;+ /** How much of a rising speed survives letting go of jump, 0..1. 1 makes every jump full height. */+ jumpCut: number;+ /** Seconds after leaving the ground that a jump still counts as from the ground. */+ coyoteTime: number;+ /** Seconds a jump pressed too early is remembered, to happen on landing. */+ jumpBuffer: number;+ /** Extra jumps before landing again. */+ airJumps: number;+ /** Seconds a drop through a one-way platform lasts. */+ dropTime: number;+ /** A jump keeps the velocity of the platform it left. */+ keepPlatformVelocity: boolean;+ /** Read the keyboard itself. Off, a game or an AI writes `moveInput`, `jumpHeld`, `jumpPressed` and `dropPressed`. */+ readKeyboard: boolean;+ /** Input: -1 left to 1 right. */+ moveInput: number;+ /** Input: the jump button is down. */+ jumpHeld: boolean;+ /** Input: the jump button went down. Consumed by the next fixed step. */+ jumpPressed: boolean;+ /** Input: ask to drop through a one-way platform. Consumed by the next fixed step. */+ dropPressed: boolean;+ enabled: boolean;+}++/**+ * Runs and jumps a CharacterController2D, with the forgiveness a platformer needs.+ *+ * @experimental+ */+export const PlatformerController2D: ComponentDef<PlatformerController2DData> = defineComponent<PlatformerController2DData>('PlatformerController2D', {+ moveSpeed: 260,+ groundAcceleration: 2400,+ airAcceleration: 1500,+ groundDeceleration: 3000,+ airDeceleration: 900,+ gravity: 1600,+ fallGravityScale: 1.25,+ maxFallSpeed: 1000,+ jumpSpeed: 620,+ jumpCut: 0.5,+ coyoteTime: 0.1,+ jumpBuffer: 0.12,+ airJumps: 0,+ dropTime: 0.2,+ keepPlatformVelocity: true,+ readKeyboard: true,+ moveInput: 0,+ jumpHeld: false,+ jumpPressed: false,+ dropPressed: false,+ enabled: true,+}, {+ fields: {+ moveSpeed: { min: 0, unit: 'px/s' },+ groundAcceleration: { min: 0, unit: 'px/s²', advanced: true },+ airAcceleration: { min: 0, unit: 'px/s²', advanced: true },+ groundDeceleration: { min: 0, unit: 'px/s²', advanced: true },+ airDeceleration: { min: 0, unit: 'px/s²', advanced: true },+ gravity: { min: 0, unit: 'px/s²' },+ fallGravityScale: { min: 0, step: 0.05, advanced: true, tooltip: 'Gravity multiplier while falling. Above 1 lands faster than it rose.' },+ maxFallSpeed: { min: 0, unit: 'px/s', advanced: true },+ jumpSpeed: { min: 0, unit: 'px/s', tooltip: 'Upward speed a jump starts with. 0 = cannot jump.' },+ jumpCut: { min: 0, max: 1, step: 0.05, tooltip: 'How much of a rising speed survives letting go of jump. 1 makes every jump full height.' },+ coyoteTime: { min: 0, step: 0.01, unit: 's', tooltip: 'After leaving the ground, how long a jump still counts as from the ground.' },+ jumpBuffer: { min: 0, step: 0.01, unit: 's', tooltip: 'How long a jump pressed too early is remembered, to happen on landing.' },+ airJumps: { min: 0, step: 1, tooltip: 'Extra jumps before landing again.' },+ dropTime: { min: 0, step: 0.01, unit: 's', tooltip: 'How long a drop through a one-way platform lasts.' },+ readKeyboard: { tooltip: 'Move with A/D or the arrows, jump with Space, W or Up, drop with Down or S and jump. Off, a game writes the inputs itself.' },+ moveInput: { min: -1, max: 1, step: 0.1, advanced: true },+ jumpHeld: { advanced: true },+ jumpPressed: { advanced: true },+ dropPressed: { advanced: true },+ },+});++/** What is true of one character between fixed steps. Not authored and not saved. @internal */+export interface PlatformerState {+ /** Seconds of coyote time left. */+ coyote: number;+ /** Seconds a buffered jump has left. */+ buffered: number;+ /** Seconds a drop has left. */+ dropping: number;+ airJumpsLeft: number;+ /** Rising from a jump that has not yet been cut. */+ jumping: boolean;+}++export function platformerState(airJumps = 0): PlatformerState {+ return { coyote: 0, buffered: 0, dropping: 0, airJumpsLeft: airJumps, jumping: false };+}++/** What the character controller reported of the last move. @internal */+export interface PlatformerGround {+ onFloor: boolean;+ onCeiling: boolean;+ /** The velocity of what it stands on. */+ floorVelocityX: number;+ floorVelocityY: number;+}++/** The velocity and collision wishes one fixed step ends in. @internal */+export interface PlatformerStep {+ velocityX: number;+ velocityY: number;+ dropThrough: boolean;+ jumped: boolean;+}++const approach = (from: number, to: number, step: number): number =>+ from < to ? Math.min(to, from + step) : Math.max(to, from - step);++/**+ * One fixed step of what the character wants, from its last velocity. Pure: every rule a player feels is here, and none of it needs a world.+ * Velocities are along the world's right and up. It updates `state`, and consumes nothing of `config`.+ * @internal+ */+export function stepPlatformer(+ config: PlatformerController2DData, state: PlatformerState, ground: PlatformerGround,+ velocityX: number, velocityY: number, jumpPressed: boolean, dropPressed: boolean, dt: number,+): PlatformerStep {+ const target = Math.max(-1, Math.min(1, config.moveInput)) * config.moveSpeed;+ const moving = target !== 0 && (velocityX === 0 || Math.sign(target) === Math.sign(velocityX));+ const rate = ground.onFloor+ ? (moving ? config.groundAcceleration : config.groundDeceleration)+ : (moving ? config.airAcceleration : config.airDeceleration);+ let vx = approach(velocityX, target, rate * dt);+ let vy = velocityY;++ state.coyote = Math.max(0, state.coyote - dt);+ state.buffered = Math.max(0, state.buffered - dt);+ state.dropping = Math.max(0, state.dropping - dt);++ if (ground.onFloor && vy <= 0) {+ state.coyote = config.coyoteTime;+ state.airJumpsLeft = config.airJumps;+ state.jumping = false;+ }+ if (jumpPressed) state.buffered = Math.max(config.jumpBuffer, dt);++ // A drop is asked for on the ground, and the same press is not also a jump.+ if (dropPressed && ground.onFloor) {+ state.dropping = config.dropTime;+ state.buffered = 0;+ }++ let jumped = false;+ if (state.buffered > 0 && config.jumpSpeed > 0 && state.dropping <= 0) {+ const fromGround = state.coyote > 0;+ if (fromGround || state.airJumpsLeft > 0) {+ if (!fromGround) state.airJumpsLeft--;+ vy = config.jumpSpeed;+ if (fromGround && config.keepPlatformVelocity) {+ vx += ground.floorVelocityX;+ if (ground.floorVelocityY > 0) vy += ground.floorVelocityY;+ }+ state.coyote = 0;+ state.buffered = 0;+ state.jumping = true;+ jumped = true;+ }+ }++ if (!jumped) {+ // Letting go of jump ends the rise once. The cut is on the jump, so being thrown upward by something else is left alone.+ if (state.jumping && vy > 0 && !config.jumpHeld) {+ vy *= config.jumpCut;+ state.jumping = false;+ }+ if (ground.onCeiling && vy > 0) vy = 0;+ const gravity = config.gravity * (vy < 0 ? config.fallGravityScale : 1);+ vy = Math.max(-config.maxFallSpeed, vy - gravity * dt);+ }++ return { velocityX: vx, velocityY: vy, dropThrough: state.dropping > 0, jumped };+}diff --git a/sdk/src/physics/components.ts b/sdk/src/physics/components.tsindex c2a31d696..2311f5156 100644--- a/sdk/src/physics/components.ts+++ b/sdk/src/physics/components.ts@@ -18,3 +18,4 @@ export {type CharacterController2DData, type SlideHit, type SlideCast,type MoveAndSlideParams, type MoveAndSlideResult,} from './CharacterController2D';+export { PlatformerController2D, type PlatformerController2DData } from './PlatformerController2D';diff --git a/sdk/src/physics/index.ts b/sdk/src/physics/index.tsindex f96158fb6..aedaed1ba 100644--- a/sdk/src/physics/index.ts+++ b/sdk/src/physics/index.ts@@ -113,6 +113,8 @@ export {type SlideHit,} from './CharacterController2D';export { registerCharacterController2DSystem } from './CharacterController2DSystem';+export { PlatformerController2D, type PlatformerController2DData } from './PlatformerController2D';+export { CharacterDynamicBodies } from './CharacterController2D';// Importing this subpath INSTALLS 2D physics — see spine/index.ts.import { registerPhysics2DSupport } from './physicsSupport';diff --git a/sdk/tests/mover-smoke.mjs b/sdk/tests/mover-smoke.mjsindex a3d9b2591..08b97d575 100644--- a/sdk/tests/mover-smoke.mjs+++ b/sdk/tests/mover-smoke.mjs@@ -29,7 +29,7 @@ const buf = () => {const move = (py, vx, vy, opts = {}) => {const { skin = 0, maxSlides = 5, snap = 0, slideCeil = 1, px = 0 } = opts;const ok = m._physics_moveCharacter(px, py, 0, 0.08, 0, -0.08, 0.16, vx, vy, 1 / 60, 0, 1,- Math.cos(Math.PI / 4), 0xfffd, SELF, skin, maxSlides, snap, slideCeil);+ Math.cos(Math.PI / 4), 0xfffd, SELF, skin, maxSlides, snap, slideCeil, 0, 0, 0, 0);return ok ? buf() : null;};diff --git a/sdk/tests/platformer-controller-2d-wasm.test.ts b/sdk/tests/platformer-controller-2d-wasm.test.tsnew file mode 100644index 000000000..af482a082--- /dev/null+++ b/sdk/tests/platformer-controller-2d-wasm.test.ts@@ -0,0 +1,535 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * The real solver under the character: each of these is a thing the mover got wrong or could not do, measured where a player would feel it.+ */+import { afterEach, beforeAll, describe, expect, it } from 'vitest';+import { App } from '../src/app/app';+import { Transform } from '../src/ecs/component';+import { setPlayMode } from '../src/ecs/env';+import { Schedule, defineSystem } from '../src/ecs/system';+import { Physics2DPlugin } from '../src/physics/Physics2DPlugin';+import { Physics2DRuntime } from '../src/physics/Physics2DRuntime';+import { CharacterController2D, CharacterDynamicBodies } from '../src/physics/CharacterController2D';+import { PlatformerController2D } from '../src/physics/PlatformerController2D';+import { RigidBody2D, BoxCollider2D, CapsuleCollider2D, PolygonCollider2D, OneWayPlatform2D, BodyType } from '../src/physics/PhysicsComponents';+import type { Entity } from '../src/types';+import type { ESEngineModule } from '../src/wasm';+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';++let core: ESEngineModule;+const apps: App[] = [];+afterEach(() => { for (const app of apps.splice(0)) app.quit(); setPlayMode(false); });++/** The capsule's foot rests this far below its origin: half height + radius + what is left of the default skin. */+const FOOT = 25.5;+const GRAVITY = -1600;++async function scene() {+ core.setActiveContext(null);+ const app = App.new(); apps.push(app); app.connectCpp(new core.Registry(), core, { ownedRegistry: true });+ setPlayMode(true);+ const module = await loadSideModule<PhysicsWasmModule>('physics');+ app.addPlugin(new Physics2DPlugin('', { gravity: { x: 0, y: 0 }, fixedTimestep: 1 / 60 }, async () => module));+ await app.getResource(Physics2DRuntime).initPromise;+ const world = app.world;+ const box = (x: number, y: number, hw: number, hh: number, type: number = BodyType.Static, sensor = false): Entity => {+ const e = world.spawn();+ world.insert(e, Transform, { position: { x, y, z: 0 } });+ world.insert(e, RigidBody2D, { bodyType: type, gravityScale: 0 });+ world.insert(e, BoxCollider2D, { halfExtents: { x: hw / 100, y: hh / 100 }, isSensor: sensor } as never);+ return e;+ };+ const oneWay = (x: number, y: number, hw: number, hh: number): Entity => {+ const e = box(x, y, hw, hh);+ world.insert(e, OneWayPlatform2D, { normal: { x: 0, y: 1 }, enabled: true });+ return e;+ };+ const slope = (degrees: number): number => {+ const t = Math.tan(degrees * Math.PI / 180), e = world.spawn(), L = 8;+ world.insert(e, Transform, { position: { x: 0, y: 0, z: 0 } });+ world.insert(e, RigidBody2D, { bodyType: BodyType.Static });+ world.insert(e, PolygonCollider2D, { vertices: [{ x: -L, y: -L * t - 1 }, { x: L, y: L * t - 1 }, { x: L, y: L * t }, { x: -L, y: -L * t }] } as never);+ return t;+ };+ const capsule = (x: number, y: number, fields: Record<string, unknown> = {}): Entity => {+ const e = world.spawn();+ world.insert(e, Transform, { position: { x, y, z: 0 } });+ world.insert(e, CapsuleCollider2D, { radius: 0.1, halfHeight: 0.15 });+ world.insert(e, CharacterController2D, { snapLength: 8, ...fields } as never);+ return e;+ };+ const player = (x: number, y: number, fields: Record<string, unknown> = {}, cc: Record<string, unknown> = {}): Entity => {+ const e = capsule(x, y, cc);+ world.insert(e, PlatformerController2D, { readKeyboard: false, ...fields } as never);+ return e;+ };+ // A bare controller is told what to want by gravity and a steady walk.+ const drive = { vx: 0, gravity: GRAVITY };+ app.addSystemToSchedule(Schedule.FixedUpdate, defineSystem([], () => {+ for (const e of world.getEntitiesWithComponents([CharacterController2D])) {+ if (world.has(e, PlatformerController2D)) continue;+ world.update(e, CharacterController2D, (c) => { c.velocity.x = drive.vx; c.velocity.y += drive.gravity / 60; });+ }+ }, { name: 'Drive' }), { runBefore: ['CharacterController2DSystem'] });+ const at = (e: Entity) => world.get(e, Transform).position;+ const cc = (e: Entity) => world.get(e, CharacterController2D);+ const run = (n: number) => app.stepFrames(n, 1 / 60);+ const press = (e: Entity, fields: Record<string, unknown>) => world.update(e, PlatformerController2D, (p) => { Object.assign(p, fields); });+ return { app, world, module, box, oneWay, slope, capsule, player, drive, at, cc, run, press };+}++describe.skipIf(!HAS_WASM || !hasSideModule('physics'))('a 2D character on the real solver', () => {+ beforeAll(async () => { core = await loadWasmModule(); });++ describe('slopes', () => {+ it.each([20, 30, 44])('stands still on a walkable %s degree slope', async (degrees) => {+ const s = await scene(); s.slope(degrees);+ const c = s.capsule(-100, 200); await s.run(90);+ expect(s.cc(c).isOnFloor).toBe(true);+ const x = s.at(c).x, y = s.at(c).y;+ await s.run(120);+ expect(s.at(c).x).toBeCloseTo(x, 1); expect(s.at(c).y).toBeCloseTo(y, 1);+ });++ it.each([[30, 1], [30, -1], [44, 1], [44, -1]])('walks %s degrees at the speed across the ground it asks for, way %s, without leaving it', async (degrees, way) => {+ const s = await scene(); const t = s.slope(degrees);+ const c = s.capsule(0, 100); await s.run(60);+ const x = s.at(c).x, gap = s.at(c).y - x * t;+ s.drive.vx = 200 * way;+ for (let i = 0; i < 30; i++) { await s.run(1); expect(s.cc(c).isOnFloor).toBe(true); }+ expect(s.at(c).x - x).toBeCloseTo(100 * way, 0);+ expect(s.at(c).y - s.at(c).x * t).toBeCloseTo(gap, 0);+ });++ it('keeps the speed along the slope when asked to', async () => {+ const s = await scene(); s.slope(30);+ const c = s.capsule(0, 100, { constantSlopeSpeed: true }); await s.run(60);+ const a = { x: s.at(c).x, y: s.at(c).y };+ s.drive.vx = 200; await s.run(30);+ expect(Math.hypot(s.at(c).x - a.x, s.at(c).y - a.y)).toBeCloseTo(100, 0);+ });++ it('is not launched off the top of a slope', async () => {+ const s = await scene();+ const e = s.world.spawn();+ s.world.insert(e, Transform, { position: { x: 0, y: 0, z: 0 } });+ s.world.insert(e, RigidBody2D, { bodyType: BodyType.Static });+ s.world.insert(e, PolygonCollider2D, { vertices: [{ x: -3, y: -3 - 1 }, { x: 0, y: 0 }, { x: 0, y: -4 }] } as never);+ s.box(300, -10, 300, 10);+ const c = s.capsule(-200, -100, { snapLength: 2 }); await s.run(60);+ s.drive.vx = 300;+ let top = -Infinity;+ for (let i = 0; i < 90; i++) { await s.run(1); top = Math.max(top, s.at(c).y); }+ expect(top).toBeLessThan(FOOT + 12);+ });++ it('walks into a slope too steep to stand on as into a wall, and slides down it', async () => {+ const s = await scene(); const t = s.slope(55);+ s.box(0, -600, 2000, 10);+ const c = s.capsule(-150, -150 * t + 80); await s.run(60);+ expect(s.cc(c).isOnFloor).toBe(false);+ s.drive.vx = 300;+ const before = s.at(c).x;+ await s.run(10);+ const after = s.at(c).x;+ await s.run(30);+ expect(s.at(c).x).toBeLessThanOrEqual(after + 1);+ expect(s.at(c).y).toBeLessThan(before * t);+ });++ it('walks up one when told it may', async () => {+ const s = await scene(); const t = s.slope(55);+ const c = s.capsule(-150, -150 * t + 80, { blockSteepSlopes: false }); await s.run(40);+ const y = s.at(c).y;+ s.drive.vx = 400; await s.run(30);+ expect(s.at(c).y).toBeGreaterThan(y + 20);+ });+ });++ describe('steps', () => {+ const walk = async (height: number, stepHeight: number) => {+ const s = await scene(); s.box(0, -100, 1000, 20);+ s.box(300, -80 + height / 2, 100, height / 2);+ const c = s.capsule(0, -40, { stepHeight }); await s.run(30);+ s.drive.vx = 200; await s.run(90);+ return { x: s.at(c).x, y: s.at(c).y, floor: s.cc(c).isOnFloor };+ };++ it('walks up a ledge within its reach, and lands on it', async () => {+ const up = await walk(24, 26);+ expect(up.x).toBeGreaterThan(280);+ expect(up.y).toBeCloseTo(-80 + 24 + FOOT, -0.5);+ expect(up.floor).toBe(true);+ });++ it('stops at a ledge beyond it', async () => {+ const blocked = await walk(40, 26);+ expect(blocked.x).toBeLessThan(200);+ });++ it('still rides over what its rounded foot can', async () => {+ expect((await walk(8, 0)).x).toBeGreaterThan(280);+ });++ it('stops at the same ledge without stepHeight, as before', async () => {+ expect((await walk(24, 0)).x).toBeLessThan(200);+ });++ it('does not step up while falling past a ledge', async () => {+ const s = await scene(); s.box(0, -300, 1000, 20);+ s.box(100, -100, 50, 40);+ // Pressed against the face with its foot 15 below the top: a walk would step this, a fall must not.+ const c = s.capsule(38, -49.5, { stepHeight: 30 });+ s.drive.vx = 300; await s.run(14);+ expect(s.at(c).x).toBeLessThan(45);+ expect(s.at(c).y).toBeLessThan(-90);+ });++ it('does not step through a low ceiling', async () => {+ const s = await scene(); s.box(0, -100, 1000, 20);+ s.box(300, -70, 100, 10);+ s.box(300, -5, 100, 10);+ const c = s.capsule(0, -40, { stepHeight: 30 }); await s.run(30);+ s.drive.vx = 200; await s.run(90);+ expect(s.at(c).x).toBeLessThan(205);+ });+ });++ describe('one-way platforms', () => {+ it('jumps up through one and lands on it', async () => {+ const s = await scene(); s.box(0, -100, 1000, 20); s.oneWay(0, 40, 80, 5);+ const c = s.capsule(0, -40); await s.run(30);+ s.world.update(c, CharacterController2D, (v) => { v.velocity.y = 900; });+ let top = -Infinity;+ for (let i = 0; i < 40; i++) { await s.run(1); top = Math.max(top, s.at(c).y); }+ expect(top).toBeGreaterThan(45 + FOOT);+ await s.run(60);+ expect(s.at(c).y).toBeCloseTo(45 + FOOT, 0);+ expect(s.cc(c).isOnFloor).toBe(true);+ });++ it('lands on a thin one at a fall too fast to catch it by overlap', async () => {+ const s = await scene(); s.box(0, -300, 1000, 20); s.oneWay(0, 0, 80, 5);+ const c = s.capsule(0, 1500); await s.run(120);+ expect(s.cc(c).isOnFloor).toBe(true);+ expect(s.at(c).y).toBeCloseTo(5 + FOOT, 0);+ });++ // 60 px/s rises less than the slop in a step: only its direction says it has left.+ it.each([620, 60])('is off it from the moment it rises at %s', async (jumpSpeed) => {+ const s = await scene(); s.oneWay(0, 0, 200, 5);+ const c = s.player(0, 60, { jumpSpeed }); await s.run(60);+ expect(s.cc(c).isOnFloor).toBe(true);+ s.press(c, { jumpHeld: true, jumpPressed: true }); await s.run(1);+ expect(s.cc(c).isOnFloor).toBe(false);+ });++ it('walks in and out of one at its height, side on', async () => {+ const s = await scene(); s.box(0, -100, 1000, 20); s.oneWay(150, -50, 40, 10);+ const c = s.capsule(0, -40); await s.run(30);+ s.drive.vx = 200; await s.run(90);+ expect(s.at(c).x).toBeGreaterThan(270);+ });++ it('drops through while told to, and stands on it otherwise', async () => {+ const s = await scene(); s.box(0, -300, 1000, 20); s.oneWay(0, 0, 80, 5);+ const c = s.capsule(0, 60); await s.run(60);+ expect(s.at(c).y).toBeCloseTo(5 + FOOT, 0);+ s.world.update(c, CharacterController2D, (v) => { v.dropThrough = true; });+ await s.run(30);+ s.world.update(c, CharacterController2D, (v) => { v.dropThrough = false; });+ await s.run(60);+ expect(s.at(c).y).toBeCloseTo(-280 + FOOT, 0);+ });++ // At 6 only the rounded foot is inside and the solver would push it out; at 20 its core is, and the solver reports nothing.+ it.each([6, 20])('is not popped back on top when a drop ends %s in', async (depth) => {+ const s = await scene(); s.box(0, -300, 1000, 20); s.oneWay(0, 0, 80, 30);+ const c = s.capsule(0, 60); await s.run(60);+ s.world.update(c, CharacterController2D, (v) => { v.dropThrough = true; });+ for (let i = 0; i < 60 && s.at(c).y > 30 + FOOT - depth; i++) await s.run(1);+ const y = s.at(c).y;+ expect(y).toBeLessThanOrEqual(30 + FOOT - depth);+ s.world.update(c, CharacterController2D, (v) => { v.dropThrough = false; });+ await s.run(3);+ expect(s.at(c).y).toBeLessThan(y);+ expect(s.cc(c).isOnFloor).toBe(false);+ });+ });++ describe('moving platforms', () => {+ async function onPlatform(fields: Record<string, unknown> = {}) {+ const s = await scene(); s.box(0, -600, 4000, 20);+ const p = s.box(0, -100, 150, 10, BodyType.Kinematic);+ const c = s.capsule(0, -40, fields); await s.run(30);+ expect(s.cc(c).isOnFloor).toBe(true);+ expect(s.cc(c).floorEntity).toBe(p);+ const move = async (dx: number, dy: number, frames: number) => {+ for (let i = 0; i < frames; i++) {+ s.world.update(p, Transform, (t) => { t.position.x += dx; t.position.y += dy; });+ await s.run(1);+ expect(s.cc(c).isOnFloor).toBe(true);+ }+ };+ return { ...s, p, c, move };+ }++ it('rides sideways', async () => {+ const s = await onPlatform();+ const x = s.at(s.c).x;+ await s.move(2, 0, 30);+ await s.run(2);+ expect(s.at(s.c).x - x).toBeCloseTo(60, 0);+ });++ it.each([[3], [-3]])('rides a lift at %s a frame, with its foot on the floor', async (dy) => {+ const s = await onPlatform();+ const gap = s.at(s.c).y - s.at(s.p).y;+ await s.move(0, dy, 30);+ await s.run(2);+ expect(s.at(s.c).y - s.at(s.p).y).toBeCloseTo(gap, 0);+ });++ it('rides a one-way lift up', async () => {+ const s = await scene();+ const p = s.oneWay(0, -100, 400, 10);+ s.world.update(p, RigidBody2D, (b) => { b.bodyType = BodyType.Kinematic; });+ const c = s.capsule(0, -40); await s.run(40);+ const gap = s.at(c).y - s.at(p).y;+ for (let i = 0; i < 30; i++) { s.world.update(p, Transform, (t) => { t.position.y += 3; }); await s.run(1); }+ expect(s.cc(c).isOnFloor).toBe(true);+ expect(s.at(c).y - s.at(p).y).toBeCloseTo(gap, -1);+ });++ it('walks on it at its own speed on top of the ride', async () => {+ const s = await onPlatform();+ const x = s.at(s.c).x;+ s.drive.vx = 60;+ await s.move(1, 0, 30);+ await s.run(1);+ expect(s.at(s.c).x - x).toBeCloseTo(30 + 31, 0);+ expect(s.cc(s.c).velocity.x).toBeCloseTo(60, 3);+ });++ it('is stopped by a wall the platform carries it into', async () => {+ const s = await onPlatform();+ s.box(100, -40, 10, 50);+ await s.move(3, 0, 40);+ expect(s.at(s.c).x).toBeLessThan(90);+ });++ it('stays put when told not to follow', async () => {+ const s = await onPlatform({ followPlatform: false });+ const x = s.at(s.c).x;+ await s.move(2, 0, 30);+ expect(s.at(s.c).x).toBeCloseTo(x, 0);+ });+ });++ describe('what it collides with', () => {+ it('walks through a trigger', async () => {+ const s = await scene(); s.box(0, -100, 1000, 20);+ s.box(100, -40, 20, 50, BodyType.Static, true);+ const c = s.capsule(0, -40); await s.run(30);+ s.drive.vx = 200; await s.run(60);+ expect(s.at(c).x).toBeGreaterThan(190);+ });++ it('stands on no trigger', async () => {+ const s = await scene(); s.box(0, -200, 1000, 20);+ s.box(0, -100, 100, 10, BodyType.Static, true);+ const c = s.capsule(0, 0); await s.run(90);+ expect(s.at(c).y).toBeCloseTo(-180 + FOOT, 0);+ });++ const crate = async (dynamicBodies: number, pushForce = 40) => {+ const s = await scene(); s.box(0, -100, 1000, 20);+ const body = s.box(100, -60, 20, 20, BodyType.Dynamic);+ const c = s.capsule(0, -40, { dynamicBodies, pushForce }); await s.run(30);+ s.drive.vx = 200; await s.run(60);+ return { char: s.at(c).x, crate: s.at(body).x };+ };++ it('is stopped by a crate by default, which stays', async () => {+ const { char, crate: where } = await crate(CharacterDynamicBodies.Block);+ expect(char).toBeLessThan(90);+ expect(where).toBeCloseTo(100, 0);+ });++ it('pushes a crate when told to, and goes with it', async () => {+ const { char, crate: where } = await crate(CharacterDynamicBodies.Push);+ expect(where).toBeGreaterThan(120);+ expect(char).toBeGreaterThan(90);+ });++ it('passes through a crate when told to', async () => {+ const { char, crate: where } = await crate(CharacterDynamicBodies.Ignore);+ expect(char).toBeGreaterThan(190);+ expect(where).toBeCloseTo(100, 0);+ });++ it('moves in the world under a parent', async () => {+ const s = await scene(); s.box(500, -100, 300, 20);+ const parent = s.world.spawn(); s.world.insert(parent, Transform, { position: { x: 500, y: 50, z: 0 } });+ const c = s.capsule(0, -40); s.world.setParent(c, parent);+ await s.run(60);+ s.world.ensureTransformsComposed();+ expect(s.world.get(c, Transform).worldPosition.y).toBeCloseTo(-80 + FOOT, 0);+ expect(s.cc(c).isOnFloor).toBe(true);+ });+ });++ describe('the platformer on top of it', () => {+ const ground = async (p: Record<string, unknown> = {}, cc: Record<string, unknown> = {}) => {+ const s = await scene(); s.box(0, -100, 2000, 20);+ const c = s.player(0, -40, p, cc); await s.run(40);+ expect(s.cc(c).isOnFloor).toBe(true);+ return { ...s, c };+ };++ it('reaches its speed, then stops', async () => {+ const s = await ground();+ s.press(s.c, { moveInput: 1 }); await s.run(30);+ expect(s.cc(s.c).velocity.x).toBeCloseTo(260, 1);+ s.press(s.c, { moveInput: 0 }); await s.run(30);+ expect(s.cc(s.c).velocity.x).toBe(0);+ });++ it('jumps as high as its speed and gravity say, and lands', async () => {+ const s = await ground({ jumpSpeed: 600, gravity: 1600 });+ const y = s.at(s.c).y;+ s.press(s.c, { jumpHeld: true, jumpPressed: true });+ let top = y;+ for (let i = 0; i < 40; i++) { await s.run(1); top = Math.max(top, s.at(s.c).y); }+ expect(top - y).toBeGreaterThan(105); expect(top - y).toBeLessThan(120);+ await s.run(60);+ expect(s.at(s.c).y).toBeCloseTo(y, 0);+ expect(s.cc(s.c).isOnFloor).toBe(true);+ });++ it('jumps lower when the button is let go', async () => {+ const height = async (held: number) => {+ const s = await ground({ jumpSpeed: 600 });+ const y = s.at(s.c).y;+ s.press(s.c, { jumpHeld: true, jumpPressed: true });+ let top = y;+ for (let i = 0; i < 50; i++) {+ if (i === held) s.press(s.c, { jumpHeld: false });+ await s.run(1); top = Math.max(top, s.at(s.c).y);+ }+ return top - y;+ };+ expect(await height(4)).toBeLessThan((await height(60)) * 0.6);+ });++ it('still jumps just after running off a ledge, and not long after', async () => {+ const off = async (late: number) => {+ const s = await scene(); s.box(-200, -100, 200, 20); s.box(0, -900, 3000, 20);+ const c = s.player(-40, -40, { coyoteTime: 0.1 }); await s.run(30);+ s.press(c, { moveInput: 1 }); s.world.update(c, CharacterController2D, (v) => { v.velocity.x = 260; });+ while (s.cc(c).isOnFloor) await s.run(1);+ await s.run(late);+ s.press(c, { jumpHeld: true, jumpPressed: true });+ await s.run(1);+ return s.cc(c).velocity.y;+ };+ expect(await off(2)).toBeGreaterThan(500);+ expect(await off(12)).toBeLessThan(0);+ });++ it('remembers a jump pressed just before landing, and not long before', async () => {+ const land = async (frames: number) => {+ const s = await scene(); s.box(0, -100, 2000, 20);+ const c = s.player(0, 400, { jumpBuffer: 0.1 });+ let i = 0;+ while (true) {+ await s.run(1); i++;+ // How far above the floor it will be `frames` steps from now, falling as it is.+ const fall = -s.cc(c).velocity.y / 60 * frames;+ if (s.at(c).y - fall <= -80 + FOOT || i > 300) break;+ }+ s.press(c, { jumpHeld: true, jumpPressed: true });+ let best = -Infinity;+ for (let n = 0; n < frames + 3; n++) { await s.run(1); best = Math.max(best, s.cc(c).velocity.y); }+ return best;+ };+ expect(await land(3)).toBeGreaterThan(400);+ expect(await land(14)).toBeLessThanOrEqual(0);+ });++ it('does not jump in the air without coyote time or an air jump, and does with one', async () => {+ const s = await scene(); s.box(0, -900, 2000, 20);+ const c = s.player(0, 0, { airJumps: 1 }); await s.run(5);+ s.press(c, { jumpHeld: true, jumpPressed: true }); await s.run(1);+ expect(s.cc(c).velocity.y).toBeGreaterThan(500);+ await s.run(50);+ s.press(c, { jumpPressed: true }); await s.run(1);+ expect(s.cc(c).velocity.y).toBeLessThan(0);+ });++ it('gets its air jumps back on landing', async () => {+ const s = await ground({ airJumps: 1, jumpSpeed: 300 });+ const jump = async () => { s.press(s.c, { jumpHeld: true, jumpPressed: true }); await s.run(1); };+ await jump(); await s.run(4);+ await jump();+ expect(s.cc(s.c).velocity.y).toBeGreaterThan(250);+ await s.run(4);+ await jump();+ expect(s.cc(s.c).velocity.y).toBeLessThan(250);+ await s.run(120);+ expect(s.cc(s.c).isOnFloor).toBe(true);+ await jump(); await s.run(4);+ await jump();+ expect(s.cc(s.c).velocity.y).toBeGreaterThan(250);+ });++ it('spends its coyote time on the jump that used it', async () => {+ const s = await ground({ coyoteTime: 0.5 });+ s.press(s.c, { jumpHeld: true, jumpPressed: true }); await s.run(1);+ const first = s.cc(s.c).velocity.y;+ await s.run(5);+ s.press(s.c, { jumpPressed: true }); await s.run(1);+ expect(s.cc(s.c).velocity.y).toBeLessThan(first);+ });++ it('takes a drop pressed with jump as a drop alone', async () => {+ const s = await scene(); s.box(0, -300, 2000, 20); s.oneWay(0, 0, 200, 5);+ const c = s.player(0, 60, { jumpBuffer: 1, dropTime: 0.1, coyoteTime: 1 }); await s.run(60);+ s.press(c, { jumpPressed: true, dropPressed: true });+ for (let i = 0; i < 20; i++) { await s.run(1); expect(s.cc(c).velocity.y).toBeLessThanOrEqual(0); }+ });++ it('drops through a one-way platform on asking, and not through solid ground', async () => {+ const s = await scene(); s.box(0, -300, 2000, 20); s.oneWay(0, 0, 200, 5);+ const c = s.player(0, 60); await s.run(60);+ const y = s.at(c).y;+ s.press(c, { dropPressed: true }); await s.run(30);+ expect(s.at(c).y).toBeLessThan(y - 20);+ expect(s.cc(c).velocity.y).toBeLessThan(0);+ await s.run(60);+ const low = s.at(c).y;+ s.press(c, { dropPressed: true }); await s.run(30);+ expect(s.at(c).y).toBeCloseTo(low, 0);+ });++ it('keeps a moving platform\'s speed when it jumps off', async () => {+ const s = await scene(); s.box(0, -900, 6000, 20);+ const p = s.box(0, -100, 400, 10, BodyType.Kinematic);+ const c = s.player(0, -40); await s.run(40);+ for (let i = 0; i < 10; i++) { s.world.update(p, Transform, (t) => { t.position.x += 3; }); await s.run(1); }+ s.press(c, { jumpHeld: true, jumpPressed: true }); await s.run(1);+ expect(s.cc(c).velocity.x).toBeCloseTo(180, -1);+ });++ it('does nothing disabled', async () => {+ const s = await ground();+ s.press(s.c, { enabled: false });+ const y = s.cc(s.c).velocity.y;+ s.press(s.c, { jumpPressed: true, moveInput: 1 }); await s.run(5);+ expect(s.cc(s.c).velocity.x).toBe(0);+ expect(s.cc(s.c).velocity.y).toBeCloseTo(y, 3);+ });+ });+});diff --git a/src/esengine/bindings/modules/physics/PhysicsBindings.hpp b/src/esengine/bindings/modules/physics/PhysicsBindings.hppindex 565750051..2042e1a69 100644--- a/src/esengine/bindings/modules/physics/PhysicsBindings.hpp+++ b/src/esengine/bindings/modules/physics/PhysicsBindings.hpp@@ -179,7 +179,7 @@ int physics_shapeCastCapsule(float center1X, float center1Y, float center2X, flo// @heapreturn physics_shapeCastBytes()uintptr_t physics_getShapeCastBuffer();int physics_overlapAABB(float minX, float minY, float maxX, float maxY, uint32_t maskBits);-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, float skinWidth, int maxSlides, float snapLength, int slideOnCeiling);+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, float skinWidth, int maxSlides, float snapLength, int slideOnCeiling, float carryX, float carryY, uint32_t flags, float stepHeight);// @heapreturn physics_moveCharacterBytes()uintptr_t physics_getMoveCharacterBuffer();diff --git a/src/esengine/bindings/modules/physics/PhysicsQueries.cpp b/src/esengine/bindings/modules/physics/PhysicsQueries.cppindex 8c828b675..891dc1e68 100644--- a/src/esengine/bindings/modules/physics/PhysicsQueries.cpp+++ b/src/esengine/bindings/modules/physics/PhysicsQueries.cpp@@ -3,6 +3,7 @@#include "./PhysicsContext.hpp"#include <cfloat>+#include <cstring>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;@@ -52,18 +53,83 @@ static float shapeCastCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, f// 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 constexpr int MAX_MOVER_HITS = 4;+// How far a one-way surface's normal must lean to the solid side for a contact to count. Above zero, so the side of a platform walked+// past is not a wall.+static constexpr float MOVER_ONE_WAY_ALIGN = 0.5f;+// Metres a mover may be sunk into a one-way surface and still stand on it: what the skin and the solver leave behind.+static constexpr float MOVER_ONE_WAY_SLOP = 0.02f;++static constexpr uint32_t MOVER_DROP_THROUGH = 1u;+static constexpr uint32_t MOVER_IGNORE_DYNAMIC = 2u;+static constexpr uint32_t MOVER_BLOCK_STEEP = 4u;+static constexpr uint32_t MOVER_WAS_ON_FLOOR = 8u;+static b2CollisionPlane g_moverPlanes[MAX_MOVER_PLANES];+static uint32_t g_moverPlaneEntity[MAX_MOVER_PLANES];+static bool g_moverPlaneSurface[MAX_MOVER_PLANES];static int g_moverPlaneCount = 0;static uint32_t g_moverSelfEntity = 0xFFFFFFFF;-static float g_moverBuffer[9] = {};+static uint32_t g_moverFlags = 0;+// The move's own velocity and how far it could fall, against which a one-way surface is judged.+static b2Vec2 g_moverVelocity = {0.0f, 0.0f};+static float g_moverDt = 0.0f;+// The record physics_moveCharacter writes: see physics_moveCharacterBytes.+static float g_moverBuffer[11 + MAX_MOVER_HITS * 3] = {};+static uint32_t g_moverHitEntity[MAX_MOVER_HITS];+static b2Vec2 g_moverHitNormal[MAX_MOVER_HITS];+static int g_moverHitCount = 0;++/** A one-way surface answers only from its solid side, while what meets it is not rising, and not once it is already inside it. */+static bool oneWayAdmits(b2ShapeId shapeId, uint32_t entity, b2Vec2 normal, float depth) {+ const auto it = g_ctx.oneWayNormals.find(entity);+ if (it == g_ctx.oneWayNormals.end()) return true;+ if (g_moverFlags & MOVER_DROP_THROUGH) return false;+ const b2Vec2 solid = it->second.localSpace+ ? b2RotateVector(b2Body_GetRotation(b2Shape_GetBody(shapeId)), it->second.normal)+ : it->second.normal;+ if (b2Dot(normal, solid) <= MOVER_ONE_WAY_ALIGN) return false;+ const float along = b2Dot(g_moverVelocity, solid);+ // A fall lands inside a thin surface before the mover looks at it, so a step's worth of fall still counts as landing on it.+ return depth <= MOVER_ONE_WAY_SLOP - along * g_moverDt;+}++/**+ * Whether a contact's normal is the surface's own. A rounded foot on the corner of a ledge gets a leaning normal off no slope at all, and+ * a ray along it tells them apart: it lands on a face, and only a real slope's face leans.+ */+static bool normalIsSurface(b2ShapeId shapeId, const b2PlaneResult* pr) {+ b2RayCastInput ray;+ ray.origin = b2MulAdd(pr->point, 0.05f, pr->plane.normal);+ ray.translation = b2MulSV(-0.1f, pr->plane.normal);+ ray.maxFraction = 1.0f;+ const b2CastOutput hit = b2Shape_RayCast(shapeId, &ray);+ return hit.hit && b2Dot(hit.normal, pr->plane.normal) > 0.999f;+}static bool moverPlaneCallback(b2ShapeId shapeId, const b2PlaneResult* pr, void* context) {(void)context;if (!pr->hit) return true;+ const uint32_t entity = entityFromShape(shapeId);// 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 (entity == g_moverSelfEntity) return true;+ // A trigger is walked through: it reports an overlap, and blocks nothing.+ if (b2Shape_IsSensor(shapeId)) return true;+ const bool dynamic = b2Body_GetType(b2Shape_GetBody(shapeId)) == b2_dynamicBody;+ if (dynamic && (g_moverFlags & MOVER_IGNORE_DYNAMIC)) return true;+ if (!oneWayAdmits(shapeId, entity, pr->plane.normal, pr->plane.offset)) return true;+ if (dynamic && g_moverHitCount < MAX_MOVER_HITS) {+ bool known = false;+ for (int i = 0; i < g_moverHitCount; ++i) known = known || g_moverHitEntity[i] == entity;+ if (!known) {+ g_moverHitEntity[g_moverHitCount] = entity;+ g_moverHitNormal[g_moverHitCount++] = pr->plane.normal;+ }+ }if (g_moverPlaneCount < MAX_MOVER_PLANES) {+ g_moverPlaneEntity[g_moverPlaneCount] = entity;+ g_moverPlaneSurface[g_moverPlaneCount] = (g_moverFlags & MOVER_BLOCK_STEEP) != 0 && normalIsSurface(shapeId, pr);g_moverPlanes[g_moverPlaneCount].plane = pr->plane;g_moverPlanes[g_moverPlaneCount].pushLimit = FLT_MAX;g_moverPlanes[g_moverPlaneCount].push = 0.0f;@@ -78,6 +144,7 @@ static bool moverPlaneCallback(b2ShapeId shapeId, const b2PlaneResult* pr, void*// kept manually rather than via cast clipping (a nearer wall must not hide a floor).static float g_snapClosest = 1.0f;static b2Vec2 g_snapNormal = {0.0f, 0.0f};+static uint32_t g_snapEntity = 0xFFFFFFFF;static bool g_snapHit = false;static b2Vec2 g_snapUp = {0.0f, 1.0f};static float g_snapFloorCos = 0.0f;@@ -85,16 +152,123 @@ static float g_snapFloorCos = 0.0f;static float snapCastCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) {(void)point;(void)context;- if (entityFromShape(shapeId) == g_moverSelfEntity) return 1.0f;+ const uint32_t entity = entityFromShape(shapeId);+ if (entity == g_moverSelfEntity || b2Shape_IsSensor(shapeId)) return 1.0f;+ if ((g_moverFlags & MOVER_IGNORE_DYNAMIC) && b2Body_GetType(b2Shape_GetBody(shapeId)) == b2_dynamicBody) return 1.0f;+ if (!oneWayAdmits(shapeId, entity, normal, 0.0f)) return 1.0f;float d = normal.x * g_snapUp.x + normal.y * g_snapUp.y;if (d >= g_snapFloorCos && fraction < g_snapClosest) {g_snapClosest = fraction;g_snapNormal = normal;+ g_snapEntity = entity;g_snapHit = true;}return 1.0f;}+// How far a cast up gets before something overhead stops it, for a mover stepping over a ledge.+static float g_headroom = 1.0f;++static float headroomCastCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) {+ (void)point;+ (void)context;+ const uint32_t entity = entityFromShape(shapeId);+ if (entity == g_moverSelfEntity || b2Shape_IsSensor(shapeId)) return 1.0f;+ if (g_ctx.oneWayNormals.count(entity) != 0) return 1.0f;+ // It is already touching the ledge and the floor, and a cast starting in touch reports them with no normal. Only what faces down is overhead.+ if (b2Dot(normal, g_snapUp) > -0.1f) return 1.0f;+ if ((g_moverFlags & MOVER_IGNORE_DYNAMIC) && b2Body_GetType(b2Shape_GetBody(shapeId)) == b2_dynamicBody) return 1.0f;+ if (fraction < g_headroom) g_headroom = fraction;+ return 1.0f;+}++namespace {++/** The mover's capsule and the query it sweeps with, the same for every part of one move. */+struct MoverShape {+ b2Vec2 c1, c2;+ float radius;+ b2QueryFilter filter;+ int slides;+};++b2Capsule capsuleAt(const MoverShape& shape, b2Vec2 pos) {+ b2Capsule capsule;+ capsule.center1 = b2Add(pos, shape.c1);+ capsule.center2 = b2Add(pos, shape.c2);+ capsule.radius = shape.radius;+ return capsule;+}++b2ShapeProxy proxyAt(const MoverShape& shape, b2Vec2 pos, b2Vec2 points[2]) {+ points[0] = b2Add(pos, shape.c1);+ points[1] = b2Add(pos, shape.c2);+ return b2MakeProxy(points, 2, shape.radius);+}++/** A slope too steep to stand on is a wall to walk into: what is left of the move is whatever does not press into it. */+b2Vec2 withoutClimbing(b2Vec2 delta, b2Vec2 up, float floorCos) {+ for (int i = 0; i < g_moverPlaneCount; ++i) {+ const b2Vec2 n = g_moverPlanes[i].plane.normal;+ const float d = b2Dot(n, up);+ if (d <= 0.0f || d >= floorCos || !g_moverPlaneSurface[i]) continue;+ const b2Vec2 across = b2Normalize(b2Sub(n, b2MulSV(d, up)));+ const float into = b2Dot(delta, across);+ if (into < 0.0f) delta = b2Sub(delta, b2MulSV(into, across));+ }+ return delta;+}++/** Collide and slide from `pos` towards `target`, leaving the last contacts in the plane list. */+b2Vec2 solveMove(const MoverShape& shape, b2Vec2 pos, b2Vec2 target, b2Vec2 up, float floorCos) {+ const float tolerance = 0.001f;+ for (int iteration = 0; iteration < shape.slides; ++iteration) {+ g_moverPlaneCount = 0;+ b2Capsule mover = capsuleAt(shape, pos);+ b2World_CollideMover(g_ctx.worldId, &mover, shape.filter, moverPlaneCallback, nullptr);+ if (g_moverFlags & MOVER_BLOCK_STEEP) target = b2Add(pos, withoutClimbing(b2Sub(target, pos), up, floorCos));+ b2PlaneSolverResult result = b2SolvePlanes(b2Sub(target, pos), g_moverPlanes, g_moverPlaneCount);+ pos = b2Add(pos, result.translation);+ if (b2LengthSquared(result.translation) < tolerance * tolerance) break;+ }+ return pos;+}++struct StepResult { bool stepped; b2Vec2 pos; b2Vec2 normal; uint32_t floor; };++/** Over a ledge no higher than `height`: up, across what the wall took from the move, and down onto floor. Refused for anything short of that. */+StepResult stepOver(const MoverShape& shape, b2Vec2 pos, b2Vec2 left, b2Vec2 up, float floorCos, float height) {+ StepResult out{false, pos, {0.0f, 0.0f}, 0xFFFFFFFF};+ b2Vec2 points[2];+ g_headroom = 1.0f;+ b2ShapeProxy proxy = proxyAt(shape, pos, points);+ b2World_CastShape(g_ctx.worldId, &proxy, b2MulSV(height, up), shape.filter, headroomCastCallback, nullptr);+ const float rise = height * g_headroom;+ if (rise <= 0.001f) return out;++ const b2Vec2 raised = b2Add(pos, b2MulSV(rise, up));+ const b2Vec2 across = solveMove(shape, raised, b2Add(raised, left), up, floorCos);+ const float leftLength = b2Length(left);+ if (b2Dot(b2Sub(across, raised), left) <= 0.25f * leftLength * leftLength) return out;++ // A foot only just over the edge lands on the corner, whose normal leans: anything that holds it up from below will do.+ g_snapClosest = 1.0f;+ g_snapHit = false;+ g_snapFloorCos = 0.01f;+ proxy = proxyAt(shape, across, points);+ const b2Vec2 down = b2MulSV(-rise, up);+ b2World_CastShape(g_ctx.worldId, &proxy, down, shape.filter, snapCastCallback, nullptr);+ g_snapFloorCos = floorCos;+ if (!g_snapHit) return out;+ out.stepped = true;+ out.pos = b2Add(across, b2MulSV(g_snapClosest, down));+ out.normal = up;+ out.floor = g_snapEntity;+ return out;+}++} // namespace+extern "C" {EMSCRIPTEN_KEEPALIVE@@ -219,52 +393,49 @@ 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).+// Move a capsule character one step, in meters. `carryX/Y` moves it with what it stands on, apart from its own velocity.+// Writes [dx, dy, velX, velY, onFloor, onWall, onCeiling, floorNx, floorNy, floorEntityBits, hitCount, (entityBits, nx, ny) * 4]+// and returns 1, or 0 if the world is gone.EMSCRIPTEN_KEEPALIVEint 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,- float skinWidth, int maxSlides, float snapLength, int slideOnCeiling) {+ float skinWidth, int maxSlides, float snapLength, int slideOnCeiling,+ float carryX, float carryY, uint32_t flags, float stepHeight) {if (!b2World_IsValid(g_ctx.worldId)) return 0;g_moverSelfEntity = selfEntity;+ g_moverFlags = flags;+ g_moverVelocity = {velX, velY};+ g_moverDt = dt;+ g_moverHitCount = 0;b2Vec2 pos = {px, py};b2Vec2 up = {upX, upY};- b2Vec2 target = {px + velX * dt, py + velY * dt};+ b2Vec2 start = pos;+ b2Vec2 target = {px + (velX + carryX) * dt, py + (velY + carryY) * dt};b2QueryFilter filter = b2DefaultQueryFilter();filter.maskBits = static_cast<uint64_t>(maskBits);// skinWidth keeps the capsule a small margin off surfaces (less jitter, no// visual overlap) — a slightly larger collision radius does exactly that.- float moverRadius = radius + (skinWidth > 0.0f ? skinWidth : 0.0f);- int slides = maxSlides > 0 ? maxSlides : 1;+ MoverShape shape{{c1x, c1y}, {c2x, c2y}, radius + (skinWidth > 0.0f ? skinWidth : 0.0f), filter, maxSlides > 0 ? maxSlides : 1};- const float tolerance = 0.001f;- for (int iteration = 0; iteration < slides; ++iteration) {- g_moverPlaneCount = 0;- b2Capsule mover;- mover.center1 = {pos.x + c1x, pos.y + c1y};- mover.center2 = {pos.x + c2x, pos.y + c2y};- mover.radius = moverRadius;- 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;- }+ pos = solveMove(shape, pos, target, up, floorCos);b2Vec2 vel = {velX, velY};+ // Clipped as it is, the speed walked into a steep slope turns into climbing it on the next move.+ if (flags & MOVER_BLOCK_STEEP) vel = withoutClimbing(vel, up, floorCos);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;+ uint32_t floorEntity = 0xFFFFFFFF;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; }+ if (d >= floorCos) { onFloor = true; fnx = n.x; fny = n.y; floorEntity = g_moverPlaneEntity[i]; }else if (d <= -floorCos) { onCeiling = true; }else { onWall = true; }}@@ -276,6 +447,35 @@ int physics_moveCharacter(float px, float py, float c1x, float c1y, float c2x, fif (vUp > 0.0f) { newVel.x -= vUp * upX; newVel.y -= vUp * upY; }}+ g_snapUp = up;+ g_snapFloorCos = floorCos;++ // A ledge low enough to step over stops a walking character only for this contact: its own walking+ // goes on, and neither a jump nor a fall steps up onto anything.+ if (stepHeight > 0.0f && onWall && (flags & MOVER_WAS_ON_FLOOR) != 0 && b2Dot(vel, up) <= 0.01f) {+ const b2Vec2 wanted = b2Sub(target, start);+ const b2Vec2 along = b2Sub(wanted, b2MulSV(b2Dot(wanted, up), up));+ const float length = b2Length(along);+ if (length > 0.0001f) {+ const b2Vec2 direction = b2MulSV(1.0f / length, along);+ const float remaining = length - b2Dot(b2Sub(pos, start), direction);+ if (remaining > 0.0001f) {+ const StepResult step = stepOver(shape, pos, b2MulSV(remaining, direction), up, floorCos, stepHeight);+ if (step.stepped) {+ pos = step.pos;+ onFloor = true;+ onWall = false;+ fnx = step.normal.x;+ fny = step.normal.y;+ floorEntity = step.floor;+ newVel = vel;+ const float vn = b2Dot(newVel, step.normal);+ if (vn < 0.0f) newVel = b2Sub(newVel, b2MulSV(vn, step.normal));+ }+ }+ }+ }+// Floor snap: when not rising and not already grounded, probe down up to// snapLength and stick to a floor within reach, so the character stays glued to// descending stairs/slopes instead of launching off each ledge.@@ -284,10 +484,8 @@ int physics_moveCharacter(float px, float py, float c1x, float c1y, float c2x, fif (vUp <= 0.01f) {g_snapClosest = 1.0f;g_snapHit = false;- g_snapUp = up;- g_snapFloorCos = floorCos;- b2Vec2 pts[2] = { {pos.x + c1x, pos.y + c1y}, {pos.x + c2x, pos.y + c2y} };- b2ShapeProxy proxy = b2MakeProxy(pts, 2, moverRadius);+ b2Vec2 pts[2];+ b2ShapeProxy proxy = proxyAt(shape, pos, pts);b2Vec2 down = {-upX * snapLength, -upY * snapLength};b2World_CastShape(g_ctx.worldId, &proxy, down, filter, snapCastCallback, nullptr);if (g_snapHit) {@@ -295,6 +493,7 @@ int physics_moveCharacter(float px, float py, float c1x, float c1y, float c2x, fonFloor = true;fnx = g_snapNormal.x;fny = g_snapNormal.y;+ floorEntity = g_snapEntity;float vn = newVel.x * g_snapNormal.x + newVel.y * g_snapNormal.y;if (vn < 0.0f) { newVel.x -= vn * g_snapNormal.x; newVel.y -= vn * g_snapNormal.y; }}@@ -310,6 +509,13 @@ int physics_moveCharacter(float px, float py, float c1x, float c1y, float c2x, fg_moverBuffer[6] = onCeiling ? 1.0f : 0.0f;g_moverBuffer[7] = fnx;g_moverBuffer[8] = fny;+ std::memcpy(&g_moverBuffer[9], &floorEntity, sizeof(uint32_t));+ g_moverBuffer[10] = static_cast<float>(g_moverHitCount);+ for (int i = 0; i < g_moverHitCount; ++i) {+ std::memcpy(&g_moverBuffer[11 + i * 3], &g_moverHitEntity[i], sizeof(uint32_t));+ g_moverBuffer[12 + i * 3] = g_moverHitNormal[i].x;+ g_moverBuffer[13 + i * 3] = g_moverHitNormal[i].y;+ }return 1;}diff --git a/src/esengine/bindings/modules/physics/PhysicsReadback.cpp b/src/esengine/bindings/modules/physics/PhysicsReadback.cppindex 892d3d1fb..99ea4a017 100644--- a/src/esengine/bindings/modules/physics/PhysicsReadback.cpp+++ b/src/esengine/bindings/modules/physics/PhysicsReadback.cpp@@ -72,10 +72,10 @@ EMSCRIPTEN_KEEPALIVE size_t physics_shapeCastBytes() {return floatBytes(g_shapeCastBuffer);}-// The character mover writes a fixed record (position delta, ground normal, flags),+// The character mover writes a fixed record (position delta, ground normal, flags, what it stands on and hit),// so its whole extent is always live — see physics_moveCharacter.EMSCRIPTEN_KEEPALIVE size_t physics_moveCharacterBytes() {- return 9 * sizeof(float);+ return (11 + 4 * 3) * sizeof(float);}} // extern "C"diff --git a/templates/2d-platformer/assets/scenes/main.esscene b/templates/2d-platformer/assets/scenes/main.essceneindex 85b022de4..845e27926 100644--- a/templates/2d-platformer/assets/scenes/main.esscene+++ b/templates/2d-platformer/assets/scenes/main.esscene@@ -439,10 +439,6 @@"layer": 1}},- {- "type": "Player",- "data": {}- },{"type": "RigidBody2D","data": {@@ -465,6 +461,13 @@"data": {"maskBits": 65533}+ },+ {+ "type": "PlatformerController2D",+ "data": {+ "moveSpeed": 320,+ "jumpSpeed": 640+ }}],"visible": truediff --git a/templates/2d-platformer/src/components.ts b/templates/2d-platformer/src/components.tsindex 8724fd70b..b2e6d0be5 100644--- a/templates/2d-platformer/src/components.ts+++ b/templates/2d-platformer/src/components.ts@@ -1,10 +1,5 @@import { defineComponent } from 'esengine';-export const Player = defineComponent('Player', {- speed: 320,- jumpForce: 640,-});-export const Coin = defineComponent('Coin', {baseY: 0,bobTimer: 0,diff --git a/templates/2d-platformer/src/main.ts b/templates/2d-platformer/src/main.tsindex 6ddca396f..de15aec96 100644--- a/templates/2d-platformer/src/main.ts+++ b/templates/2d-platformer/src/main.ts@@ -1,11 +1,9 @@import { addSystemToSchedule, Schedule } from 'esengine';import './components';-import { playerSystem } from './systems/player';import { coinBobSystem, coinPickupSystem } from './systems/coin';import { scoreSystem } from './systems/score';-addSystemToSchedule(Schedule.FixedPreUpdate, playerSystem);addSystemToSchedule(Schedule.Update, coinPickupSystem);addSystemToSchedule(Schedule.Update, coinBobSystem);addSystemToSchedule(Schedule.Update, scoreSystem);diff --git a/templates/2d-platformer/src/systems/player.ts b/templates/2d-platformer/src/systems/player.tsdeleted file mode 100644index 80919568a..000000000--- a/templates/2d-platformer/src/systems/player.ts+++ /dev/null@@ -1,27 +0,0 @@-import {- defineSystem, Query, Mut, Res, Time, Input,- CharacterController2D,-} from 'esengine';-import { Player } from '../components';--const GRAVITY = -1600;--export const playerSystem = defineSystem(- [Query(Mut(CharacterController2D), Player), Res(Time), Res(Input)],- (players, time, input) => {- for (const [_entity, cc, player] of players) {- let moveX = 0;- if (input.isKeyDown('ArrowLeft') || input.isKeyDown('KeyA')) moveX -= 1;- if (input.isKeyDown('ArrowRight') || input.isKeyDown('KeyD')) moveX += 1;- cc.velocity.x = moveX * player.speed;-- cc.velocity.y += GRAVITY * time.fixedDelta;-- const jump = input.isKeyPressed('Space')- || input.isKeyPressed('ArrowUp')- || input.isKeyPressed('KeyW');- if (cc.isOnFloor && jump) cc.velocity.y = player.jumpForce;- }- },- { name: 'PlayerSystem' }-);diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjsindex f51c65a4f..ef886c40e 100644--- a/tools/check-gizmo-coverage.mjs+++ b/tools/check-gizmo-coverage.mjs@@ -197,6 +197,7 @@ const DISPOSITION = {// and a shape drawn for it would claim a place it does not occupy.'ParticleEmitter.collisionMaxDistance': ['no-place', 'query culling threshold relative to the nearest active camera, not an emitter extent'],'CharacterController2D.skinWidth': ['no-place', 'a contact skin held off the collider; drawn, it is that outline\'s own line width'],+ 'CharacterController2D.stepHeight': ['no-place', 'the highest ledge it walks up: a limit on motion, not a volume'],'CharacterController3D.stepHeight': ['no-place', 'the tallest step it will climb — a limit on motion, not a volume'],'NavVolume.cellSize': ['no-place', 'the voxel the box is diced into; the box is what has a place'],'NavVolume.cellHeight': ['no-place', 'the voxel the box is diced into; the box is what has a place'],diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjsindex 4eea2d328..47895023f 100644--- a/tools/goldenProjects.mjs+++ b/tools/goldenProjects.mjs@@ -1213,7 +1213,7 @@ export const CAPABILITIES = [*/export const EVIDENCE = {physics: /\b(RigidBody2D|BoxCollider2D|CircleCollider2D|CapsuleCollider2D|physics2dPlugin|CharacterController2D)\b/,- input: /\b(Input|defineInputMap|isKeyDown|InputState)\b/,+ input: /\b(Input|defineInputMap|isKeyDown|InputState|PlatformerController2D)\b/,animation: /\b(SpriteAnimator|Animator|spriteAnim|Flipbook|TimelinePlayer|AnimClip)\b/,ecs: /\b(defineComponent|defineSystem)\b/,// The component that RUNS one. A `.esgraph` on disk that no scenediff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex a12dcd420..a3b4ac4f1 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4220,6 +4220,8 @@ export const NOTED = {{"note": "A skinned mesh is not culled for where its entity stands."},"feat(rig2d): a 2D character can be rigged with no other program, with IK and bone constraints":{"note": "A 2D character can be rigged in the editor, with no other program."},+ "feat(physics): a side-on character runs, jumps and forgives, on a mover that handles slopes, ledges and platforms":+ {"note": "A side-on character comes ready to run and jump."},"fix(assets): one hot load at a time per asset, so two rescans cannot lose a texture":{"note": "A texture stays on a scene that rescans as it is placed."},"feat(rig): the 2D rig editor, from an image to a character in the scene":