Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(gameplay): the animator hears what the character did, not what the player asked

esenginebf1e2760fbb7
diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
index a9a0b4257..157405c58 100644
--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx
+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
@@ -158,6 +158,40 @@ if (input.justPressed('jump') && c.isOnFloor) c.velocity.y = 500;
`0` walks into everything as if it were a wall.
</Aside>
+## Third person
+
+`ThirdPersonController` and `ThirdPersonCamera` are the gameplay layer above a
+character: input becomes a request, the character controller answers it, and the
+answer is what the animator hears.
+
+```typescript
+// Nothing to write. Both are components a scene declares.
+player.add(ThirdPersonController, { moveSpeed: 320, jumpSpeed: 520 });
+rig.add(ThirdPersonCamera, { target: player, distance: 420 });
+```
+
+The stick is read in the camera's GROUND plane, so an eye angled steeply down
+still walks the character across the floor. Pitch never reaches the character.
+
+| Field | What it does |
+|---|---|
+| `moveSpeed` | Top speed on the ground, world units/second. |
+| `acceleration` / `deceleration` | How fast it reaches that speed, and sheds it. |
+| `rotationSpeed` | How fast it turns to face where it went, degrees/second. |
+| `jumpSpeed` | Upward speed a jump starts with. `0` cannot jump. |
+| `airControl` | How much of `acceleration` applies off the ground, 0..1. |
+| `camera` | Whose forward the stick is read against. |
+
+<Aside>
+ The animator is told the speed the character REACHED, not the speed it asked
+ for. A character shoving a wall has a full stick and no motion, and it must not
+ be running on the spot; the same reading is what makes a slope it cannot climb
+ look like the stop it is.
+
+ The camera sweeps the physics world between the pivot and the eye, pulling in
+ when something solid stands between. It moves nothing but itself.
+</Aside>
+
## Joints
A door, a rope bridge, a lift, a ragdoll: none of them are one body and a shape.
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
index 6e1d7c8f9..2deef4006 100644
--- a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
@@ -142,6 +142,36 @@ if (input.justPressed('jump') && c.isOnFloor) c.velocity.y = 500;
更重的要给更多,而 `0` 会让它把所有东西都当成墙。
</Aside>
+## 第三人称
+
+`ThirdPersonController` 与 `ThirdPersonCamera` 是角色之上的 gameplay 层:输入
+变成一个请求,角色控制器给出答复,而动画听到的是这个答复。
+
+```typescript
+// 不需要写脚本,两者都是场景声明的组件。
+player.add(ThirdPersonController, { moveSpeed: 320, jumpSpeed: 520 });
+rig.add(ThirdPersonCamera, { target: player, distance: 420 });
+```
+
+摇杆是在相机的**地面**平面里读的,所以镜头再怎么俯视,角色仍然沿地面走。俯仰
+永远不会传到角色身上。
+
+| 字段 | 作用 |
+|---|---|
+| `moveSpeed` | 地面上的最高速度,世界单位/秒。 |
+| `acceleration` / `deceleration` | 加速到该速度的快慢,以及减速的快慢。 |
+| `rotationSpeed` | 转向「实际去过的方向」的角速度,度/秒。 |
+| `jumpSpeed` | 起跳的初始向上速度。`0` 表示不能跳。 |
+| `airControl` | 离地时 `acceleration` 生效的比例,0..1。 |
+| `camera` | 摇杆以谁的前方为准。 |
+
+<Aside>
+ 告诉动画的是角色**实际达到**的速度,而不是它请求的速度。顶着墙的角色摇杆推满
+ 却没有位移,它不该在原地跑步;爬不上去的斜坡也靠同一个读数表现为「停住」。
+
+ 相机会在支点与眼睛之间扫掠物理世界,有实体挡住时把自己拉近。它只移动自己。
+</Aside>
+
## 关节
门、绳桥、升降台、布娃娃:它们都不是「一个刚体加一个形状」,
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 3d1351182..7212ca397 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 113,
"beta": 91,
- "experimental": 1701,
+ "experimental": 1722,
"deprecated": 3
},
- "total": 1905,
+ "total": 1926,
"subsystems": [
{
"id": "ecs",
@@ -248,6 +248,18 @@
"Video"
]
},
+ {
+ "id": "gameplay",
+ "title": "Gameplay — third-person character and camera",
+ "titleZh": "Gameplay —— 第三人称角色与相机",
+ "tier": "experimental",
+ "why": "the newest layer in the engine, and the one a game shapes hardest: what a character owes its animator settled first, everything above it has not",
+ "whyZh": "引擎里最新的一层,也是最被具体游戏塑形的一层:角色欠动画什么已经定了,它之上的还没有",
+ "entry": [
+ "ThirdPersonController",
+ "ThirdPersonCamera"
+ ]
+ },
{
"id": "ai",
"title": "AI — navigation, FSM, behaviour trees",
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index ebfea6dff..60ec26fb5 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -115,6 +115,8 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
MeshCollider3D: { category: 'physics', summary: 'Collides against an imported mesh\u2019s own triangles — terrain, stairs, a room. Always static, and one-sided.', doc: 'gameplay/physics-3d', anchor: 'colliding-against-imported-geometry', anchorZh: '用导入的几何做碰撞' },
ConvexCollider3D: { category: 'physics', summary: 'Collides against the convex hull of an imported mesh — the shape a solver can push, unlike a mesh collider.', doc: 'gameplay/physics-3d', anchor: 'colliding-against-imported-geometry', anchorZh: '用导入的几何做碰撞' },
CharacterController3D: { category: 'physics', summary: 'A kinematic 3D mover: swept against the world, climbs steps, stays glued to slopes, and reports the ground it is on.', doc: 'gameplay/physics-3d', anchor: 'characters', anchorZh: '角色' },
+ ThirdPersonController: { category: 'physics', summary: 'Turns input into a movement request for a CharacterController3D, and reports what the character actually did to its Animator.', doc: 'gameplay/physics-3d', anchor: 'third-person', anchorZh: '第三人称' },
+ ThirdPersonCamera: { category: 'physics', summary: 'An eye that orbits a target under pointer control and pulls in when something solid stands between.', doc: 'gameplay/physics-3d', anchor: 'third-person', anchorZh: '第三人称' },
PointJoint3D: { category: 'physics', summary: 'Holds two 3D bodies at a shared point, free to turn on all three axes — a chain link, a ragdoll limb.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },
HingeJoint3D: { category: 'physics', summary: 'One axis of rotation between two 3D bodies — a door or a driven wheel, with optional limits and a motor.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },
SliderJoint3D: { category: 'physics', summary: 'One axis of travel between two 3D bodies — a lift or a piston, with optional limits and a motor.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index e4577fe0a..0211055db 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -4080,6 +4080,172 @@
}
]
},
+ {
+ "name": "ThirdPersonCamera",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "target",
+ "type": "Entity",
+ "default": "none",
+ "doc": "The transform this camera orbits."
+ },
+ {
+ "key": "distance",
+ "type": "number",
+ "default": "420"
+ },
+ {
+ "key": "yaw",
+ "type": "number",
+ "default": "0"
+ },
+ {
+ "key": "pitch",
+ "type": "number",
+ "default": "15"
+ },
+ {
+ "key": "minPitch",
+ "type": "number",
+ "default": "-30"
+ },
+ {
+ "key": "maxPitch",
+ "type": "number",
+ "default": "70"
+ },
+ {
+ "key": "sensitivity",
+ "type": "number",
+ "default": "0.2"
+ },
+ {
+ "key": "followDamping",
+ "type": "number",
+ "default": "12",
+ "range": "≥ 0",
+ "advanced": true
+ },
+ {
+ "key": "targetOffset",
+ "type": "Vec3",
+ "default": "(0, 90, 0)"
+ },
+ {
+ "key": "obstruction",
+ "type": "boolean",
+ "default": "true"
+ },
+ {
+ "key": "obstructionRadius",
+ "type": "number",
+ "default": "15",
+ "range": "≥ 0",
+ "advanced": true
+ },
+ {
+ "key": "obstructionLayers",
+ "type": "number",
+ "default": "0",
+ "range": "0–15, step 1",
+ "advanced": true
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ],
+ "animatable": [
+ "target",
+ "distance",
+ "yaw",
+ "pitch",
+ "minPitch",
+ "maxPitch",
+ "sensitivity",
+ "followDamping",
+ "targetOffset.x",
+ "targetOffset.y",
+ "targetOffset.z",
+ "obstructionRadius",
+ "obstructionLayers"
+ ]
+ },
+ {
+ "name": "ThirdPersonController",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "moveSpeed",
+ "type": "number",
+ "default": "320"
+ },
+ {
+ "key": "acceleration",
+ "type": "number",
+ "default": "2400"
+ },
+ {
+ "key": "deceleration",
+ "type": "number",
+ "default": "3200"
+ },
+ {
+ "key": "rotationSpeed",
+ "type": "number",
+ "default": "720"
+ },
+ {
+ "key": "jumpSpeed",
+ "type": "number",
+ "default": "0",
+ "doc": "Upward speed a jump starts with. 0 = cannot jump.",
+ "range": "≥ 0"
+ },
+ {
+ "key": "airControl",
+ "type": "number",
+ "default": "0.3",
+ "range": "0–1, step 0.05",
+ "advanced": true
+ },
+ {
+ "key": "cameraRelative",
+ "type": "boolean",
+ "default": "true"
+ },
+ {
+ "key": "camera",
+ "type": "Entity",
+ "default": "none",
+ "doc": "Whose forward the stick is read against."
+ },
+ {
+ "key": "idleThreshold",
+ "type": "number",
+ "default": "8",
+ "range": "≥ 0, step 0.05",
+ "advanced": true
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ],
+ "animatable": [
+ "moveSpeed",
+ "acceleration",
+ "deceleration",
+ "rotationSpeed",
+ "jumpSpeed",
+ "airControl",
+ "camera",
+ "idleThreshold"
+ ]
+ },
{
"name": "Tilemap",
"source": "ts",
diff --git a/examples/third-person-3d/assets/models/locomotion.esanimator b/examples/third-person-3d/assets/models/locomotion.esanimator
new file mode 100644
index 000000000..32f2e42ab
--- /dev/null
+++ b/examples/third-person-3d/assets/models/locomotion.esanimator
@@ -0,0 +1,76 @@
+{
+ "parameters": [
+ {
+ "name": "speed",
+ "type": "float",
+ "default": 0
+ },
+ {
+ "name": "grounded",
+ "type": "bool",
+ "default": true
+ }
+ ],
+ "initialState": "Idle",
+ "states": [
+ {
+ "name": "Idle",
+ "motion": {
+ "kind": "timeline",
+ "clip": "skinned-fade_Flat.estimeline",
+ "loop": true
+ },
+ "transitions": [
+ {
+ "to": "Locomotion",
+ "conditions": [
+ {
+ "param": "speed",
+ "op": "gt",
+ "value": 8
+ }
+ ],
+ "duration": 0.25
+ }
+ ]
+ },
+ {
+ "name": "Locomotion",
+ "motion": {
+ "kind": "blend1d",
+ "parameter": "speed",
+ "thresholds": [
+ {
+ "value": 0,
+ "motion": {
+ "kind": "timeline",
+ "clip": "skinned-fade_Flat.estimeline",
+ "loop": true
+ }
+ },
+ {
+ "value": 200,
+ "motion": {
+ "kind": "timeline",
+ "clip": "skinned-fade_Bent.estimeline",
+ "loop": true
+ }
+ }
+ ]
+ },
+ "transitions": [
+ {
+ "to": "Idle",
+ "conditions": [
+ {
+ "param": "speed",
+ "op": "lt",
+ "value": 8
+ }
+ ],
+ "duration": 0.25
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/examples/third-person-3d/assets/models/skinned-fade.esmesh b/examples/third-person-3d/assets/models/skinned-fade.esmesh
new file mode 100644
index 000000000..31f790bdf
Binary files /dev/null and b/examples/third-person-3d/assets/models/skinned-fade.esmesh differ
diff --git a/examples/third-person-3d/assets/models/skinned-fade.esmesh.meta b/examples/third-person-3d/assets/models/skinned-fade.esmesh.meta
new file mode 100644
index 000000000..90653d470
--- /dev/null
+++ b/examples/third-person-3d/assets/models/skinned-fade.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "e4adc279-27d8-4383-8b4d-c3b009b67a31",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/third-person-3d/assets/models/skinned-fade.gltf b/examples/third-person-3d/assets/models/skinned-fade.gltf
new file mode 100644
index 000000000..ea98f8bdf
--- /dev/null
+++ b/examples/third-person-3d/assets/models/skinned-fade.gltf
@@ -0,0 +1,223 @@
+{
+ "asset": {
+ "version": "2.0",
+ "generator": "estella crossfade fixture"
+ },
+ "buffers": [
+ {
+ "byteLength": 370,
+ "uri": "data:application/octet-stream;base64,AAAAAAAAoMEAAAAAAAAAAAAAoEEAAAAAAABwQgAAoMEAAAAAAABwQgAAoEEAAAAAAADwQgAAoMEAAAAAAADwQgAAoEEAAAAAAAACAAEAAQACAAMAAgAEAAMAAwAEAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAAAAAAIA/AACAPwAAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAAAAAAAAgD8AAAAAAABwwgAAAAAAAAAAAACAPw=="
+ },
+ {
+ "byteLength": 72,
+ "uri": "data:application/octet-stream;base64,AAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAA8wQ1P/MENT8AAAAAAAAAAPMENT/zBDU/"
+ }
+ ],
+ "bufferViews": [
+ {
+ "buffer": 0,
+ "byteOffset": 0,
+ "byteLength": 72
+ },
+ {
+ "buffer": 0,
+ "byteOffset": 72,
+ "byteLength": 24
+ },
+ {
+ "buffer": 0,
+ "byteOffset": 98,
+ "byteLength": 48
+ },
+ {
+ "buffer": 0,
+ "byteOffset": 146,
+ "byteLength": 96
+ },
+ {
+ "buffer": 0,
+ "byteOffset": 242,
+ "byteLength": 128
+ },
+ {
+ "buffer": 1,
+ "byteOffset": 0,
+ "byteLength": 8
+ },
+ {
+ "buffer": 1,
+ "byteOffset": 8,
+ "byteLength": 32
+ },
+ {
+ "buffer": 1,
+ "byteOffset": 40,
+ "byteLength": 32
+ }
+ ],
+ "accessors": [
+ {
+ "bufferView": 0,
+ "componentType": 5126,
+ "count": 6,
+ "type": "VEC3",
+ "min": [
+ 0,
+ -20,
+ 0
+ ],
+ "max": [
+ 120,
+ 20,
+ 0
+ ]
+ },
+ {
+ "bufferView": 1,
+ "componentType": 5123,
+ "count": 12,
+ "type": "SCALAR"
+ },
+ {
+ "bufferView": 2,
+ "componentType": 5123,
+ "count": 6,
+ "type": "VEC4"
+ },
+ {
+ "bufferView": 3,
+ "componentType": 5126,
+ "count": 6,
+ "type": "VEC4"
+ },
+ {
+ "bufferView": 4,
+ "componentType": 5126,
+ "count": 2,
+ "type": "MAT4"
+ },
+ {
+ "bufferView": 5,
+ "componentType": 5126,
+ "count": 2,
+ "type": "SCALAR",
+ "min": [
+ 0.0
+ ],
+ "max": [
+ 1.0
+ ]
+ },
+ {
+ "bufferView": 6,
+ "componentType": 5126,
+ "count": 2,
+ "type": "VEC4"
+ },
+ {
+ "bufferView": 7,
+ "componentType": 5126,
+ "count": 2,
+ "type": "VEC4"
+ }
+ ],
+ "meshes": [
+ {
+ "name": "Arm",
+ "primitives": [
+ {
+ "attributes": {
+ "POSITION": 0,
+ "JOINTS_0": 2,
+ "WEIGHTS_0": 3
+ },
+ "indices": 1,
+ "mode": 4
+ }
+ ]
+ }
+ ],
+ "nodes": [
+ {
+ "name": "Rig",
+ "children": [
+ 1,
+ 2,
+ 3
+ ]
+ },
+ {
+ "name": "Bone0"
+ },
+ {
+ "name": "Bone1",
+ "translation": [
+ 60,
+ 0,
+ 0
+ ]
+ },
+ {
+ "name": "Body",
+ "mesh": 0,
+ "skin": 0
+ }
+ ],
+ "scenes": [
+ {
+ "nodes": [
+ 0
+ ]
+ }
+ ],
+ "scene": 0,
+ "skins": [
+ {
+ "joints": [
+ 1,
+ 2
+ ],
+ "inverseBindMatrices": 4
+ }
+ ],
+ "animations": [
+ {
+ "name": "Flat",
+ "samplers": [
+ {
+ "input": 5,
+ "output": 6,
+ "interpolation": "LINEAR"
+ }
+ ],
+ "channels": [
+ {
+ "sampler": 0,
+ "target": {
+ "node": 2,
+ "path": "rotation"
+ }
+ }
+ ]
+ },
+ {
+ "name": "Bent",
+ "samplers": [
+ {
+ "input": 5,
+ "output": 7,
+ "interpolation": "LINEAR"
+ }
+ ],
+ "channels": [
+ {
+ "sampler": 0,
+ "target": {
+ "node": 2,
+ "path": "rotation"
+ }
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/examples/third-person-3d/assets/models/skinned-fade.gltf.meta b/examples/third-person-3d/assets/models/skinned-fade.gltf.meta
new file mode 100644
index 000000000..14ba40008
--- /dev/null
+++ b/examples/third-person-3d/assets/models/skinned-fade.gltf.meta
@@ -0,0 +1,8 @@
+{
+ "uuid": "d63c357f-d90b-47f6-a61e-eb42f460f6eb",
+ "version": "2.0",
+ "type": "model",
+ "importer": {
+ "scale": 1
+ }
+}
diff --git a/examples/third-person-3d/assets/models/skinned-fade_Bent.estimeline b/examples/third-person-3d/assets/models/skinned-fade_Bent.estimeline
new file mode 100644
index 000000000..8888436fb
--- /dev/null
+++ b/examples/third-person-3d/assets/models/skinned-fade_Bent.estimeline
@@ -0,0 +1,92 @@
+{
+ "version": "1.2",
+ "type": "timeline",
+ "duration": 1,
+ "wrapMode": "once",
+ "tracks": [
+ {
+ "type": "property",
+ "name": "Bone1",
+ "childPath": "Bone1",
+ "component": "Transform",
+ "channels": [
+ {
+ "property": "rotation.x",
+ "keyframes": [
+ {
+ "time": 0,
+ "value": 0,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ },
+ {
+ "time": 1,
+ "value": 0,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ }
+ ]
+ },
+ {
+ "property": "rotation.y",
+ "keyframes": [
+ {
+ "time": 0,
+ "value": 0,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ },
+ {
+ "time": 1,
+ "value": 0,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ }
+ ]
+ },
+ {
+ "property": "rotation.z",
+ "keyframes": [
+ {
+ "time": 0,
+ "value": 0.7071067690849304,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ },
+ {
+ "time": 1,
+ "value": 0.7071067690849304,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ }
+ ]
+ },
+ {
+ "property": "rotation.w",
+ "keyframes": [
+ {
+ "time": 0,
+ "value": 0.7071067690849304,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ },
+ {
+ "time": 1,
+ "value": 0.7071067690849304,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+}
diff --git a/examples/third-person-3d/assets/models/skinned-fade_Bent.estimeline.meta b/examples/third-person-3d/assets/models/skinned-fade_Bent.estimeline.meta
new file mode 100644
index 000000000..2409e6b80
--- /dev/null
+++ b/examples/third-person-3d/assets/models/skinned-fade_Bent.estimeline.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "8fb5d824-25b2-4dbd-804d-524a47ae7fc8",
+ "version": "2.0",
+ "type": "animation",
+ "importer": {}
+}
diff --git a/examples/third-person-3d/assets/models/skinned-fade_Flat.estimeline b/examples/third-person-3d/assets/models/skinned-fade_Flat.estimeline
new file mode 100644
index 000000000..563dbabb2
--- /dev/null
+++ b/examples/third-person-3d/assets/models/skinned-fade_Flat.estimeline
@@ -0,0 +1,92 @@
+{
+ "version": "1.2",
+ "type": "timeline",
+ "duration": 1,
+ "wrapMode": "once",
+ "tracks": [
+ {
+ "type": "property",
+ "name": "Bone1",
+ "childPath": "Bone1",
+ "component": "Transform",
+ "channels": [
+ {
+ "property": "rotation.x",
+ "keyframes": [
+ {
+ "time": 0,
+ "value": 0,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ },
+ {
+ "time": 1,
+ "value": 0,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ }
+ ]
+ },
+ {
+ "property": "rotation.y",
+ "keyframes": [
+ {
+ "time": 0,
+ "value": 0,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ },
+ {
+ "time": 1,
+ "value": 0,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ }
+ ]
+ },
+ {
+ "property": "rotation.z",
+ "keyframes": [
+ {
+ "time": 0,
+ "value": 0,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ },
+ {
+ "time": 1,
+ "value": 0,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ }
+ ]
+ },
+ {
+ "property": "rotation.w",
+ "keyframes": [
+ {
+ "time": 0,
+ "value": 1,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ },
+ {
+ "time": 1,
+ "value": 1,
+ "inTangent": 0,
+ "outTangent": 0,
+ "interpolation": "linear"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+}
diff --git a/examples/third-person-3d/assets/models/skinned-fade_Flat.estimeline.meta b/examples/third-person-3d/assets/models/skinned-fade_Flat.estimeline.meta
new file mode 100644
index 000000000..108bc0efd
--- /dev/null
+++ b/examples/third-person-3d/assets/models/skinned-fade_Flat.estimeline.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "3db4d297-f7f4-426a-8c0f-cfe86a022120",
+ "version": "2.0",
+ "type": "animation",
+ "importer": {}
+}
diff --git a/examples/third-person-3d/assets/scenes/main.esscene b/examples/third-person-3d/assets/scenes/main.esscene
new file mode 100644
index 000000000..478a5b83b
--- /dev/null
+++ b/examples/third-person-3d/assets/scenes/main.esscene
@@ -0,0 +1,475 @@
+{
+ "version": 4,
+ "name": "ThirdPerson3D",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 200,
+ "z": 500
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 0,
+ "fov": 55,
+ "nearPlane": 10,
+ "farPlane": 4000,
+ "isActive": true,
+ "priority": 0
+ }
+ },
+ {
+ "type": "ThirdPersonCamera",
+ "data": {
+ "target": 5,
+ "distance": 420,
+ "pitch": 18
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Ground",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": -20,
+ "z": 0
+ },
+ "scale": {
+ "x": 16.0,
+ "y": 0.4,
+ "z": 16.0
+ }
+ }
+ },
+ {
+ "type": "RigidBody3D",
+ "data": {
+ "bodyType": 0
+ }
+ },
+ {
+ "type": "BoxCollider3D",
+ "data": {
+ "halfExtents": {
+ "x": 800.0,
+ "y": 20.0,
+ "z": 800.0
+ },
+ "friction": 0.6
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "color": {
+ "r": 0.3,
+ "g": 0.34,
+ "b": 0.3,
+ "a": 1
+ }
+ }
+ }
+ ]
+ },
+ {
+ "id": 2,
+ "name": "Wall",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 420,
+ "y": 120,
+ "z": 0
+ },
+ "scale": {
+ "x": 0.4,
+ "y": 2.4,
+ "z": 8.0
+ }
+ }
+ },
+ {
+ "type": "RigidBody3D",
+ "data": {
+ "bodyType": 0
+ }
+ },
+ {
+ "type": "BoxCollider3D",
+ "data": {
+ "halfExtents": {
+ "x": 20.0,
+ "y": 120.0,
+ "z": 400.0
+ },
+ "friction": 0.6
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "color": {
+ "r": 0.45,
+ "g": 0.3,
+ "b": 0.28,
+ "a": 1
+ }
+ }
+ }
+ ]
+ },
+ {
+ "id": 3,
+ "name": "Step",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": -360,
+ "y": 25,
+ "z": 0
+ },
+ "scale": {
+ "x": 3.0,
+ "y": 0.5,
+ "z": 4.0
+ }
+ }
+ },
+ {
+ "type": "RigidBody3D",
+ "data": {
+ "bodyType": 0
+ }
+ },
+ {
+ "type": "BoxCollider3D",
+ "data": {
+ "halfExtents": {
+ "x": 150.0,
+ "y": 25.0,
+ "z": 200.0
+ },
+ "friction": 0.6
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "color": {
+ "r": 0.36,
+ "g": 0.32,
+ "b": 0.28,
+ "a": 1
+ }
+ }
+ }
+ ]
+ },
+ {
+ "id": 4,
+ "name": "Ramp",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 40,
+ "z": -520
+ },
+ "rotation": {
+ "w": 0.9945218953682733,
+ "x": 0.10452846326765347,
+ "y": 0,
+ "z": 0
+ },
+ "scale": {
+ "x": 4.0,
+ "y": 0.3,
+ "z": 7.0
+ }
+ }
+ },
+ {
+ "type": "RigidBody3D",
+ "data": {
+ "bodyType": 0
+ }
+ },
+ {
+ "type": "BoxCollider3D",
+ "data": {
+ "halfExtents": {
+ "x": 200.0,
+ "y": 15.0,
+ "z": 350.0
+ },
+ "friction": 0.6
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "color": {
+ "r": 0.33,
+ "g": 0.36,
+ "b": 0.4,
+ "a": 1
+ }
+ }
+ }
+ ]
+ },
+ {
+ "id": 5,
+ "name": "Player",
+ "parent": null,
+ "children": [
+ 6,
+ 7,
+ 8
+ ],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 80,
+ "z": 120
+ }
+ }
+ },
+ {
+ "type": "CharacterController3D",
+ "data": {
+ "radius": 30,
+ "halfHeight": 30,
+ "stepHeight": 40,
+ "snapDown": 50
+ }
+ },
+ {
+ "type": "ThirdPersonController",
+ "data": {
+ "camera": 0,
+ "moveSpeed": 320,
+ "jumpSpeed": 520,
+ "idleThreshold": 8
+ }
+ },
+ {
+ "type": "Animator",
+ "data": {
+ "controller": "assets/models/locomotion.esanimator",
+ "currentState": "",
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 6,
+ "name": "Bone0",
+ "parent": 5,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "id": 7,
+ "name": "Bone1",
+ "parent": 5,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 60,
+ "y": 0,
+ "z": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "id": 8,
+ "name": "Body",
+ "parent": 5,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "assets/models/skinned-fade.esmesh",
+ "lit": true,
+ "opaque": true,
+ "color": {
+ "r": 0.35,
+ "g": 0.75,
+ "b": 0.45,
+ "a": 1
+ }
+ }
+ },
+ {
+ "type": "MeshSkin",
+ "data": {
+ "joints": [
+ 6,
+ 7
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": 9,
+ "name": "Sun",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ },
+ "rotation": {
+ "w": 0.83394695,
+ "x": -0.52086316,
+ "y": 0.18230211,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Light",
+ "data": {
+ "type": 1,
+ "intensity": 1.05,
+ "enabled": true,
+ "color": {
+ "r": 1,
+ "g": 0.96,
+ "b": 0.9,
+ "a": 1
+ }
+ }
+ }
+ ]
+ },
+ {
+ "id": 10,
+ "name": "Sky",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Light",
+ "data": {
+ "type": 2,
+ "intensity": 0.42,
+ "enabled": true,
+ "color": {
+ "r": 0.55,
+ "g": 0.66,
+ "b": 0.85,
+ "a": 1
+ }
+ }
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/examples/third-person-3d/project.esproject b/examples/third-person-3d/project.esproject
new file mode 100644
index 000000000..126f2ac2e
--- /dev/null
+++ b/examples/third-person-3d/project.esproject
@@ -0,0 +1,13 @@
+{
+ "formatVersion": "1",
+ "name": "Third Person 3D",
+ "description": "A skinned character walks, turns and jumps under a camera that stays out of walls \u2014 declared by components, not driven by a script.",
+ "tag": "3D",
+ "version": "0.1.0",
+ "defaultScene": "assets/scenes/main.esscene",
+ "designResolution": {
+ "width": 960,
+ "height": 640
+ },
+ "spineVersion": "none"
+}
\ No newline at end of file
diff --git a/examples/third-person-3d/src/main.ts b/examples/third-person-3d/src/main.ts
new file mode 100644
index 000000000..d29b54595
--- /dev/null
+++ b/examples/third-person-3d/src/main.ts
@@ -0,0 +1,4 @@
+// No gameplay script: ThirdPersonController and ThirdPersonCamera are components
+// the scene declares, and the engine's systems run them. Reading WASD, moving
+// the character and following it with the camera is what those components are.
+export {};
diff --git a/examples/third-person-3d/tsconfig.json b/examples/third-person-3d/tsconfig.json
new file mode 100644
index 000000000..1f11ff310
--- /dev/null
+++ b/examples/third-person-3d/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": false,
+ "outDir": "./dist",
+ "rootDir": ".",
+ "paths": {
+ "esengine": ["./.esengine/sdk/index.d.ts"],
+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"]
+ }
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules"]
+}
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 1f0c640ed..f34b3a783 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: 113 public · 84 beta · 1537 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1558 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -3601,6 +3601,15 @@ index: number
mapping: string
```
+## GameplayPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: () => void
+name: string
+static new (): GameplayPlugin
+static prototype: GameplayPlugin
+```
+
## GearBinding — interface @experimental
```
component: string
@@ -4878,6 +4887,12 @@ ComponentDef<MotorJoint2DData>
(button: number) => Binding
```
+## MoveBasis — interface @experimental
+```
+forward: Vec3
+right: Vec3
+```
+
## Mut — function @public
```
<T extends AnyComponentDef>(component: T): MutWrapper<T>
@@ -8094,6 +8109,16 @@ number
"timeline"
```
+## TPC_GROUNDED — const @experimental
+```
+"grounded"
+```
+
+## TPC_SPEED — const @experimental
+```
+"speed"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -8394,6 +8419,47 @@ label: number
title: number
```
+## ThirdPersonCamera — const @experimental
+```
+ComponentDef<ThirdPersonCameraData>
+```
+
+## ThirdPersonCameraData — interface @experimental
+```
+distance: number
+enabled: boolean
+followDamping: number
+maxPitch: number
+minPitch: number
+obstruction: boolean
+obstructionLayers: number
+obstructionRadius: number
+pitch: number
+sensitivity: number
+target: number
+targetOffset: Vec3
+yaw: number
+```
+
+## ThirdPersonController — const @experimental
+```
+ComponentDef<ThirdPersonControllerData>
+```
+
+## ThirdPersonControllerData — interface @experimental
+```
+acceleration: number
+airControl: number
+camera: number
+cameraRelative: boolean
+deceleration: number
+enabled: boolean
+idleThreshold: number
+jumpSpeed: number
+moveSpeed: number
+rotationSpeed: number
+```
+
## TileCollisionPiece — interface @experimental
```
center: Vec2
@@ -9532,6 +9598,11 @@ y: number
(id: string) => Binding
```
+## WORLD_BASIS — const @experimental
+```
+MoveBasis
+```
+
## WangIndex — interface @experimental
```
byKey: Map<number, number>
@@ -9945,6 +10016,11 @@ AnimationPlugin
(time: number, duration: number, mode: WrapMode): { time: number; stopped: boolean; }
```
+## approachVelocity — function @experimental
+```
+(current: { x: number; z: number; }, target: { x: number; z: number; }, acceleration: number, deceleration: number, dt: number): { x: number; z: number; }
+```
+
## arrayDataSource — function @experimental
```
<T>(items: readonly T[]): ArrayDataSource<T>
@@ -10085,6 +10161,11 @@ BtPlugin
(camera: CameraFields, transform: CameraTransformFields, width: number, height: number, canvas: CanvasScale | null, result?: Float32Array): Float32Array
```
+## cameraGroundBasis — function @experimental
+```
+(yawDeg: number): { forward: Vec3; right: Vec3; }
+```
+
## canCaptureFramePixels — function @experimental
```
(module: ESEngineModule): boolean
@@ -10115,6 +10196,11 @@ BtPlugin
(): string[]
```
+## clampPitch — function @experimental
+```
+(pitch: number, min: number, max: number): number
+```
+
## clearAllCaches — function @experimental
```
(): void
@@ -10440,6 +10526,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## dampFactor — function @experimental
+```
+(damping: number, dt: number): number
+```
+
## debug — function @experimental
```
(category: string, message: string, data?: unknown): void
@@ -10520,6 +10611,11 @@ PluralSelector
<T>(sources: ReadonlySignal<unknown>[], compute: () => T): ReadonlySignal<T>
```
+## desiredDirection — function @experimental
+```
+(input: { x: number; y: number; }, basis: MoveBasis): Vec3
+```
+
## detectAnchor — function @experimental
```
(node: UINodeData): AnchorPreset | null
@@ -10785,6 +10881,11 @@ EventBindingPlugin
(rot: Quat, axis?: FacingAxis): Vec3
```
+## facingYaw — function @experimental
+```
+(direction: Vec3): number
+```
+
## fetchDecodePixels — function @experimental
```
(url: string): Promise<DecodedPixels>
@@ -10895,6 +10996,11 @@ FsmPlugin
(): boolean
```
+## gameplayPlugin — const @experimental
+```
+GameplayPlugin
+```
+
## gearBinding — function @experimental
```
(controller: string, component: string, property: string, pages: Record<string, GearValue>, tween?: GearTween): GearBinding
@@ -11550,6 +11656,11 @@ NavPlugin
(world: World, events: UIEventQueue, e: Entity): void
```
+## orbitOffset — function @experimental
+```
+(yawDeg: number, pitchDeg: number): Vec3
+```
+
## orientationPerm — function @experimental
```
(flags: TileFlags): Perm
@@ -12415,6 +12526,11 @@ ServicesPlugin
(shape: Collider2DShape): Vec2
```
+## shortestAngleDelta — function @experimental
+```
+(from: number, to: number): number
+```
+
## shutdownDrawAPI — function @experimental
```
(): void
@@ -12635,6 +12751,11 @@ TrailPlugin
(): number
```
+## turnToward — function @experimental
+```
+(from: number, to: number, degreesPerSecond: number, dt: number): number
+```
+
## uiHitTestWorld — function @experimental
```
(world: PickableWorld, ray: WorldRay): Entity | null
@@ -12840,3 +12961,13 @@ VideoPlugin
(f32: Float32Array, u32: Uint32Array, u8: Uint8Array, ptr: number, field: PtrFieldDesc, value: PtrFieldValue | unknown): void
```
+## yawOfQuaternion — function @experimental
+```
+(q: { w: number; y: number; }): number
+```
+
+## yawQuaternion — function @experimental
+```
+(yawDeg: number): { w: number; x: number; y: number; z: number; }
+```
+
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index d65fdbb07..2ac708538 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: 113 public · 89 beta · 1556 experimental · 3 deprecated
+Symbols: 113 public · 89 beta · 1577 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -3609,6 +3609,15 @@ index: number
mapping: string
```
+## GameplayPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: () => void
+name: string
+static new (): GameplayPlugin
+static prototype: GameplayPlugin
+```
+
## GearBinding — interface @experimental
```
component: string
@@ -4891,6 +4900,12 @@ ComponentDef<MotorJoint2DData>
(button: number) => Binding
```
+## MoveBasis — interface @experimental
+```
+forward: Vec3
+right: Vec3
+```
+
## Mut — function @public
```
<T extends AnyComponentDef>(component: T): MutWrapper<T>
@@ -8287,6 +8302,16 @@ number
"timeline"
```
+## TPC_GROUNDED — const @experimental
+```
+"grounded"
+```
+
+## TPC_SPEED — const @experimental
+```
+"speed"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -8587,6 +8612,47 @@ label: number
title: number
```
+## ThirdPersonCamera — const @experimental
+```
+ComponentDef<ThirdPersonCameraData>
+```
+
+## ThirdPersonCameraData — interface @experimental
+```
+distance: number
+enabled: boolean
+followDamping: number
+maxPitch: number
+minPitch: number
+obstruction: boolean
+obstructionLayers: number
+obstructionRadius: number
+pitch: number
+sensitivity: number
+target: number
+targetOffset: Vec3
+yaw: number
+```
+
+## ThirdPersonController — const @experimental
+```
+ComponentDef<ThirdPersonControllerData>
+```
+
+## ThirdPersonControllerData — interface @experimental
+```
+acceleration: number
+airControl: number
+camera: number
+cameraRelative: boolean
+deceleration: number
+enabled: boolean
+idleThreshold: number
+jumpSpeed: number
+moveSpeed: number
+rotationSpeed: number
+```
+
## TileCollisionPiece — interface @experimental
```
center: Vec2
@@ -9725,6 +9791,11 @@ y: number
(id: string) => Binding
```
+## WORLD_BASIS — const @experimental
+```
+MoveBasis
+```
+
## WangIndex — interface @experimental
```
byKey: Map<number, number>
@@ -10138,6 +10209,11 @@ AnimationPlugin
(time: number, duration: number, mode: WrapMode): { time: number; stopped: boolean; }
```
+## approachVelocity — function @experimental
+```
+(current: { x: number; z: number; }, target: { x: number; z: number; }, acceleration: number, deceleration: number, dt: number): { x: number; z: number; }
+```
+
## arrayDataSource — function @experimental
```
<T>(items: readonly T[]): ArrayDataSource<T>
@@ -10293,6 +10369,11 @@ BtPlugin
(camera: CameraFields, transform: CameraTransformFields, width: number, height: number, canvas: CanvasScale | null, result?: Float32Array): Float32Array
```
+## cameraGroundBasis — function @experimental
+```
+(yawDeg: number): { forward: Vec3; right: Vec3; }
+```
+
## canCaptureFramePixels — function @experimental
```
(module: ESEngineModule): boolean
@@ -10323,6 +10404,11 @@ BtPlugin
(): string[]
```
+## clampPitch — function @experimental
+```
+(pitch: number, min: number, max: number): number
+```
+
## clearAllCaches — function @experimental
```
(): void
@@ -10673,6 +10759,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## dampFactor — function @experimental
+```
+(damping: number, dt: number): number
+```
+
## debug — function @experimental
```
(category: string, message: string, data?: unknown): void
@@ -10753,6 +10844,11 @@ PluralSelector
<T>(sources: ReadonlySignal<unknown>[], compute: () => T): ReadonlySignal<T>
```
+## desiredDirection — function @experimental
+```
+(input: { x: number; y: number; }, basis: MoveBasis): Vec3
+```
+
## detectAnchor — function @experimental
```
(node: UINodeData): AnchorPreset | null
@@ -11018,6 +11114,11 @@ EventBindingPlugin
(rot: Quat, axis?: FacingAxis): Vec3
```
+## facingYaw — function @experimental
+```
+(direction: Vec3): number
+```
+
## fetchDecodePixels — function @experimental
```
(url: string): Promise<DecodedPixels>
@@ -11128,6 +11229,11 @@ FsmPlugin
(): boolean
```
+## gameplayPlugin — const @experimental
+```
+GameplayPlugin
+```
+
## gearBinding — function @experimental
```
(controller: string, component: string, property: string, pages: Record<string, GearValue>, tween?: GearTween): GearBinding
@@ -11793,6 +11899,11 @@ NavPlugin
(world: World, events: UIEventQueue, e: Entity): void
```
+## orbitOffset — function @experimental
+```
+(yawDeg: number, pitchDeg: number): Vec3
+```
+
## orientationPerm — function @experimental
```
(flags: TileFlags): Perm
@@ -12658,6 +12769,11 @@ ServicesPlugin
(shape: Collider2DShape): Vec2
```
+## shortestAngleDelta — function @experimental
+```
+(from: number, to: number): number
+```
+
## shutdownDrawAPI — function @experimental
```
(): void
@@ -12878,6 +12994,11 @@ TrailPlugin
(): number
```
+## turnToward — function @experimental
+```
+(from: number, to: number, degreesPerSecond: number, dt: number): number
+```
+
## uiHitTestWorld — function @experimental
```
(world: PickableWorld, ray: WorldRay): Entity | null
@@ -13083,3 +13204,13 @@ VideoPlugin
(f32: Float32Array, u32: Uint32Array, u8: Uint8Array, ptr: number, field: PtrFieldDesc, value: PtrFieldValue | unknown): void
```
+## yawOfQuaternion — function @experimental
+```
+(q: { w: number; y: number; }): number
+```
+
+## yawQuaternion — function @experimental
+```
+(yawDeg: number): { w: number; x: number; y: number; z: number; }
+```
+
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index be7828e34..e90e45166 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: 113 public · 86 beta · 1536 experimental · 3 deprecated
+Symbols: 113 public · 86 beta · 1557 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3596,6 +3596,15 @@ index: number
mapping: string
```
+## GameplayPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: () => void
+name: string
+static new (): GameplayPlugin
+static prototype: GameplayPlugin
+```
+
## GearBinding — interface @experimental
```
component: string
@@ -4873,6 +4882,12 @@ ComponentDef<MotorJoint2DData>
(button: number) => Binding
```
+## MoveBasis — interface @experimental
+```
+forward: Vec3
+right: Vec3
+```
+
## Mut — function @public
```
<T extends AnyComponentDef>(component: T): MutWrapper<T>
@@ -8089,6 +8104,16 @@ number
"timeline"
```
+## TPC_GROUNDED — const @experimental
+```
+"grounded"
+```
+
+## TPC_SPEED — const @experimental
+```
+"speed"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -8389,6 +8414,47 @@ label: number
title: number
```
+## ThirdPersonCamera — const @experimental
+```
+ComponentDef<ThirdPersonCameraData>
+```
+
+## ThirdPersonCameraData — interface @experimental
+```
+distance: number
+enabled: boolean
+followDamping: number
+maxPitch: number
+minPitch: number
+obstruction: boolean
+obstructionLayers: number
+obstructionRadius: number
+pitch: number
+sensitivity: number
+target: number
+targetOffset: Vec3
+yaw: number
+```
+
+## ThirdPersonController — const @experimental
+```
+ComponentDef<ThirdPersonControllerData>
+```
+
+## ThirdPersonControllerData — interface @experimental
+```
+acceleration: number
+airControl: number
+camera: number
+cameraRelative: boolean
+deceleration: number
+enabled: boolean
+idleThreshold: number
+jumpSpeed: number
+moveSpeed: number
+rotationSpeed: number
+```
+
## TileCollisionPiece — interface @experimental
```
center: Vec2
@@ -9527,6 +9593,11 @@ y: number
(id: string) => Binding
```
+## WORLD_BASIS — const @experimental
+```
+MoveBasis
+```
+
## WangIndex — interface @experimental
```
byKey: Map<number, number>
@@ -9940,6 +10011,11 @@ AnimationPlugin
(time: number, duration: number, mode: WrapMode): { time: number; stopped: boolean; }
```
+## approachVelocity — function @experimental
+```
+(current: { x: number; z: number; }, target: { x: number; z: number; }, acceleration: number, deceleration: number, dt: number): { x: number; z: number; }
+```
+
## arrayDataSource — function @experimental
```
<T>(items: readonly T[]): ArrayDataSource<T>
@@ -10080,6 +10156,11 @@ BtPlugin
(camera: CameraFields, transform: CameraTransformFields, width: number, height: number, canvas: CanvasScale | null, result?: Float32Array): Float32Array
```
+## cameraGroundBasis — function @experimental
+```
+(yawDeg: number): { forward: Vec3; right: Vec3; }
+```
+
## canCaptureFramePixels — function @experimental
```
(module: ESEngineModule): boolean
@@ -10110,6 +10191,11 @@ BtPlugin
(): string[]
```
+## clampPitch — function @experimental
+```
+(pitch: number, min: number, max: number): number
+```
+
## clearAllCaches — function @experimental
```
(): void
@@ -10435,6 +10521,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## dampFactor — function @experimental
+```
+(damping: number, dt: number): number
+```
+
## debug — function @experimental
```
(category: string, message: string, data?: unknown): void
@@ -10515,6 +10606,11 @@ PluralSelector
<T>(sources: ReadonlySignal<unknown>[], compute: () => T): ReadonlySignal<T>
```
+## desiredDirection — function @experimental
+```
+(input: { x: number; y: number; }, basis: MoveBasis): Vec3
+```
+
## detectAnchor — function @experimental
```
(node: UINodeData): AnchorPreset | null
@@ -10780,6 +10876,11 @@ EventBindingPlugin
(rot: Quat, axis?: FacingAxis): Vec3
```
+## facingYaw — function @experimental
+```
+(direction: Vec3): number
+```
+
## fetchDecodePixels — function @experimental
```
(url: string): Promise<DecodedPixels>
@@ -10890,6 +10991,11 @@ FsmPlugin
(): boolean
```
+## gameplayPlugin — const @experimental
+```
+GameplayPlugin
+```
+
## gearBinding — function @experimental
```
(controller: string, component: string, property: string, pages: Record<string, GearValue>, tween?: GearTween): GearBinding
@@ -11555,6 +11661,11 @@ NodePlatformAdapter
(world: World, events: UIEventQueue, e: Entity): void
```
+## orbitOffset — function @experimental
+```
+(yawDeg: number, pitchDeg: number): Vec3
+```
+
## orientationPerm — function @experimental
```
(flags: TileFlags): Perm
@@ -12420,6 +12531,11 @@ ServicesPlugin
(shape: Collider2DShape): Vec2
```
+## shortestAngleDelta — function @experimental
+```
+(from: number, to: number): number
+```
+
## shutdownDrawAPI — function @experimental
```
(): void
@@ -12640,6 +12756,11 @@ TrailPlugin
(): number
```
+## turnToward — function @experimental
+```
+(from: number, to: number, degreesPerSecond: number, dt: number): number
+```
+
## uiHitTestWorld — function @experimental
```
(world: PickableWorld, ray: WorldRay): Entity | null
@@ -12845,3 +12966,13 @@ VideoPlugin
(f32: Float32Array, u32: Uint32Array, u8: Uint8Array, ptr: number, field: PtrFieldDesc, value: PtrFieldValue | unknown): void
```
+## yawOfQuaternion — function @experimental
+```
+(q: { w: number; y: number; }): number
+```
+
+## yawQuaternion — function @experimental
+```
+(yawDeg: number): { w: number; x: number; y: number; z: number; }
+```
+
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 6906eb180..7ab43387f 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: 113 public · 84 beta · 1558 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1579 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3596,6 +3596,15 @@ index: number
mapping: string
```
+## GameplayPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: () => void
+name: string
+static new (): GameplayPlugin
+static prototype: GameplayPlugin
+```
+
## GearBinding — interface @experimental
```
component: string
@@ -5119,6 +5128,12 @@ ComponentDef<MotorJoint2DData>
(button: number) => Binding
```
+## MoveBasis — interface @experimental
+```
+forward: Vec3
+right: Vec3
+```
+
## Mut — function @public
```
<T extends AnyComponentDef>(component: T): MutWrapper<T>
@@ -8335,6 +8350,16 @@ number
"timeline"
```
+## TPC_GROUNDED — const @experimental
+```
+"grounded"
+```
+
+## TPC_SPEED — const @experimental
+```
+"speed"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -8635,6 +8660,47 @@ label: number
title: number
```
+## ThirdPersonCamera — const @experimental
+```
+ComponentDef<ThirdPersonCameraData>
+```
+
+## ThirdPersonCameraData — interface @experimental
+```
+distance: number
+enabled: boolean
+followDamping: number
+maxPitch: number
+minPitch: number
+obstruction: boolean
+obstructionLayers: number
+obstructionRadius: number
+pitch: number
+sensitivity: number
+target: number
+targetOffset: Vec3
+yaw: number
+```
+
+## ThirdPersonController — const @experimental
+```
+ComponentDef<ThirdPersonControllerData>
+```
+
+## ThirdPersonControllerData — interface @experimental
+```
+acceleration: number
+airControl: number
+camera: number
+cameraRelative: boolean
+deceleration: number
+enabled: boolean
+idleThreshold: number
+jumpSpeed: number
+moveSpeed: number
+rotationSpeed: number
+```
+
## TileCollisionPiece — interface @experimental
```
center: Vec2
@@ -9779,6 +9845,11 @@ y: number
(id: string) => Binding
```
+## WORLD_BASIS — const @experimental
+```
+MoveBasis
+```
+
## WangIndex — interface @experimental
```
byKey: Map<number, number>
@@ -10192,6 +10263,11 @@ AnimationPlugin
(time: number, duration: number, mode: WrapMode): { time: number; stopped: boolean; }
```
+## approachVelocity — function @experimental
+```
+(current: { x: number; z: number; }, target: { x: number; z: number; }, acceleration: number, deceleration: number, dt: number): { x: number; z: number; }
+```
+
## arrayDataSource — function @experimental
```
<T>(items: readonly T[]): ArrayDataSource<T>
@@ -10332,6 +10408,11 @@ BtPlugin
(camera: CameraFields, transform: CameraTransformFields, width: number, height: number, canvas: CanvasScale | null, result?: Float32Array): Float32Array
```
+## cameraGroundBasis — function @experimental
+```
+(yawDeg: number): { forward: Vec3; right: Vec3; }
+```
+
## canCaptureFramePixels — function @experimental
```
(module: ESEngineModule): boolean
@@ -10362,6 +10443,11 @@ BtPlugin
(): string[]
```
+## clampPitch — function @experimental
+```
+(pitch: number, min: number, max: number): number
+```
+
## clearAllCaches — function @experimental
```
(): void
@@ -10692,6 +10778,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## dampFactor — function @experimental
+```
+(damping: number, dt: number): number
+```
+
## debug — function @experimental
```
(category: string, message: string, data?: unknown): void
@@ -10772,6 +10863,11 @@ PluralSelector
<T>(sources: ReadonlySignal<unknown>[], compute: () => T): ReadonlySignal<T>
```
+## desiredDirection — function @experimental
+```
+(input: { x: number; y: number; }, basis: MoveBasis): Vec3
+```
+
## detectAnchor — function @experimental
```
(node: UINodeData): AnchorPreset | null
@@ -11037,6 +11133,11 @@ EventBindingPlugin
(rot: Quat, axis?: FacingAxis): Vec3
```
+## facingYaw — function @experimental
+```
+(direction: Vec3): number
+```
+
## fetchDecodePixels — function @experimental
```
(url: string): Promise<DecodedPixels>
@@ -11147,6 +11248,11 @@ FsmPlugin
(): boolean
```
+## gameplayPlugin — const @experimental
+```
+GameplayPlugin
+```
+
## gearBinding — function @experimental
```
(controller: string, component: string, property: string, pages: Record<string, GearValue>, tween?: GearTween): GearBinding
@@ -11812,6 +11918,11 @@ NavPlugin
(world: World, events: UIEventQueue, e: Entity): void
```
+## orbitOffset — function @experimental
+```
+(yawDeg: number, pitchDeg: number): Vec3
+```
+
## orientationPerm — function @experimental
```
(flags: TileFlags): Perm
@@ -12677,6 +12788,11 @@ ServicesPlugin
(shape: Collider2DShape): Vec2
```
+## shortestAngleDelta — function @experimental
+```
+(from: number, to: number): number
+```
+
## shutdownDrawAPI — function @experimental
```
(): void
@@ -12897,6 +13013,11 @@ TrailPlugin
(): number
```
+## turnToward — function @experimental
+```
+(from: number, to: number, degreesPerSecond: number, dt: number): number
+```
+
## uiHitTestWorld — function @experimental
```
(world: PickableWorld, ray: WorldRay): Entity | null
@@ -13102,3 +13223,13 @@ VideoPlugin
(f32: Float32Array, u32: Uint32Array, u8: Uint8Array, ptr: number, field: PtrFieldDesc, value: PtrFieldValue | unknown): void
```
+## yawOfQuaternion — function @experimental
+```
+(q: { w: number; y: number; }): number
+```
+
+## yawQuaternion — function @experimental
+```
+(yawDeg: number): { w: number; x: number; y: number; z: number; }
+```
+
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index f6a0933a6..caeb4ba79 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: 113 public · 84 beta · 1548 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1569 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3596,6 +3596,15 @@ index: number
mapping: string
```
+## GameplayPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: () => void
+name: string
+static new (): GameplayPlugin
+static prototype: GameplayPlugin
+```
+
## GearBinding — interface @experimental
```
component: string
@@ -4880,6 +4889,12 @@ ComponentDef<MotorJoint2DData>
(button: number) => Binding
```
+## MoveBasis — interface @experimental
+```
+forward: Vec3
+right: Vec3
+```
+
## Mut — function @public
```
<T extends AnyComponentDef>(component: T): MutWrapper<T>
@@ -8096,6 +8111,16 @@ number
"timeline"
```
+## TPC_GROUNDED — const @experimental
+```
+"grounded"
+```
+
+## TPC_SPEED — const @experimental
+```
+"speed"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -8396,6 +8421,47 @@ label: number
title: number
```
+## ThirdPersonCamera — const @experimental
+```
+ComponentDef<ThirdPersonCameraData>
+```
+
+## ThirdPersonCameraData — interface @experimental
+```
+distance: number
+enabled: boolean
+followDamping: number
+maxPitch: number
+minPitch: number
+obstruction: boolean
+obstructionLayers: number
+obstructionRadius: number
+pitch: number
+sensitivity: number
+target: number
+targetOffset: Vec3
+yaw: number
+```
+
+## ThirdPersonController — const @experimental
+```
+ComponentDef<ThirdPersonControllerData>
+```
+
+## ThirdPersonControllerData — interface @experimental
+```
+acceleration: number
+airControl: number
+camera: number
+cameraRelative: boolean
+deceleration: number
+enabled: boolean
+idleThreshold: number
+jumpSpeed: number
+moveSpeed: number
+rotationSpeed: number
+```
+
## TileCollisionPiece — interface @experimental
```
center: Vec2
@@ -9534,6 +9600,11 @@ y: number
(id: string) => Binding
```
+## WORLD_BASIS — const @experimental
+```
+MoveBasis
+```
+
## WangIndex — interface @experimental
```
byKey: Map<number, number>
@@ -9968,6 +10039,11 @@ AnimationPlugin
(time: number, duration: number, mode: WrapMode): { time: number; stopped: boolean; }
```
+## approachVelocity — function @experimental
+```
+(current: { x: number; z: number; }, target: { x: number; z: number; }, acceleration: number, deceleration: number, dt: number): { x: number; z: number; }
+```
+
## arrayDataSource — function @experimental
```
<T>(items: readonly T[]): ArrayDataSource<T>
@@ -10108,6 +10184,11 @@ BtPlugin
(camera: CameraFields, transform: CameraTransformFields, width: number, height: number, canvas: CanvasScale | null, result?: Float32Array): Float32Array
```
+## cameraGroundBasis — function @experimental
+```
+(yawDeg: number): { forward: Vec3; right: Vec3; }
+```
+
## canCaptureFramePixels — function @experimental
```
(module: ESEngineModule): boolean
@@ -10138,6 +10219,11 @@ BtPlugin
(): string[]
```
+## clampPitch — function @experimental
+```
+(pitch: number, min: number, max: number): number
+```
+
## clearAllCaches — function @experimental
```
(): void
@@ -10463,6 +10549,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## dampFactor — function @experimental
+```
+(damping: number, dt: number): number
+```
+
## debug — function @experimental
```
(category: string, message: string, data?: unknown): void
@@ -10543,6 +10634,11 @@ PluralSelector
<T>(sources: ReadonlySignal<unknown>[], compute: () => T): ReadonlySignal<T>
```
+## desiredDirection — function @experimental
+```
+(input: { x: number; y: number; }, basis: MoveBasis): Vec3
+```
+
## detectAnchor — function @experimental
```
(node: UINodeData): AnchorPreset | null
@@ -10808,6 +10904,11 @@ EventBindingPlugin
(rot: Quat, axis?: FacingAxis): Vec3
```
+## facingYaw — function @experimental
+```
+(direction: Vec3): number
+```
+
## fetchDecodePixels — function @experimental
```
(url: string): Promise<DecodedPixels>
@@ -10918,6 +11019,11 @@ FsmPlugin
(): boolean
```
+## gameplayPlugin — const @experimental
+```
+GameplayPlugin
+```
+
## gearBinding — function @experimental
```
(controller: string, component: string, property: string, pages: Record<string, GearValue>, tween?: GearTween): GearBinding
@@ -11578,6 +11684,11 @@ NavPlugin
(world: World, events: UIEventQueue, e: Entity): void
```
+## orbitOffset — function @experimental
+```
+(yawDeg: number, pitchDeg: number): Vec3
+```
+
## orientationPerm — function @experimental
```
(flags: TileFlags): Perm
@@ -12443,6 +12554,11 @@ ServicesPlugin
(shape: Collider2DShape): Vec2
```
+## shortestAngleDelta — function @experimental
+```
+(from: number, to: number): number
+```
+
## shutdownDrawAPI — function @experimental
```
(): void
@@ -12663,6 +12779,11 @@ TrailPlugin
(): number
```
+## turnToward — function @experimental
+```
+(from: number, to: number, degreesPerSecond: number, dt: number): number
+```
+
## uiHitTestWorld — function @experimental
```
(world: PickableWorld, ray: WorldRay): Entity | null
@@ -12913,3 +13034,13 @@ MiniGameProfile
(path: string, data: string | ArrayBuffer): Promise<void>
```
+## yawOfQuaternion — function @experimental
+```
+(q: { w: number; y: number; }): number
+```
+
+## yawQuaternion — function @experimental
+```
+(yawDeg: number): { w: number; x: number; y: number; z: number; }
+```
+
diff --git a/sdk/src/app/pluginSets.ts b/sdk/src/app/pluginSets.ts
index e04c10b00..a6e189cd2 100644
--- a/sdk/src/app/pluginSets.ts
+++ b/sdk/src/app/pluginSets.ts
@@ -30,6 +30,7 @@ import { meshRendererPlugin } from '../render/meshRenderer';
import { tilemapPlugin } from '../tilemap';
import { postProcessPlugin } from '../postprocess';
import { timelinePlugin } from '../timeline';
+import { gameplayPlugin } from '../gameplay';
import { timerPlugin } from '../ecs/timer';
import { velocityPlugin } from '../velocity';
import { lifecyclePlugin } from '../ecs/lifecycle';
@@ -60,7 +61,7 @@ export const simulationBasePlugins = (): Plugin[] => [
/** What exists to be seen. Every entry drives the engine through `engineApi`. */
export const presentationBasePlugins = (): Plugin[] => [
animationPlugin, videoPlugin, particlePlugin, trailPlugin, meshRendererPlugin,
- tilemapPlugin, postProcessPlugin, timelinePlugin,
+ tilemapPlugin, postProcessPlugin, timelinePlugin, gameplayPlugin,
];
/**
@@ -72,6 +73,7 @@ export const webBasePlugins = (): Plugin[] => [
diagnosticsPlugin,
timerPlugin, velocityPlugin, lifecyclePlugin, animationPlugin, audioPlugin, videoPlugin,
particlePlugin, trailPlugin, meshRendererPlugin, tilemapPlugin, postProcessPlugin, timelinePlugin,
+ gameplayPlugin,
perceptionPlugin, fsmPlugin, btPlugin, navPlugin, eventBindingPlugin, replicationPlugin,
servicesPlugin,
];
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 39ac61b0c..f83813427 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -858,6 +858,34 @@ export {
type PerceptionData,
} from './ai';
+// =============================================================================
+// Gameplay (third-person character + camera)
+// =============================================================================
+
+export {
+ GameplayPlugin,
+ gameplayPlugin,
+ ThirdPersonController,
+ ThirdPersonCamera,
+ TPC_SPEED,
+ TPC_GROUNDED,
+ desiredDirection,
+ approachVelocity,
+ facingYaw,
+ shortestAngleDelta,
+ turnToward,
+ yawQuaternion,
+ yawOfQuaternion,
+ cameraGroundBasis,
+ orbitOffset,
+ dampFactor,
+ clampPitch,
+ WORLD_BASIS,
+ type ThirdPersonControllerData,
+ type ThirdPersonCameraData,
+ type MoveBasis,
+} from './gameplay';
+
// =============================================================================
// Timeline (Sequencer)
// =============================================================================
diff --git a/sdk/src/gameplay/GameplayPlugin.ts b/sdk/src/gameplay/GameplayPlugin.ts
new file mode 100644
index 000000000..26c372f02
--- /dev/null
+++ b/sdk/src/gameplay/GameplayPlugin.ts
@@ -0,0 +1,250 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file GameplayPlugin.ts
+ * @brief Wires the third-person character and its camera into the frame.
+ *
+ * @details Three systems, and WHERE they sit is the design. The controller asks
+ * before the physics step and observes after it, so what reaches the
+ * animator is the motion the world allowed rather than the motion the
+ * player asked for. The camera runs once a frame, after everything has
+ * moved, because it follows and is never followed.
+ */
+
+import type { App, Plugin } from '../app/app';
+import { defineSystem, Schedule } from '../ecs/system';
+import { Res, Time, type TimeData } from '../ecs/resource';
+import { playModeOnly } from '../ecs/env';
+import { Input, type InputState } from '../input/input';
+import { Transform, type TransformData } from '../ecs/component';
+import { CharacterController3D, type CharacterController3DData } from '../physics3d/Physics3DComponents';
+import { Physics3D } from '../physics3d/Physics3DPlugin';
+import type { Physics3DQueries } from '../physics3d/Physics3DQueries';
+import { Animator, AnimatorController, type AnimatorControllerAPI } from '../animation/Animator';
+import type { World } from '../ecs/world';
+import type { Entity } from '../types';
+import {
+ ThirdPersonController, type ThirdPersonControllerData,
+ desiredDirection, approachVelocity, facingYaw, turnToward,
+ yawQuaternion, yawOfQuaternion, WORLD_BASIS, type MoveBasis,
+} from './ThirdPersonController';
+import {
+ ThirdPersonCamera, type ThirdPersonCameraData,
+ orbitOffset, cameraGroundBasis, dampFactor, clampPitch,
+} from './ThirdPersonCamera';
+
+/** Animator parameters this controller writes. Names, not clips. */
+export const TPC_SPEED = 'speed';
+export const TPC_GROUNDED = 'grounded';
+
+/** The stick, from the keys a keyboard stands in for one with. */
+function readStick(input: InputState): { x: number; y: number } {
+ const x = (input.isKeyDown('KeyD') ? 1 : 0) - (input.isKeyDown('KeyA') ? 1 : 0);
+ const y = (input.isKeyDown('KeyW') ? 1 : 0) - (input.isKeyDown('KeyS') ? 1 : 0);
+ const length = Math.hypot(x, y);
+ return length > 1 ? { x: x / length, y: y / length } : { x, y };
+}
+
+/** The camera a controller reads forward from: the one it names, else any. */
+function basisFor(world: World, data: ThirdPersonControllerData): MoveBasis {
+ if (!data.cameraRelative) return WORLD_BASIS;
+ const named = data.camera && world.has(data.camera, ThirdPersonCamera)
+ ? data.camera
+ : world.getEntitiesWithComponents([ThirdPersonCamera])[0];
+ if (named === undefined) return WORLD_BASIS;
+ return cameraGroundBasis((world.get(named, ThirdPersonCamera) as ThirdPersonCameraData).yaw);
+}
+
+/**
+ * Ask for motion: the stick, in the camera's ground plane, as a velocity the
+ * character controller will try to honour. The vertical component is left alone
+ * unless a jump starts one, because the character controller carries it.
+ */
+export function requestMotion(world: World, input: InputState, dt: number): void {
+ for (const entity of world.getEntitiesWithComponents([ThirdPersonController, CharacterController3D])) {
+ const data = world.get(entity, ThirdPersonController) as ThirdPersonControllerData;
+ if (!data.enabled) continue;
+
+ const character = world.get(entity, CharacterController3D) as CharacterController3DData;
+ const direction = desiredDirection(readStick(input), basisFor(world, data));
+ const target = {
+ x: direction.x * data.moveSpeed,
+ z: direction.z * data.moveSpeed,
+ };
+ // Off the ground the player has only as much say as airControl allows.
+ const authority = character.isOnFloor ? 1 : Math.max(0, Math.min(1, data.airControl));
+ const next = approachVelocity(
+ { x: character.velocity.x, z: character.velocity.z }, target,
+ data.acceleration * authority, data.deceleration * authority, dt,
+ );
+
+ // A jump is the one time the vertical is ours to set; every other frame
+ // it stays 0, which the character controller reads as "walk".
+ const jumping = data.jumpSpeed > 0 && character.isOnFloor
+ && (input.isKeyPressed('Space') || input.isKeyDown('Space'));
+
+ world.update(entity, CharacterController3D, (c: CharacterController3DData) => {
+ c.velocity.x = next.x;
+ c.velocity.z = next.z;
+ c.velocity.y = jumping ? data.jumpSpeed : 0;
+ });
+ }
+}
+
+/**
+ * Observe what happened. The animator is told the speed the character REACHED,
+ * so walking into a wall reads as standing still, and the character turns to
+ * face where it actually went.
+ */
+export function observeMotion(world: World, animator: AnimatorControllerAPI | null, dt: number): void {
+ for (const entity of world.getEntitiesWithComponents([ThirdPersonController, CharacterController3D])) {
+ const data = world.get(entity, ThirdPersonController) as ThirdPersonControllerData;
+ if (!data.enabled) continue;
+
+ const character = world.get(entity, CharacterController3D) as CharacterController3DData;
+ const moved = character.realVelocity;
+ const speed = Math.hypot(moved.x, moved.z);
+
+ if (animator && world.has(entity, Animator)) {
+ animator.setFloat(entity, TPC_SPEED, speed < data.idleThreshold ? 0 : speed);
+ animator.setBool(entity, TPC_GROUNDED, character.isOnFloor);
+ }
+
+ // Face where it is going, not where it was asked to go - and hold the
+ // last heading when it stops, rather than snapping back to world forward.
+ if (speed < data.idleThreshold || !world.has(entity, Transform)) continue;
+ const wanted = facingYaw({ x: moved.x, y: 0, z: moved.z });
+ world.update(entity, Transform, (t: TransformData) => {
+ const turned = turnToward(yawOfQuaternion(t.rotation), wanted, data.rotationSpeed, dt);
+ const q = yawQuaternion(turned);
+ t.rotation.w = q.w; t.rotation.x = q.x; t.rotation.y = q.y; t.rotation.z = q.z;
+ });
+ }
+}
+
+/** Per-camera pointer state, so a delta exists without the input layer keeping one. */
+const lastPointer = new Map<Entity, { x: number; y: number }>();
+
+/**
+ * How far back the eye may sit before something solid is in the way. The probe
+ * is a sphere so the eye stops short of a wall rather than touching it.
+ */
+function clearDistance(
+ queries: Physics3DQueries | null, data: ThirdPersonCameraData,
+ pivot: { x: number; y: number; z: number }, offset: { x: number; y: number; z: number },
+): number {
+ if (!data.obstruction || !queries || data.distance <= 0) return data.distance;
+ const hit = queries.sphereCast(
+ pivot, data.obstructionRadius,
+ { x: offset.x * data.distance, y: offset.y * data.distance, z: offset.z * data.distance },
+ data.obstructionLayers,
+ );
+ if (!hit) return data.distance;
+ // The hit is a FRACTION of the sweep, and the sweep was the full distance.
+ return Math.max(0, Math.min(data.distance, hit.fraction * data.distance));
+}
+
+export function updateCameras(
+ world: World, input: InputState, queries: Physics3DQueries | null, dt: number,
+): void {
+ for (const entity of world.getEntitiesWithComponents([ThirdPersonCamera, Transform])) {
+ const data = world.get(entity, ThirdPersonCamera) as ThirdPersonCameraData;
+ if (!data.enabled || !data.target || !world.has(data.target, Transform)) continue;
+
+ const pointer = input.getMousePosition();
+ const previous = lastPointer.get(entity);
+ lastPointer.set(entity, { x: pointer.x, y: pointer.y });
+ // Only while a button is held: a free pointer over the window is not
+ // someone turning the camera.
+ const dragging = input.isMouseButtonDown(0) || input.isMouseButtonDown(2);
+ let { yaw, pitch } = data;
+ if (previous && dragging) {
+ yaw -= (pointer.x - previous.x) * data.sensitivity;
+ pitch = clampPitch(pitch + (pointer.y - previous.y) * data.sensitivity,
+ data.minPitch, data.maxPitch);
+ }
+ if (yaw !== data.yaw || pitch !== data.pitch) {
+ world.update(entity, ThirdPersonCamera, (c: ThirdPersonCameraData) => {
+ c.yaw = yaw; c.pitch = pitch;
+ });
+ }
+
+ const targetTransform = world.get(data.target, Transform) as TransformData;
+ const pivot = {
+ x: targetTransform.position.x + data.targetOffset.x,
+ y: targetTransform.position.y + data.targetOffset.y,
+ z: targetTransform.position.z + data.targetOffset.z,
+ };
+ const offset = orbitOffset(yaw, pitch);
+ const distance = clearDistance(queries, data, pivot, offset);
+ const wanted = {
+ x: pivot.x + offset.x * distance,
+ y: pivot.y + offset.y * distance,
+ z: pivot.z + offset.z * distance,
+ };
+
+ const k = dampFactor(data.followDamping, dt);
+ world.update(entity, Transform, (t: TransformData) => {
+ t.position.x += (wanted.x - t.position.x) * k;
+ t.position.y += (wanted.y - t.position.y) * k;
+ t.position.z += (wanted.z - t.position.z) * k;
+ // Looking back down the offset it sits along: pitch tips the eye
+ // down when the camera is above, which is the negative turn about X.
+ const half = { p: -pitch * Math.PI / 360, y: yaw * Math.PI / 360 };
+ const cp = Math.cos(half.p), sp = Math.sin(half.p);
+ const cy = Math.cos(half.y), sy = Math.sin(half.y);
+ t.rotation.w = cp * cy;
+ t.rotation.x = sp * cy;
+ t.rotation.y = cp * sy;
+ t.rotation.z = -sp * sy;
+ });
+ }
+}
+
+export class GameplayPlugin implements Plugin {
+ name = 'gameplay';
+ private offDespawn_: (() => void) | null = null;
+
+ build(app: App): void {
+ const world = app.world;
+ this.offDespawn_ = world.onDespawn((entity: Entity) => { lastPointer.delete(entity); });
+
+ // Before the physics step: what the player is asking for.
+ app.addSystemToSchedule(Schedule.FixedPreUpdate, defineSystem(
+ [Res(Time), Res(Input)],
+ (time: TimeData, input: InputState) => {
+ requestMotion(world, input, time.fixedDelta);
+ },
+ { name: 'ThirdPersonControllerSystem' },
+ ), { runIf: playModeOnly });
+
+ // After it: what the world allowed. The animator hears this one.
+ app.addSystemToSchedule(Schedule.FixedPostUpdate, defineSystem(
+ [Res(Time)],
+ (time: TimeData) => {
+ const animator = app.hasResource(AnimatorController)
+ ? app.getResource(AnimatorController) : null;
+ observeMotion(world, animator, time.fixedDelta);
+ },
+ { name: 'ThirdPersonObserveSystem' },
+ ), { runIf: playModeOnly });
+
+ // Once a frame, after everything it follows has moved.
+ app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(
+ [Res(Time), Res(Input)],
+ (time: TimeData, input: InputState) => {
+ const queries = app.hasResource(Physics3D) ? app.getResource(Physics3D) : null;
+ updateCameras(world, input, queries, time.delta);
+ },
+ { name: 'ThirdPersonCameraSystem' },
+ ), { runIf: playModeOnly });
+ }
+
+ cleanup(): void {
+ this.offDespawn_?.();
+ this.offDespawn_ = null;
+ lastPointer.clear();
+ }
+}
+
+export const gameplayPlugin = new GameplayPlugin();
diff --git a/sdk/src/gameplay/ThirdPersonCamera.ts b/sdk/src/gameplay/ThirdPersonCamera.ts
new file mode 100644
index 000000000..369759e1e
--- /dev/null
+++ b/sdk/src/gameplay/ThirdPersonCamera.ts
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ThirdPersonCamera.ts
+ * @brief An eye that orbits a target and does not go through walls.
+ *
+ * @details Owns where the camera is and which way it looks: yaw, pitch, how far
+ * back it sits and how it catches up. It moves nothing else - a
+ * character's motion is {@link ThirdPersonController}'s, and the two
+ * only meet where the controller reads this yaw to know what "forward"
+ * means to the player.
+ *
+ * Obstruction asks the physics world the same way anything else does.
+ * A camera that owned a second notion of solid would drift from the one
+ * the character walks against.
+ */
+
+import { defineComponent, type ComponentDef } from '../ecs/component';
+import type { Entity } from '../types';
+import type { Vec3 } from '../types';
+
+/** The fields of the `ThirdPersonCamera` component. @experimental */
+export interface ThirdPersonCameraData {
+ /** What it orbits. 0 = inert. */
+ target: Entity;
+ /** How far back it sits when nothing is in the way, world units. */
+ distance: number;
+ /** Turn about world up, degrees. */
+ yaw: number;
+ /** Turn above the horizon, degrees; positive looks down at the target. */
+ pitch: number;
+ minPitch: number;
+ maxPitch: number;
+ /** Degrees per pixel of pointer travel. */
+ sensitivity: number;
+ /** How fast position catches up, per second. 0 = rigid. */
+ followDamping: number;
+ /** Lifted off the target's origin, so the eye frames the chest not the feet. */
+ targetOffset: Vec3;
+ /** Pull in when something solid stands between the pivot and the eye. */
+ obstruction: boolean;
+ /** How fat the probe is, so the eye stops before it clips a wall. */
+ obstructionRadius: number;
+ /** Physics layers the probe collides with; 0 = every layer. */
+ obstructionLayers: number;
+ enabled: boolean;
+}
+
+/**
+ * A camera that orbits a target under pointer control.
+ *
+ * @experimental
+ */
+export const ThirdPersonCamera: ComponentDef<ThirdPersonCameraData> =
+ defineComponent<ThirdPersonCameraData>('ThirdPersonCamera', {
+ target: 0 as Entity,
+ distance: 420,
+ yaw: 0,
+ pitch: 15,
+ minPitch: -30,
+ maxPitch: 70,
+ sensitivity: 0.2,
+ followDamping: 12,
+ targetOffset: { x: 0, y: 90, z: 0 },
+ obstruction: true,
+ obstructionRadius: 15,
+ obstructionLayers: 0,
+ enabled: true,
+ }, {
+ entityFields: ['target'],
+ fields: {
+ target: { tooltip: 'The transform this camera orbits.' },
+ minPitch: { unit: '°' },
+ maxPitch: { unit: '°' },
+ yaw: { unit: '°' },
+ pitch: { unit: '°' },
+ obstructionRadius: { min: 0, advanced: true },
+ obstructionLayers: { min: 0, max: 15, step: 1, advanced: true },
+ followDamping: { min: 0, advanced: true },
+ },
+ });
+
+const DEG2RAD = Math.PI / 180;
+
+/**
+ * Where the eye sits relative to its pivot, at these angles. Length 1, and
+ * pointing BEHIND the target: the camera looks back down it.
+ */
+export function orbitOffset(yawDeg: number, pitchDeg: number): Vec3 {
+ const yaw = yawDeg * DEG2RAD;
+ const pitch = pitchDeg * DEG2RAD;
+ const flat = Math.cos(pitch);
+ return { x: Math.sin(yaw) * flat, y: Math.sin(pitch), z: Math.cos(yaw) * flat };
+}
+
+/**
+ * The ground-plane basis the player's input is read in, for a camera at this
+ * yaw. PITCH IS ABSENT on purpose: forward is where the player looks ALONG the
+ * ground, so an eye angled steeply down still walks the character across the
+ * floor rather than into it.
+ */
+export function cameraGroundBasis(yawDeg: number): { forward: Vec3; right: Vec3 } {
+ const yaw = yawDeg * DEG2RAD;
+ return {
+ forward: { x: -Math.sin(yaw), y: 0, z: -Math.cos(yaw) },
+ right: { x: Math.cos(yaw), y: 0, z: -Math.sin(yaw) },
+ };
+}
+
+/**
+ * How much of the way to the target a damped value travels in `dt`.
+ * `damping` is a rate per second; 0 means "arrive now", which is what a gate
+ * that wants to read the settled value asks for.
+ */
+export function dampFactor(damping: number, dt: number): number {
+ if (damping <= 0) return 1;
+ return 1 - Math.exp(-damping * dt);
+}
+
+/** Keep `pitch` inside its limits, whichever way round they were authored. */
+export function clampPitch(pitch: number, min: number, max: number): number {
+ const lo = Math.min(min, max);
+ const hi = Math.max(min, max);
+ return Math.min(Math.max(pitch, lo), hi);
+}
diff --git a/sdk/src/gameplay/ThirdPersonController.ts b/sdk/src/gameplay/ThirdPersonController.ts
new file mode 100644
index 000000000..3e8e911ca
--- /dev/null
+++ b/sdk/src/gameplay/ThirdPersonController.ts
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ThirdPersonController.ts
+ * @brief Input to a walking character, and the character's real motion back
+ * out to its animator.
+ *
+ * @details It decides what the player WANTS - a direction in the camera's ground
+ * plane, a speed to reach it at, a jump - and asks
+ * CharacterController3D for it. What actually happens is the physics
+ * world's answer, and that answer, not the request, is what reaches the
+ * animator: a character shoving a wall has a full stick and no motion,
+ * and it must not be running on the spot.
+ *
+ * It solves no collision, owns no gravity (the character controller
+ * carries the vertical component), and names no animation clip.
+ */
+
+import { defineComponent, type ComponentDef } from '../ecs/component';
+import type { Entity } from '../types';
+import type { Vec3 } from '../types';
+
+/** The fields of the `ThirdPersonController` component. @experimental */
+export interface ThirdPersonControllerData {
+ /** Top speed on the ground, world units per second. */
+ moveSpeed: number;
+ /** How fast it reaches that speed, units per second squared. */
+ acceleration: number;
+ /** How fast it sheds it when the stick centres. */
+ deceleration: number;
+ /** How fast it turns to face where it is going, degrees per second. */
+ rotationSpeed: number;
+ /** Upward speed a jump starts with; 0 disables jumping. */
+ jumpSpeed: number;
+ /** How much of `acceleration` applies while off the ground, 0..1. */
+ airControl: number;
+ /** Read the stick in the camera's ground plane rather than the world's. */
+ cameraRelative: boolean;
+ /** The camera that defines "forward". 0 = the first ThirdPersonCamera found. */
+ camera: Entity;
+ /** Speed under which the animator is told the character is standing still. */
+ idleThreshold: number;
+ enabled: boolean;
+}
+
+/**
+ * Drives a CharacterController3D from player input, and reports what the
+ * character actually did to its Animator.
+ *
+ * @experimental
+ */
+export const ThirdPersonController: ComponentDef<ThirdPersonControllerData> =
+ defineComponent<ThirdPersonControllerData>('ThirdPersonController', {
+ moveSpeed: 320,
+ acceleration: 2400,
+ deceleration: 3200,
+ rotationSpeed: 720,
+ jumpSpeed: 0,
+ airControl: 0.3,
+ cameraRelative: true,
+ camera: 0 as Entity,
+ idleThreshold: 8,
+ enabled: true,
+ }, {
+ entityFields: ['camera'],
+ fields: {
+ camera: { tooltip: 'Whose forward the stick is read against.' },
+ rotationSpeed: { unit: '°/s' },
+ airControl: { min: 0, max: 1, step: 0.05, advanced: true },
+ idleThreshold: { min: 0, step: 0.05, advanced: true },
+ jumpSpeed: { min: 0, tooltip: 'Upward speed a jump starts with. 0 = cannot jump.' },
+ },
+ });
+
+// =============================================================================
+// The decisions, as pure functions
+// =============================================================================
+
+const DEG2RAD = Math.PI / 180;
+const RAD2DEG = 180 / Math.PI;
+
+/** A basis to read the stick against: two ground-plane axes. */
+export interface MoveBasis {
+ forward: Vec3;
+ right: Vec3;
+}
+
+/** The world basis, for a controller reading its stick without a camera. */
+export const WORLD_BASIS: MoveBasis = {
+ forward: { x: 0, y: 0, z: -1 },
+ right: { x: 1, y: 0, z: 0 },
+};
+
+/**
+ * Where the player is asking to go, as a unit vector on the ground plane.
+ * Zero-length when the stick is centred, which is a stop rather than a
+ * direction. `input.y` is forward on the stick, `input.x` is right.
+ */
+export function desiredDirection(
+ input: { x: number; y: number }, basis: MoveBasis,
+): Vec3 {
+ const x = basis.forward.x * input.y + basis.right.x * input.x;
+ const z = basis.forward.z * input.y + basis.right.z * input.x;
+ const length = Math.hypot(x, z);
+ if (length < 1e-6) return { x: 0, y: 0, z: 0 };
+ return { x: x / length, y: 0, z: z / length };
+}
+
+/**
+ * Move a horizontal velocity toward what was asked for. Accelerating and
+ * stopping are separate rates because a character that coasts to a halt as
+ * slowly as it gets going feels like it is on ice.
+ */
+export function approachVelocity(
+ current: { x: number; z: number }, target: { x: number; z: number },
+ acceleration: number, deceleration: number, dt: number,
+): { x: number; z: number } {
+ const dx = target.x - current.x;
+ const dz = target.z - current.z;
+ const gap = Math.hypot(dx, dz);
+ if (gap < 1e-6) return { x: target.x, z: target.z };
+
+ const slowing = Math.hypot(target.x, target.z) < Math.hypot(current.x, current.z);
+ const step = (slowing ? deceleration : acceleration) * dt;
+ if (step >= gap) return { x: target.x, z: target.z };
+ return { x: current.x + (dx / gap) * step, z: current.z + (dz / gap) * step };
+}
+
+/** The heading, in degrees about world up, that a ground direction points at. */
+export function facingYaw(direction: Vec3): number {
+ return Math.atan2(-direction.x, -direction.z) * RAD2DEG;
+}
+
+/** The signed shortest way from `from` to `to`, in degrees. */
+export function shortestAngleDelta(from: number, to: number): number {
+ let delta = (to - from) % 360;
+ if (delta > 180) delta -= 360;
+ if (delta < -180) delta += 360;
+ return delta;
+}
+
+/**
+ * Turn `from` toward `to` at a rate. The shortest way round, so a character
+ * crossing the -180/180 seam does not spin the long way to get there.
+ */
+export function turnToward(from: number, to: number, degreesPerSecond: number, dt: number): number {
+ const delta = shortestAngleDelta(from, to);
+ if (degreesPerSecond <= 0) return to;
+ const step = degreesPerSecond * dt;
+ if (Math.abs(delta) <= step) return to;
+ return from + Math.sign(delta) * step;
+}
+
+/** A yaw in degrees as the rotation quaternion about world up. */
+export function yawQuaternion(yawDeg: number): { w: number; x: number; y: number; z: number } {
+ const half = yawDeg * DEG2RAD * 0.5;
+ return { w: Math.cos(half), x: 0, y: Math.sin(half), z: 0 };
+}
+
+/** The yaw a rotation about world up carries, in degrees. */
+export function yawOfQuaternion(q: { w: number; y: number }): number {
+ return 2 * Math.atan2(q.y, q.w) * RAD2DEG;
+}
diff --git a/sdk/src/gameplay/index.ts b/sdk/src/gameplay/index.ts
new file mode 100644
index 000000000..f8d4b3634
--- /dev/null
+++ b/sdk/src/gameplay/index.ts
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+export {
+ ThirdPersonController,
+ desiredDirection,
+ approachVelocity,
+ facingYaw,
+ shortestAngleDelta,
+ turnToward,
+ yawQuaternion,
+ yawOfQuaternion,
+ WORLD_BASIS,
+ type ThirdPersonControllerData,
+ type MoveBasis,
+} from './ThirdPersonController';
+
+export {
+ ThirdPersonCamera,
+ orbitOffset,
+ cameraGroundBasis,
+ dampFactor,
+ clampPitch,
+ type ThirdPersonCameraData,
+} from './ThirdPersonCamera';
+
+export {
+ GameplayPlugin,
+ gameplayPlugin,
+ TPC_SPEED,
+ TPC_GROUNDED,
+ requestMotion,
+ observeMotion,
+ updateCameras,
+} from './GameplayPlugin';
diff --git a/sdk/tests/thirdPerson.test.ts b/sdk/tests/thirdPerson.test.ts
new file mode 100644
index 000000000..8040be42c
--- /dev/null
+++ b/sdk/tests/thirdPerson.test.ts
@@ -0,0 +1,284 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The claim: what the player asks for and what the character did are different
+ * things, and only the second one reaches the animator or the transform.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ ThirdPersonController, ThirdPersonCamera, requestMotion, observeMotion, updateCameras,
+ TPC_SPEED, TPC_GROUNDED, cameraGroundBasis, desiredDirection, approachVelocity,
+ facingYaw, turnToward,
+ type ThirdPersonControllerData, type ThirdPersonCameraData,
+} from '../src/gameplay';
+import { CharacterController3D, type CharacterController3DData } from '../src/physics3d/Physics3DComponents';
+import { Animator, AnimatorControllerAPI, type AnimatorData } from '../src/animation';
+import { Transform, type TransformData } from '../src/ecs/component';
+
+const PLAYER = 1;
+const CAMERA = 2;
+
+function makeWorld() {
+ const store = new Map<unknown, Map<number, unknown>>();
+ const mapOf = (c: unknown) => {
+ let m = store.get(c);
+ if (!m) { m = new Map(); store.set(c, m); }
+ return m;
+ };
+ return {
+ insert(e: number, c: unknown, d: unknown) { mapOf(c).set(e, d); },
+ get(e: number, c: unknown) { return mapOf(c).get(e); },
+ has(e: number, c: unknown) { return mapOf(c).has(e); },
+ set(e: number, c: unknown, d: unknown) { mapOf(c).set(e, d); },
+ update(e: number, c: unknown, edit: (d: any) => void) {
+ const d = mapOf(c).get(e);
+ if (d === undefined) throw new Error('update: entity does not carry it');
+ edit(d); mapOf(c).set(e, d);
+ },
+ getEntitiesWithComponents(comps: unknown[]) {
+ const [first, ...rest] = comps;
+ return [...mapOf(first).keys()].filter(e => rest.every(c => mapOf(c).has(e)));
+ },
+ } as any;
+}
+
+/** A keyboard held down on the named keys, and a pointer that never moves. */
+function stubInput(keys: string[] = [], pointer = { x: 0, y: 0 }, dragging = false) {
+ const held = new Set(keys);
+ return {
+ isKeyDown: (k: string) => held.has(k),
+ isKeyPressed: (k: string) => held.has(k),
+ getMousePosition: () => pointer,
+ isMouseButtonDown: () => dragging,
+ } as any;
+}
+
+const transform = (): TransformData => ({
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 },
+} as TransformData);
+
+const character = (over: Partial<CharacterController3DData> = {}): CharacterController3DData => ({
+ velocity: { x: 0, y: 0, z: 0 },
+ radius: 0.3, halfHeight: 0.5, maxSlope: 0.87, layer: 0,
+ stepHeight: 0.4, snapDown: 0.5, mass: 70, pushForce: 5000, enabled: true,
+ isOnFloor: true, floorNormal: { x: 0, y: 1, z: 0 },
+ realVelocity: { x: 0, y: 0, z: 0 },
+ ...over,
+} as CharacterController3DData);
+
+const controller = (over: Partial<ThirdPersonControllerData> = {}): ThirdPersonControllerData => ({
+ moveSpeed: 4, acceleration: 1000, deceleration: 1000, rotationSpeed: 720,
+ jumpSpeed: 0, airControl: 0.3, cameraRelative: true, camera: 0 as never,
+ idleThreshold: 0.1, enabled: true, ...over,
+});
+
+const camera = (over: Partial<ThirdPersonCameraData> = {}): ThirdPersonCameraData => ({
+ target: PLAYER as never, distance: 6, yaw: 0, pitch: 0,
+ minPitch: -30, maxPitch: 70, sensitivity: 0.2,
+ followDamping: 0,
+ targetOffset: { x: 0, y: 0, z: 0 },
+ obstruction: true, obstructionRadius: 0.2, obstructionLayers: 0, enabled: true,
+ ...over,
+});
+
+/** A player standing on the floor, with a camera at `yaw` looking at it. */
+function scene(yaw = 0, over: Partial<ThirdPersonControllerData> = {}) {
+ const world = makeWorld();
+ world.insert(PLAYER, Transform, transform());
+ world.insert(PLAYER, CharacterController3D, character());
+ world.insert(PLAYER, ThirdPersonController, controller(over));
+ world.insert(PLAYER, Animator, { controller: 'x', currentState: '', enabled: true } as AnimatorData);
+ world.insert(CAMERA, Transform, transform());
+ world.insert(CAMERA, ThirdPersonCamera, camera({ yaw }));
+ return world;
+}
+
+const askedVelocity = (world: any) =>
+ (world.get(PLAYER, CharacterController3D) as CharacterController3DData).velocity;
+
+describe('the stick is read in the camera ground plane', () => {
+ it('walks along -Z with the camera behind the player', () => {
+ const world = scene(0);
+ requestMotion(world, stubInput(['KeyW']), 1 / 60);
+
+ const v = askedVelocity(world);
+ expect(v.z).toBeCloseTo(-4, 5);
+ expect(Math.abs(v.x)).toBeLessThan(1e-6);
+ });
+
+ it('walks along -X once the camera has turned a quarter', () => {
+ const world = scene(90);
+ requestMotion(world, stubInput(['KeyW']), 1 / 60);
+
+ const v = askedVelocity(world);
+ expect(v.x).toBeCloseTo(-4, 5);
+ expect(Math.abs(v.z)).toBeLessThan(1e-5);
+ });
+
+ it('ignores camera pitch, so looking down does not walk into the floor', () => {
+ // The basis is built from yaw alone; a steep pitch must not tilt it.
+ const level = cameraGroundBasis(0);
+ const direction = desiredDirection({ x: 0, y: 1 }, level);
+ expect(direction.y).toBe(0);
+ expect(direction.z).toBeCloseTo(-1, 6);
+ });
+});
+
+describe('the animator hears what happened, not what was asked', () => {
+ it('reports the speed the character reached', () => {
+ const world = scene(0);
+ const animator = new AnimatorControllerAPI();
+ requestMotion(world, stubInput(['KeyW']), 1 / 60);
+ // The physics step's answer: it moved at 3, not the 4 it asked for.
+ world.update(PLAYER, CharacterController3D, (c: CharacterController3DData) => {
+ c.realVelocity.z = -3;
+ });
+ observeMotion(world, animator, 1 / 60);
+
+ expect(animator.getFloat(PLAYER, TPC_SPEED)).toBeCloseTo(3, 5);
+ });
+
+ it('says standing still when a wall takes the motion away', () => {
+ const world = scene(0);
+ const animator = new AnimatorControllerAPI();
+ requestMotion(world, stubInput(['KeyW']), 1 / 60);
+
+ // The stick is full: the character ASKED to move.
+ expect(Math.hypot(askedVelocity(world).x, askedVelocity(world).z)).toBeCloseTo(4, 5);
+ // And the world gave it nothing, which is what a wall does.
+ world.update(PLAYER, CharacterController3D, (c: CharacterController3DData) => {
+ c.realVelocity.x = 0; c.realVelocity.z = 0;
+ });
+ observeMotion(world, animator, 1 / 60);
+
+ expect(animator.getFloat(PLAYER, TPC_SPEED)).toBe(0);
+ });
+
+ it('passes the floor contact through as it stands', () => {
+ const world = scene(0);
+ const animator = new AnimatorControllerAPI();
+ world.update(PLAYER, CharacterController3D, (c: CharacterController3DData) => {
+ c.isOnFloor = false;
+ });
+ observeMotion(world, animator, 1 / 60);
+ expect(animator.getBool(PLAYER, TPC_GROUNDED)).toBe(false);
+ });
+});
+
+describe('movement goes through the character controller', () => {
+ it('asks for a velocity and moves no transform itself', () => {
+ const world = scene(0);
+ const before = { ...(world.get(PLAYER, Transform) as TransformData).position };
+ requestMotion(world, stubInput(['KeyW']), 1 / 60);
+ const after = (world.get(PLAYER, Transform) as TransformData).position;
+
+ expect(after).toEqual(before);
+ expect(askedVelocity(world).z).toBeCloseTo(-4, 5);
+ });
+
+ it('leaves the vertical alone so the controller keeps carrying it', () => {
+ const world = scene(0);
+ requestMotion(world, stubInput(['KeyW']), 1 / 60);
+ expect(askedVelocity(world).y).toBe(0);
+ });
+
+ it('starts a jump only from the floor', () => {
+ const world = scene(0, { jumpSpeed: 5 });
+ requestMotion(world, stubInput(['Space']), 1 / 60);
+ expect(askedVelocity(world).y).toBeCloseTo(5, 5);
+
+ world.update(PLAYER, CharacterController3D, (c: CharacterController3DData) => {
+ c.isOnFloor = false;
+ });
+ requestMotion(world, stubInput(['Space']), 1 / 60);
+ expect(askedVelocity(world).y).toBe(0);
+ });
+});
+
+describe('a centred stick stops the character', () => {
+ it('decelerates to nothing', () => {
+ const world = scene(0, { deceleration: 50 });
+ requestMotion(world, stubInput(['KeyW']), 1 / 60);
+ expect(Math.hypot(askedVelocity(world).x, askedVelocity(world).z)).toBeGreaterThan(0);
+
+ for (let i = 0; i < 60; i++) requestMotion(world, stubInput([]), 1 / 60);
+ expect(Math.hypot(askedVelocity(world).x, askedVelocity(world).z)).toBeCloseTo(0, 6);
+ });
+
+ it('keeps the heading it stopped at rather than snapping to world forward', () => {
+ const world = scene(0);
+ const animator = new AnimatorControllerAPI();
+ world.update(PLAYER, CharacterController3D, (c: CharacterController3DData) => {
+ c.realVelocity.x = -3;
+ });
+ observeMotion(world, animator, 1);
+ const facing = { ...(world.get(PLAYER, Transform) as TransformData).rotation };
+
+ world.update(PLAYER, CharacterController3D, (c: CharacterController3DData) => {
+ c.realVelocity.x = 0;
+ });
+ observeMotion(world, animator, 1);
+ expect((world.get(PLAYER, Transform) as TransformData).rotation).toEqual(facing);
+ });
+});
+
+describe('the camera keeps out of walls', () => {
+ const noWall = { sphereCast: () => null } as any;
+ /** A wall halfway along whatever the camera sweeps. */
+ const wallAtHalf = { sphereCast: () => ({ entity: 9, fraction: 0.5, x: 0, y: 0, z: 0,
+ normalX: 0, normalY: 0, normalZ: 1 }) } as any;
+
+ const cameraDistance = (world: any): number => {
+ const p = (world.get(CAMERA, Transform) as TransformData).position;
+ const t = (world.get(PLAYER, Transform) as TransformData).position;
+ return Math.hypot(p.x - t.x, p.y - t.y, p.z - t.z);
+ };
+
+ it('sits at its full distance with nothing in the way', () => {
+ const world = scene(0);
+ updateCameras(world, stubInput(), noWall, 1 / 60);
+ expect(cameraDistance(world)).toBeCloseTo(6, 4);
+ });
+
+ it('pulls in when something stands between', () => {
+ const world = scene(0);
+ updateCameras(world, stubInput(), wallAtHalf, 1 / 60);
+ expect(cameraDistance(world)).toBeCloseTo(3, 4);
+ });
+
+ it('goes back out once the way is clear', () => {
+ const world = scene(0);
+ updateCameras(world, stubInput(), wallAtHalf, 1 / 60);
+ expect(cameraDistance(world)).toBeCloseTo(3, 4);
+ updateCameras(world, stubInput(), noWall, 1 / 60);
+ expect(cameraDistance(world)).toBeCloseTo(6, 4);
+ });
+
+ it('moves the camera and never the character', () => {
+ const world = scene(0);
+ const before = { ...(world.get(PLAYER, Transform) as TransformData).position };
+ updateCameras(world, stubInput(), wallAtHalf, 1 / 60);
+ expect((world.get(PLAYER, Transform) as TransformData).position).toEqual(before);
+ });
+});
+
+describe('the pure decisions', () => {
+ it('accelerates and decelerates at their own rates', () => {
+ const up = approachVelocity({ x: 0, z: 0 }, { x: 10, z: 0 }, 10, 1000, 0.1);
+ expect(up.x).toBeCloseTo(1, 6);
+ const down = approachVelocity({ x: 10, z: 0 }, { x: 0, z: 0 }, 10, 100, 0.1);
+ expect(down.x).toBeCloseTo(0, 6);
+ });
+
+ it('faces along -Z at zero yaw', () => {
+ expect(facingYaw({ x: 0, y: 0, z: -1 })).toBeCloseTo(0, 6);
+ expect(facingYaw({ x: -1, y: 0, z: 0 })).toBeCloseTo(90, 6);
+ });
+
+ it('turns the short way across the seam', () => {
+ expect(turnToward(170, -170, 3600, 1 / 60)).toBeCloseTo(-170, 6);
+ expect(turnToward(170, -170, 60, 0.1)).toBeCloseTo(176, 6);
+ });
+});
diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjs
index b9a3caad7..b91dabac7 100644
--- a/tools/apiSubsystems.mjs
+++ b/tools/apiSubsystems.mjs
@@ -222,6 +222,16 @@ export const SUBSYSTEMS = [
whyZh: '各平台路径差异仍大,这套面还在收敛',
entry: ['Video'],
},
+ {
+ id: 'gameplay',
+ title: 'Gameplay — third-person character and camera',
+ titleZh: 'Gameplay —— 第三人称角色与相机',
+ source: ['gameplay'],
+ tier: 'experimental',
+ why: 'the newest layer in the engine, and the one a game shapes hardest: what a character owes its animator settled first, everything above it has not',
+ whyZh: '引擎里最新的一层,也是最被具体游戏塑形的一层:角色欠动画什么已经定了,它之上的还没有',
+ entry: ['ThirdPersonController', 'ThirdPersonCamera'],
+ },
{
id: 'ai',
title: 'AI — navigation, FSM, behaviour trees',