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): FirstPersonController looks, walks, jumps and crouches in a CharacterController3D; FirstPersonViewModel draws a held thing with a second camera so it does not go through walls

yhhc399f3ceacdd
diff --git a/desktop b/desktop
index 6a6b62b26..98b847df0 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 6a6b62b26c950c2ad2e30ea61b74cc92129c0cb4
+Subproject commit 98b847df0e354da9a5b52ea8417ffaedf31eb7bf
diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
index 868e2805b..47766ec37 100644
--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx
+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
@@ -249,6 +249,62 @@ still walks the character across the floor. Pitch never reaches the character.
when something solid stands between. It moves nothing but itself.
</Aside>
+## First person
+
+`FirstPersonController` looks, walks, jumps and crouches in a `CharacterController3D`, the way the third-person layer does: it asks, and the physics world answers.
+Put it on the body, with a camera as its child; the body turns with the player's yaw and the camera tilts with the pitch.
+
+```typescript
+// Components a scene declares.
+world.insert(player, CharacterController3D, { radius: 30, halfHeight: 90 });
+world.insert(player, FirstPersonController, { moveSpeed: 320, jumpSpeed: 420 });
+// …and a Camera on a child of `player`.
+```
+
+- **Looking.** On the web the first click takes the pointer (`pointerLock`) and the mouse turns the view; without it the view turns while a button is held. On a
+ touch screen a finger that starts `touchLookFrom` pixels across the screen (480 by default) turns it, which leaves the left for a stick. A mini game has no pointer
+ to take, so it looks by touch.
+- **Walking.** WASD or the arrow keys, **Shift** to sprint, **Space** to jump, **Ctrl** or **C** to crouch. The speed, the sprint and crouch multipliers, the
+ acceleration and how much say the player has in the air are fields.
+- **Crouching** makes the capsule again at `crouchHalfHeight`, with the feet where they were: the physics world cannot resize a character, so the old one is let go for
+ a step. Standing up first looks for a ceiling, and the player stays down where there is none to stand under.
+
+### A view model
+
+A held thing drawn with the world's camera goes through walls and stretches with a wide field of view. `FirstPersonViewModel`, on the player's camera, draws it with a
+second camera instead: one is made under the camera, drawing only the sorting layer you name (`layer`, 20 by default), with a field of view and near plane of its own, over
+the world and not clearing it. The player's camera is told not to draw that layer. Put the held thing under the camera and give its renderers that layer.
+
+```typescript
+world.insert(camera, FirstPersonViewModel, { layer: 20, fov: 50, nearPlane: 1 });
+world.insert(weapon, MeshRenderer, { mesh: 'builtin:cube', layer: 20 });
+```
+
+Both are in `esengine/gameplay`. There is no weapon system, ballistics or damage in them, and no template yet; the input is the keyboard, the pointer and the touch screen, and a
+virtual stick or a gamepad are not read.
+
+## Ragdoll
+
+A `Ragdoll` on a skinned character turns its bones into jointed bodies when you switch `active` on, and gives the pose back to the animation when you switch it off. It reads
+the skeleton the character already has (the joints its skinned mesh names), so there is nothing to author beyond the switch and a few numbers.
+
+```typescript
+world.insert(enemy, Ragdoll, { active: false });
+// When it is knocked down:
+world.insert(enemy, Ragdoll, { ...world.get(enemy, Ragdoll), active: true });
+```
+
+- Each bone that is long enough gets a box along it, joined by a swing/twist joint to the nearest bone above that has one, at the pose the animation had that frame, so
+ nothing snaps. The animation keeps running underneath; the bodies' pose is put back over it each frame.
+- **Limits.** With the `Humanoid` profile (the default) each joint gets the share of `swing` and `twist` its part of a body has, read from the bone's name (a spine stiff,
+ a shoulder loose, a shin almost a hinge). A knee and an elbow are one-way hinges of at most `bend` degrees: a shin folds back and a forearm folds forward, which is told
+ from `facing`, the way the character looks along its own axes.
+- **Standing up** blends from the pose the bodies were left in to the one the animation gives, over `recoverTime` seconds.
+- **A bone of its own.** A `RagdollJoint` on a bone's entity gives it no body, or limits of its own in degrees (and a `bend` and `fold` to make any bone a one-way hinge).
+- Select a ragdoll in the editor to see the boxes and the joint limits it would be made of, from the pose its skeleton is in.
+
+It is a passive ragdoll: nothing drives the limbs. Target-device acceptance is recorded separately.
+
## Melee combat
Three facts, and the whole of a combat system is keeping them apart:
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 9aaaa9577..983930794 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
@@ -224,6 +224,50 @@ world.insert(rig, ThirdPersonCamera, { target: player, distance: 420 });
相机会在支点与眼睛之间扫掠物理世界,有实体挡住时把自己拉近。它只移动自己。
</Aside>
+## 第一人称
+
+`FirstPersonController` 在 `CharacterController3D` 里看、走、跳、蹲,和第三人称层一样:它提出请求,物理世界作答。放在身体上,相机作为它的子节点;身体跟着玩家的偏航转,相机跟着俯仰抬。
+
+```typescript
+// 场景里声明的组件。
+world.insert(player, CharacterController3D, { radius: 30, halfHeight: 90 });
+world.insert(player, FirstPersonController, { moveSpeed: 320, jumpSpeed: 420 });
+// ……再在 `player` 的子节点上放一个 Camera。
+```
+
+- **看。** 在 Web 上,第一次点击会拿到指针(`pointerLock`),鼠标转动视角;关掉它则按住鼠标键时才转。触屏上,从屏幕横向 `touchLookFrom` 像素(默认 480)之后开始的手指拖动会转动视角,把左边留给摇杆。小游戏没有指针可拿,靠触摸看。
+- **走。** WASD 或方向键,**Shift** 冲刺,**空格** 跳,**Ctrl** 或 **C** 蹲。速度、冲刺和蹲伏倍率、加速度、空中控制力度都是字段。
+- **蹲** 会用 `crouchHalfHeight` 重新生成胶囊,脚的位置不变:物理世界不能改变角色的大小,所以旧的会先放掉一步。站起来之前先查头顶,没有空间就继续蹲着。
+
+### 视图模型
+
+手持物如果用世界的相机画,会穿墙,还会随广角一起拉伸。放在玩家相机上的 `FirstPersonViewModel` 改用第二台相机来画:在该相机下生成一台,只画你指定的排序层(`layer`,默认 20),有自己的视场角和近裁剪面,画在世界之上、不清除它。玩家的相机则被告知不再画这一层。把手持物放在相机下,把它的渲染器设到这一层。
+
+```typescript
+world.insert(camera, FirstPersonViewModel, { layer: 20, fov: 50, nearPlane: 1 });
+world.insert(weapon, MeshRenderer, { mesh: 'builtin:cube', layer: 20 });
+```
+
+两者都在 `esengine/gameplay` 里。里面没有武器系统、弹道和伤害,也还没有模板;输入读键盘、指针和触屏,不读虚拟摇杆和手柄。
+
+## 布娃娃
+
+蒙皮角色上的 `Ragdoll`,把 `active` 打开,骨头就变成用关节连起来的刚体;关掉,姿态再还给动画。它读角色已有的骨架(蒙皮网格列出的关节),所以除了开关和几个数字,没有别的要设。
+
+```typescript
+world.insert(enemy, Ragdoll, { active: false });
+// 被击倒时:
+world.insert(enemy, Ragdoll, { ...world.get(enemy, Ragdoll), active: true });
+```
+
+- 够长的骨头各得到一个沿骨头方向的盒子,用摆动/扭转关节接到上方最近有盒子的骨头,以动画当帧的姿态生成,所以不会瞬间弹开。动画在下面照常运行,每帧把刚体的姿态盖回去。
+- **限位。** 默认的 `Humanoid` 配置按骨头名字判断它在身体的哪个部位,各取 `swing` 和 `twist` 的一个比例(脊柱硬、肩松、小腿近似铰链)。膝盖和手肘是最多 `bend` 度的单向铰链:小腿向后折,小臂向前折,方向由 `facing`(角色在自己的坐标轴上朝哪边看)决定。
+- **站起来** 会在 `recoverTime` 秒内,从刚体留下的姿态平滑混回动画的姿态。
+- **单根骨头。** 骨头实体上的 `RagdollJoint` 可以让它没有刚体,或者用自己的限位(度数),还能用 `bend` 和 `fold` 把任意骨头变成单向铰链。
+- 在编辑器里选中布娃娃,会按骨架当前的姿态显示它将要生成的盒子和关节限位。
+
+这是被动布娃娃,没有任何东西驱动四肢。目标设备的验收另行记录。
+
## 近战
三件事,把它们分开就是战斗系统的全部:
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index ba5bcd01d..f2b5c9a92 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -169,6 +169,12 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
MeleeAttack: { category: 'physics', summary: 'A swing whose timing is the animation’s and whose reach is the physics world’s: a `hit` beat asks what is around an animated anchor, and gameplay decides who may be hurt.', doc: 'gameplay/physics-3d', anchor: 'melee-combat', anchorZh: '近战' },
Hunter: { category: 'physics', summary: 'A character that hunts what it perceives: it asks navigation for a route, the character controller for the movement, and the animator for a swing — the concrete twin of ThirdPersonController.', doc: 'gameplay/ai/overview', anchor: 'a-melee-enemy-without-writing-one', anchorZh: '不用写代码的近战敌人' },
Health: { category: 'physics', summary: 'What something has left, and what makes it damageable at all — written only by the system that answers the Damage bus.', doc: 'gameplay/physics-3d', anchor: 'melee-combat', anchorZh: '近战' },
+ Ragdoll: { category: 'physics', summary: 'Turns a skinned character\'s bones into jointed bodies while active, with limits by part of the body and one-way knees and elbows, and blends back to the animation when it is switched off.', doc: 'gameplay/physics-3d', anchor: 'ragdoll', anchorZh: '布娃娃' },
+ RagdollJoint: { category: 'physics', summary: 'What the author says of one bone of a ragdoll: no body of its own, or limits (and a one-way bend) of its own.', doc: 'gameplay/physics-3d', anchor: 'ragdoll', anchorZh: '布娃娃' },
+ FirstPersonController: { category: 'physics', summary: 'Looks, walks, jumps and crouches in a CharacterController3D from the keyboard, the pointer and the touch screen, through a camera on a child.', doc: 'gameplay/physics-3d', anchor: 'first-person', anchorZh: '第一人称' },
+ FirstPersonViewModel: { category: 'physics', summary: 'On the player\'s camera: draws what is held with a second camera over the world\'s, with its own field of view and near plane, so it does not go through walls.', doc: 'gameplay/physics-3d', anchor: 'a-view-model', anchorZh: '视图模型' },
+ PathFollower: { category: 'graphics', summary: 'Moves its entity along the Spline of another at a steady speed, once, round or back and forth, turning to face along it if asked.', doc: null },
+ TerrainBand2D: { category: 'graphics', summary: 'A 2D ground drawn along the Spline of the same entity: a filled body, a lip along the surface with an optional image, and an optional chain collider.', doc: null },
SwingTwistJoint3D: { category: 'physics', summary: 'A ball joint with independent twist limits, an elliptical swing cone and optional angular velocity motors.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },
SixDOFJoint3D: { category: 'physics', summary: 'Locks, limits or frees each translation and rotation axis independently, with optional velocity motors.', doc: 'gameplay/physics-3d', anchor: 'joints', 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: '关节' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index ae01ab129..23eb8331d 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -1574,6 +1574,237 @@
}
]
},
+ {
+ "name": "FirstPersonController",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "moveSpeed",
+ "type": "number",
+ "default": "320",
+ "range": "≥ 0"
+ },
+ {
+ "key": "sprintMultiplier",
+ "type": "number",
+ "default": "1.6",
+ "range": "≥ 1, step 0.05"
+ },
+ {
+ "key": "crouchMultiplier",
+ "type": "number",
+ "default": "0.5",
+ "range": "0–1, step 0.05"
+ },
+ {
+ "key": "acceleration",
+ "type": "number",
+ "default": "2400",
+ "range": "≥ 0",
+ "advanced": true
+ },
+ {
+ "key": "deceleration",
+ "type": "number",
+ "default": "3200",
+ "range": "≥ 0",
+ "advanced": true
+ },
+ {
+ "key": "airControl",
+ "type": "number",
+ "default": "0.3",
+ "range": "0–1, step 0.05",
+ "advanced": true
+ },
+ {
+ "key": "jumpSpeed",
+ "type": "number",
+ "default": "420",
+ "doc": "Upward speed a jump starts with. 0 = cannot jump.",
+ "range": "≥ 0"
+ },
+ {
+ "key": "lookSensitivity",
+ "type": "number",
+ "default": "0.12",
+ "range": "≥ 0, step 0.01"
+ },
+ {
+ "key": "touchSensitivity",
+ "type": "number",
+ "default": "0.2",
+ "range": "≥ 0, step 0.01"
+ },
+ {
+ "key": "pitchMin",
+ "type": "number",
+ "default": "-85",
+ "range": "-90–0"
+ },
+ {
+ "key": "pitchMax",
+ "type": "number",
+ "default": "85",
+ "range": "0–90"
+ },
+ {
+ "key": "eyeHeight",
+ "type": "number",
+ "default": "70",
+ "doc": "Where the eye is above the character's centre when standing."
+ },
+ {
+ "key": "crouchEyeHeight",
+ "type": "number",
+ "default": "28"
+ },
+ {
+ "key": "crouchHalfHeight",
+ "type": "number",
+ "default": "45",
+ "doc": "The capsule's half height when crouched. The standing one is the character controller's own.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "eyeSpeed",
+ "type": "number",
+ "default": "400",
+ "range": "≥ 0",
+ "advanced": true
+ },
+ {
+ "key": "camera",
+ "type": "Entity",
+ "default": "none",
+ "doc": "The camera that looks, under this entity. Empty is the first child that carries one."
+ },
+ {
+ "key": "pointerLock",
+ "type": "boolean",
+ "default": "true",
+ "doc": "Take the pointer for looking once the player clicks, instead of looking while a button is held."
+ },
+ {
+ "key": "touchLook",
+ "type": "boolean",
+ "default": "true",
+ "doc": "Look by dragging a finger on the right of the screen."
+ },
+ {
+ "key": "touchLookFrom",
+ "type": "number",
+ "default": "480",
+ "doc": "How far across the screen, in pixels, a finger must start to look. The left is left for a stick.",
+ "range": "≥ 0"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ },
+ {
+ "key": "yaw",
+ "type": "number",
+ "default": "0",
+ "advanced": true
+ },
+ {
+ "key": "pitch",
+ "type": "number",
+ "default": "0",
+ "advanced": true
+ },
+ {
+ "key": "crouching",
+ "type": "boolean",
+ "default": "false",
+ "readonly": true
+ },
+ {
+ "key": "standHalfHeight",
+ "type": "number",
+ "default": "0",
+ "readonly": true
+ },
+ {
+ "key": "eye",
+ "type": "number",
+ "default": "-1",
+ "readonly": true
+ },
+ {
+ "key": "rebuild",
+ "type": "number",
+ "default": "0",
+ "readonly": true
+ }
+ ],
+ "animatable": [
+ "moveSpeed",
+ "sprintMultiplier",
+ "crouchMultiplier",
+ "acceleration",
+ "deceleration",
+ "airControl",
+ "jumpSpeed",
+ "lookSensitivity",
+ "touchSensitivity",
+ "pitchMin",
+ "pitchMax",
+ "eyeHeight",
+ "crouchEyeHeight",
+ "crouchHalfHeight",
+ "eyeSpeed",
+ "camera",
+ "touchLookFrom",
+ "yaw",
+ "pitch",
+ "standHalfHeight",
+ "eye",
+ "rebuild"
+ ]
+ },
+ {
+ "name": "FirstPersonViewModel",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "layer",
+ "type": "number",
+ "default": "20",
+ "doc": "The sorting layer the held thing is on: put it on its renderers, under this camera.",
+ "range": "0–31"
+ },
+ {
+ "key": "fov",
+ "type": "number",
+ "default": "60",
+ "doc": "The held thing's own field of view, so it does not stretch with a wide view of the world.",
+ "range": "1–170"
+ },
+ {
+ "key": "nearPlane",
+ "type": "number",
+ "default": "1",
+ "doc": "How close it may come before it is cut, so it can be held against a wall without going through it.",
+ "range": "≥ 0.01"
+ },
+ {
+ "key": "farPlane",
+ "type": "number",
+ "default": "1000",
+ "range": "≥ 1",
+ "advanced": true
+ }
+ ],
+ "animatable": [
+ "layer",
+ "fov",
+ "nearPlane",
+ "farPlane"
+ ]
+ },
{
"name": "FixedJoint2D",
"source": "ts",
@@ -3972,6 +4203,66 @@
}
]
},
+ {
+ "name": "PathFollower",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "spline",
+ "type": "Entity",
+ "default": "-1",
+ "doc": "The entity that holds the Spline to follow."
+ },
+ {
+ "key": "speed",
+ "type": "number",
+ "default": "4",
+ "doc": "World units a second along the curve. Negative runs it backwards."
+ },
+ {
+ "key": "distance",
+ "type": "number",
+ "default": "0",
+ "doc": "How far along the curve it has gone, in world units. Set it to start part-way along.",
+ "range": "≥ 0"
+ },
+ {
+ "key": "mode",
+ "type": "enum",
+ "default": "Loop",
+ "doc": "What it does at the end of the curve: stop, go round again, or turn back.",
+ "values": [
+ "Once",
+ "Loop",
+ "Ping-pong"
+ ]
+ },
+ {
+ "key": "orient",
+ "type": "enum",
+ "default": "None",
+ "doc": "Whether it turns to face the way it is going: about y for a 3D walker, about z for a 2D sprite.",
+ "values": [
+ "None",
+ "Face along (XZ)",
+ "Face along (XY)"
+ ]
+ },
+ {
+ "key": "playing",
+ "type": "boolean",
+ "default": "true",
+ "doc": "Whether it is moving. A follower set to Once stops itself at the end."
+ }
+ ],
+ "animatable": [
+ "spline",
+ "speed",
+ "distance",
+ "mode",
+ "orient"
+ ]
+ },
{
"name": "Perceiver",
"source": "ts",
@@ -4543,6 +4834,162 @@
"blendDistance"
]
},
+ {
+ "name": "Ragdoll",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "active",
+ "type": "boolean",
+ "default": "false",
+ "doc": "Whether the character is limp. Turn it on when it is knocked down, off to stand it up."
+ },
+ {
+ "key": "skin",
+ "type": "Entity",
+ "default": "none",
+ "doc": "The entity that holds the skinned mesh, whose joints are the skeleton. Empty looks on this entity and then below it."
+ },
+ {
+ "key": "profile",
+ "type": "enum",
+ "default": "Humanoid",
+ "doc": "Uniform gives every joint the same limits. Humanoid gives each the share of them its part of a body has, read from the bone's name: a spine stiff, a shoulder loose, a shin almost a hinge.",
+ "values": [
+ "Uniform",
+ "Humanoid"
+ ]
+ },
+ {
+ "key": "swing",
+ "type": "number",
+ "default": "100",
+ "doc": "How far a limb may swing from its bone's line, in degrees. With the humanoid profile, the most a loose joint (a shoulder, a hip) is given.",
+ "range": "0–175"
+ },
+ {
+ "key": "twist",
+ "type": "number",
+ "default": "60",
+ "doc": "How far a limb may twist about its own line, in degrees. With the humanoid profile, the most a loose joint is given.",
+ "range": "0–175"
+ },
+ {
+ "key": "bend",
+ "type": "number",
+ "default": "130",
+ "doc": "How far a knee or an elbow may bend, in degrees, and only one way: a shin folds back, a forearm folds forward. 0 leaves them swinging like any other joint. Humanoid profile only.",
+ "range": "0–175"
+ },
+ {
+ "key": "facing",
+ "type": "enum",
+ "default": "+Z",
+ "doc": "Which of its own axes the character looks along. It is what tells a knee from a hyperextended one.",
+ "values": [
+ "+Z",
+ "-Z",
+ "+X",
+ "-X"
+ ]
+ },
+ {
+ "key": "thickness",
+ "type": "number",
+ "default": "0.25",
+ "doc": "A limb's thickness as a fraction of its length.",
+ "range": "0.01–2"
+ },
+ {
+ "key": "minBoneLength",
+ "type": "number",
+ "default": "0.05",
+ "doc": "A bone shorter than this gets no body of its own (a finger, a toe): its parent carries it.",
+ "range": "≥ 0"
+ },
+ {
+ "key": "friction",
+ "type": "number",
+ "default": "0.5",
+ "range": "≥ 0"
+ },
+ {
+ "key": "recoverTime",
+ "type": "number",
+ "default": "0.4",
+ "doc": "Seconds to blend from the limp pose back to the animation once the ragdoll is turned off.",
+ "range": "≥ 0"
+ }
+ ],
+ "animatable": [
+ "skin",
+ "profile",
+ "swing",
+ "twist",
+ "bend",
+ "facing",
+ "thickness",
+ "minBoneLength",
+ "friction",
+ "recoverTime"
+ ]
+ },
+ {
+ "name": "RagdollJoint",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "body",
+ "type": "boolean",
+ "default": "true",
+ "doc": "Whether this bone gets a body of its own. Off, the bone above carries it."
+ },
+ {
+ "key": "custom",
+ "type": "boolean",
+ "default": "false",
+ "doc": "Use the limits below instead of the ones the ragdoll's profile gives this joint."
+ },
+ {
+ "key": "swing",
+ "type": "number",
+ "default": "70",
+ "doc": "How far the limb may swing from its bone's line, in degrees, either way.",
+ "range": "0–175"
+ },
+ {
+ "key": "twist",
+ "type": "number",
+ "default": "40",
+ "doc": "How far the limb may twist about its own line, in degrees, either way.",
+ "range": "0–175"
+ },
+ {
+ "key": "bend",
+ "type": "number",
+ "default": "0",
+ "doc": "How far it may bend, in degrees, one way only (a knee, an elbow). 0 is an ordinary swing and twist joint.",
+ "range": "0–175"
+ },
+ {
+ "key": "fold",
+ "type": "enum",
+ "default": "As its name says",
+ "doc": "Which way a bend goes where the bone's name does not say.",
+ "values": [
+ "As its name says",
+ "Toward the facing",
+ "Away from the facing"
+ ]
+ }
+ ],
+ "animatable": [
+ "swing",
+ "twist",
+ "bend",
+ "fold"
+ ]
+ },
{
"name": "RainShelter",
"source": "ts",
@@ -6487,6 +6934,77 @@
"layerColor3.a"
]
},
+ {
+ "name": "TerrainBand2D",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "resolution",
+ "type": "number",
+ "default": "16",
+ "doc": "How far apart, along the curve, the outline's points are. Smaller is smoother and costs more triangles.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "depth",
+ "type": "number",
+ "default": "200",
+ "doc": "How far below its lowest point an open spline's fill reaches. A closed spline ignores it.",
+ "range": "≥ 0"
+ },
+ {
+ "key": "tile",
+ "type": "number",
+ "default": "128",
+ "doc": "The length of one repeat of the fill's texture, in world units.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "edgeWidth",
+ "type": "number",
+ "default": "12",
+ "doc": "How wide the lip along the surface is, drawn over the fill. 0 draws none.",
+ "range": "≥ 0"
+ },
+ {
+ "key": "edgeColor",
+ "type": "Color",
+ "default": "#59a633",
+ "doc": "The lip's colour, multiplying the texture under it."
+ },
+ {
+ "key": "edgeTexture",
+ "type": "Asset<texture>",
+ "default": "none",
+ "doc": "An image the lip is drawn with, repeating along the surface. None draws the lip as a flat colour."
+ },
+ {
+ "key": "edgeTile",
+ "type": "number",
+ "default": "64",
+ "doc": "The length of one repeat of the lip's image along the surface, in world units.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "collider",
+ "type": "boolean",
+ "default": "false",
+ "doc": "Give this entity a chain collider along the surface. Add a static Rigidbody2D to make it solid."
+ }
+ ],
+ "animatable": [
+ "resolution",
+ "depth",
+ "tile",
+ "edgeWidth",
+ "edgeColor.r",
+ "edgeColor.g",
+ "edgeColor.b",
+ "edgeColor.a",
+ "edgeTexture",
+ "edgeTile"
+ ]
+ },
{
"name": "Text",
"source": "ts",
diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.ts
index e8d9b707e..dd4642872 100644
--- a/pipeline/src/project/targetSupport.ts
+++ b/pipeline/src/project/targetSupport.ts
@@ -73,7 +73,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>
],
replication: ['Replicated', 'NetGhost'],
gameplay: [
- 'ThirdPersonController', 'ThirdPersonCamera', 'Health', 'MeleeAttack', 'Hunter', 'Playthrough',
+ 'ThirdPersonController', 'ThirdPersonCamera', 'FirstPersonController', 'FirstPersonViewModel', 'Health', 'MeleeAttack', 'Hunter', 'Playthrough',
],
};
diff --git a/sdk/etc/gameplay.api.md b/sdk/etc/gameplay.api.md
index 42a1e0071..66611d21b 100644
--- a/sdk/etc/gameplay.api.md
+++ b/sdk/etc/gameplay.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/gameplay
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 0 beta · 65 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 74 experimental · 0 deprecated
## ATTACK_KEY — const @experimental
```
@@ -43,6 +43,54 @@ y: number
z: number
```
+## FirstPersonController — const @experimental
+```
+ComponentDef<FirstPersonControllerData>
+```
+
+## FirstPersonControllerData — interface @experimental
+```
+acceleration: number
+airControl: number
+camera: number
+crouchEyeHeight: number
+crouchHalfHeight: number
+crouchMultiplier: number
+crouching: boolean
+deceleration: number
+enabled: boolean
+eye: number
+eyeHeight: number
+eyeSpeed: number
+jumpSpeed: number
+lookSensitivity: number
+moveSpeed: number
+pitch: number
+pitchMax: number
+pitchMin: number
+pointerLock: boolean
+rebuild: number
+sprintMultiplier: number
+standHalfHeight: number
+touchLook: boolean
+touchLookFrom: number
+touchSensitivity: number
+yaw: number
+```
+
+## FirstPersonViewModel — const @experimental
+```
+ComponentDef<FirstPersonViewModelData>
+```
+
+## FirstPersonViewModelData — interface @experimental
+```
+farPlane: number
+fov: number
+layer: number
+nearPlane: number
+```
+
## GameplayPlugin — class @experimental
```
build: (app: App) => void
@@ -293,6 +341,11 @@ MoveBasis
(pitch: number, min: number, max: number): number
```
+## crouchAfter — function @experimental
+```
+(crouching: boolean, wantsCrouch: boolean, roomToStand: boolean): boolean
+```
+
## dampFactor — function @experimental
```
(damping: number, dt: number): number
@@ -333,6 +386,11 @@ GameplayPlugin
(world: World, animator: AnimatorControllerAPI | null, attackTrigger: string, dt: number): void
```
+## lookAfter — function @experimental
+```
+(yaw: number, pitch: number, dx: number, dy: number, degreesPerPixel: number, pitchMin: number, pitchMax: number): { yaw: number; pitch: number; }
+```
+
## nearestEntities — function @experimental
```
<D>(world: World, component: ComponentDef<D>, from: { x: number; y: number; }, options?: NearestOptions<D>): NearEntity[]
@@ -353,6 +411,11 @@ GameplayPlugin
(yawDeg: number, pitchDeg: number): Vec3
```
+## pitchRotation — function @experimental
+```
+(pitchDeg: number): { w: number; x: number; y: number; z: number; }
+```
+
## requestMotion — function @experimental
```
(world: World, input: InputState, dt: number, animator?: AnimatorControllerAPI | null): void
@@ -398,6 +461,11 @@ GameplayPlugin
(world: World, input: InputState, queries: Physics3DQueries | null, dt: number): void
```
+## walkDirection — function @experimental
+```
+(stick: { x: number; y: number; }, yaw: number): { x: number; z: number; }
+```
+
## yawOfQuaternion — function @experimental
```
(q: { w: number; y: number; }): number
@@ -408,3 +476,8 @@ GameplayPlugin
(yawDeg: number): { w: number; x: number; y: number; z: number; }
```
+## yawRotation — function @experimental
+```
+(yawDeg: number): { w: number; x: number; y: number; z: number; }
+```
+
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 1c538dddc..d5f27abd6 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5083,6 +5083,7 @@ gamepads: Map<number, PadState>
getGamepadAxis: (axis: number, pad?: number) => number
getGamepadButtonValue: (button: number, pad?: number) => number
getGamepads: () => number[]
+getMouseDelta: () => { x: number; y: number; }
getMousePosition: () => { x: number; y: number; }
getScrollDelta: () => { x: number; y: number; }
getTouch: (id: number) => TouchPoint | null
@@ -5114,6 +5115,8 @@ mouseButtonsPressed: Set<number>
mouseButtonsPressedFixed: Set<number>
mouseButtonsReleased: Set<number>
mouseButtonsReleasedFixed: Set<number>
+mouseDeltaX: number
+mouseDeltaY: number
mouseX: number
mouseY: number
noteKeyDown: (code: string) => void
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 6657a153b..1c87c2a1e 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5091,6 +5091,7 @@ gamepads: Map<number, PadState>
getGamepadAxis: (axis: number, pad?: number) => number
getGamepadButtonValue: (button: number, pad?: number) => number
getGamepads: () => number[]
+getMouseDelta: () => { x: number; y: number; }
getMousePosition: () => { x: number; y: number; }
getScrollDelta: () => { x: number; y: number; }
getTouch: (id: number) => TouchPoint | null
@@ -5122,6 +5123,8 @@ mouseButtonsPressed: Set<number>
mouseButtonsPressedFixed: Set<number>
mouseButtonsReleased: Set<number>
mouseButtonsReleasedFixed: Set<number>
+mouseDeltaX: number
+mouseDeltaY: number
mouseX: number
mouseY: number
noteKeyDown: (code: string) => void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index e2fc03a8e..8b8922598 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -5078,6 +5078,7 @@ gamepads: Map<number, PadState>
getGamepadAxis: (axis: number, pad?: number) => number
getGamepadButtonValue: (button: number, pad?: number) => number
getGamepads: () => number[]
+getMouseDelta: () => { x: number; y: number; }
getMousePosition: () => { x: number; y: number; }
getScrollDelta: () => { x: number; y: number; }
getTouch: (id: number) => TouchPoint | null
@@ -5109,6 +5110,8 @@ mouseButtonsPressed: Set<number>
mouseButtonsPressedFixed: Set<number>
mouseButtonsReleased: Set<number>
mouseButtonsReleasedFixed: Set<number>
+mouseDeltaX: number
+mouseDeltaY: number
mouseX: number
mouseY: number
noteKeyDown: (code: string) => void
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 1eed741e1..11b64a616 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -5078,6 +5078,7 @@ gamepads: Map<number, PadState>
getGamepadAxis: (axis: number, pad?: number) => number
getGamepadButtonValue: (button: number, pad?: number) => number
getGamepads: () => number[]
+getMouseDelta: () => { x: number; y: number; }
getMousePosition: () => { x: number; y: number; }
getScrollDelta: () => { x: number; y: number; }
getTouch: (id: number) => TouchPoint | null
@@ -5109,6 +5110,8 @@ mouseButtonsPressed: Set<number>
mouseButtonsPressedFixed: Set<number>
mouseButtonsReleased: Set<number>
mouseButtonsReleasedFixed: Set<number>
+mouseDeltaX: number
+mouseDeltaY: number
mouseX: number
mouseY: number
noteKeyDown: (code: string) => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 1dbe29294..9d2367b27 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -5085,6 +5085,7 @@ gamepads: Map<number, PadState>
getGamepadAxis: (axis: number, pad?: number) => number
getGamepadButtonValue: (button: number, pad?: number) => number
getGamepads: () => number[]
+getMouseDelta: () => { x: number; y: number; }
getMousePosition: () => { x: number; y: number; }
getScrollDelta: () => { x: number; y: number; }
getTouch: (id: number) => TouchPoint | null
@@ -5116,6 +5117,8 @@ mouseButtonsPressed: Set<number>
mouseButtonsPressedFixed: Set<number>
mouseButtonsReleased: Set<number>
mouseButtonsReleasedFixed: Set<number>
+mouseDeltaX: number
+mouseDeltaY: number
mouseX: number
mouseY: number
noteKeyDown: (code: string) => void
diff --git a/sdk/src/gameplay/FirstPersonController.ts b/sdk/src/gameplay/FirstPersonController.ts
new file mode 100644
index 000000000..207d5ef89
--- /dev/null
+++ b/sdk/src/gameplay/FirstPersonController.ts
@@ -0,0 +1,174 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file FirstPersonController.ts
+ * @brief Looking, walking, jumping and crouching as the one who stands in the world, and a hand-held thing that does not go through walls.
+ *
+ * @details It decides what the player WANTS (where to look, which way to go, whether to jump or crouch) and asks the 3D character controller for it, as the third-person
+ * layer does: it solves no collision and owns no gravity. The body turns about world up with the player's yaw; the camera under it tilts with the pitch.
+ *
+ * Crouching changes the capsule. The physics world has no way to resize a character, so a crouch makes it again at the new height, with the feet where they were, and
+ * standing up first asks whether there is room over the head.
+ *
+ * The view model is a second camera drawn over the first, with a field of view and a near plane of its own, over the layer the held thing is on, so that it neither
+ * stretches with a wide view of the world nor goes through the wall it is held against.
+ */
+import { defineComponent, type ComponentDef } from '../ecs/component';
+import type { Entity } from '../types';
+
+/** The fields of the `FirstPersonController` component. @experimental */
+export interface FirstPersonControllerData {
+ /** Top speed on the ground, world units per second. */
+ moveSpeed: number;
+ /** What the speed is multiplied by while the sprint key is held. */
+ sprintMultiplier: number;
+ /** What the speed is multiplied by while crouched. */
+ crouchMultiplier: number;
+ /** How fast it reaches its speed, units per second squared. */
+ acceleration: number;
+ /** How fast it sheds it when nothing is asked for. */
+ deceleration: number;
+ /** How much of `acceleration` applies while off the ground, 0..1. */
+ airControl: number;
+ /** Upward speed a jump starts with; 0 disables jumping. */
+ jumpSpeed: number;
+ /** Degrees of turn for each pixel the pointer moves. */
+ lookSensitivity: number;
+ /** Degrees of turn for each pixel a finger drags. */
+ touchSensitivity: number;
+ /** The lowest the player may look, in degrees (negative is down). */
+ pitchMin: number;
+ /** The highest the player may look, in degrees. */
+ pitchMax: number;
+ /** Where the eye is above the character's centre when standing, in world units. */
+ eyeHeight: number;
+ /** Where it is when crouched. */
+ crouchEyeHeight: number;
+ /** The capsule's half height when crouched; the standing one is the character controller's own. */
+ crouchHalfHeight: number;
+ /** How fast the eye moves between the two heights, units per second. */
+ eyeSpeed: number;
+ /** The camera that looks: a child of this entity. 0 is the first child that carries a Camera. */
+ camera: Entity;
+ /** Take the pointer for looking once the player clicks (web), instead of looking while a button is held. A mini game has no pointer to take. */
+ pointerLock: boolean;
+ /** Look by dragging a finger on the right of the screen, from `touchLookFrom` pixels across. */
+ touchLook: boolean;
+ touchLookFrom: number;
+ enabled: boolean;
+ /** Where it is looking, in degrees: set them to turn the player (a spawn point, a teleport). */
+ yaw: number;
+ pitch: number;
+ /** Whether it is crouched now; set by the controller. */
+ crouching: boolean;
+ /** The capsule's standing half height, remembered from the character controller the first time it is seen; 0 until then. */
+ standHalfHeight: number;
+ /** Where the eye is now, between the two heights. */
+ eye: number;
+ /** A rebuild of the capsule in progress: 0 none, 1 the old one is let go and the new one made on the next step. */
+ rebuild: number;
+}
+
+/**
+ * A player who looks through a camera and walks, jumps and crouches in a CharacterController3D.
+ *
+ * @experimental
+ */
+export const FirstPersonController: ComponentDef<FirstPersonControllerData> = defineComponent<FirstPersonControllerData>('FirstPersonController', {
+ moveSpeed: 320, sprintMultiplier: 1.6, crouchMultiplier: 0.5, acceleration: 2400, deceleration: 3200, airControl: 0.3, jumpSpeed: 420,
+ lookSensitivity: 0.12, touchSensitivity: 0.2, pitchMin: -85, pitchMax: 85,
+ eyeHeight: 70, crouchEyeHeight: 28, crouchHalfHeight: 45, eyeSpeed: 400,
+ camera: 0 as Entity, pointerLock: true, touchLook: true, touchLookFrom: 480, enabled: true,
+ yaw: 0, pitch: 0, crouching: false, standHalfHeight: 0, eye: -1, rebuild: 0,
+}, {
+ entityFields: ['camera'],
+ readonlyFields: ['crouching', 'standHalfHeight', 'eye', 'rebuild'],
+ fields: {
+ moveSpeed: { min: 0, category: 'Movement' },
+ sprintMultiplier: { min: 1, step: 0.05, category: 'Movement' },
+ crouchMultiplier: { min: 0, max: 1, step: 0.05, category: 'Movement' },
+ acceleration: { min: 0, category: 'Movement', advanced: true },
+ deceleration: { min: 0, category: 'Movement', advanced: true },
+ airControl: { min: 0, max: 1, step: 0.05, category: 'Movement', advanced: true },
+ jumpSpeed: { min: 0, category: 'Movement', tooltip: 'Upward speed a jump starts with. 0 = cannot jump.' },
+ lookSensitivity: { min: 0, step: 0.01, unit: '°/px', category: 'Look' },
+ touchSensitivity: { min: 0, step: 0.01, unit: '°/px', category: 'Look' },
+ pitchMin: { min: -90, max: 0, unit: '°', category: 'Look' },
+ pitchMax: { min: 0, max: 90, unit: '°', category: 'Look' },
+ eyeHeight: { category: 'Body', tooltip: 'Where the eye is above the character\'s centre when standing.' },
+ crouchEyeHeight: { category: 'Body' },
+ crouchHalfHeight: { min: 1, category: 'Body', tooltip: 'The capsule\'s half height when crouched. The standing one is the character controller\'s own.' },
+ eyeSpeed: { min: 0, category: 'Body', advanced: true },
+ camera: { category: 'Look', tooltip: 'The camera that looks, under this entity. Empty is the first child that carries one.' },
+ pointerLock: { category: 'Look', tooltip: 'Take the pointer for looking once the player clicks, instead of looking while a button is held.' },
+ touchLook: { category: 'Look', tooltip: 'Look by dragging a finger on the right of the screen.' },
+ touchLookFrom: { min: 0, category: 'Look', tooltip: 'How far across the screen, in pixels, a finger must start to look. The left is left for a stick.', shownWhen: { field: 'touchLook', values: [1] } },
+ yaw: { category: 'State', advanced: true },
+ pitch: { category: 'State', advanced: true },
+ },
+});
+
+/** The fields of the `FirstPersonViewModel` component. @experimental */
+export interface FirstPersonViewModelData {
+ /** The sorting layer the held thing is on; its entities carry this `layer` on their renderers. */
+ layer: number;
+ /** The view model's own field of view, in degrees. */
+ fov: number;
+ nearPlane: number;
+ farPlane: number;
+}
+
+/**
+ * Put on the player's camera: a second camera is drawn over it, showing only the entities on `layer`, with a field of view and near plane of its own, and the camera is told
+ * not to draw that layer itself. Whatever is held goes under the camera, on the layer.
+ *
+ * @experimental
+ */
+export const FirstPersonViewModel: ComponentDef<FirstPersonViewModelData> = defineComponent<FirstPersonViewModelData>('FirstPersonViewModel', {
+ layer: 20, fov: 60, nearPlane: 1, farPlane: 1000,
+}, {
+ fields: {
+ layer: { min: 0, max: 31, category: 'View model', tooltip: 'The sorting layer the held thing is on: put it on its renderers, under this camera.' },
+ fov: { min: 1, max: 170, unit: '°', category: 'View model', tooltip: 'The held thing\'s own field of view, so it does not stretch with a wide view of the world.' },
+ nearPlane: { min: 0.01, category: 'View model', tooltip: 'How close it may come before it is cut, so it can be held against a wall without going through it.' },
+ farPlane: { min: 1, category: 'View model', advanced: true },
+ },
+});
+
+const DEG2RAD = Math.PI / 180;
+
+/** A turn about world up, as a quaternion. Zero is looking down -z; a positive turn is to the left. */
+export function yawRotation(yawDeg: number): { w: number; x: number; y: number; z: number } {
+ const h = yawDeg * DEG2RAD / 2;
+ return { w: Math.cos(h), x: 0, y: Math.sin(h), z: 0 };
+}
+
+/** A tilt about the camera's own right, as a quaternion. A positive tilt looks up. */
+export function pitchRotation(pitchDeg: number): { w: number; x: number; y: number; z: number } {
+ const h = pitchDeg * DEG2RAD / 2;
+ return { w: Math.cos(h), x: Math.sin(h), y: 0, z: 0 };
+}
+
+/** Where the player looks after the pointer has moved (`dx`, `dy` in pixels, screen down being positive): to the right and up are what the pointer says. */
+export function lookAfter(yaw: number, pitch: number, dx: number, dy: number, degreesPerPixel: number, pitchMin: number, pitchMax: number): { yaw: number; pitch: number } {
+ const turned = yaw - dx * degreesPerPixel;
+ // Kept in -180..180 so a long play does not grow it without end.
+ const wrapped = ((turned + 180) % 360 + 360) % 360 - 180;
+ return { yaw: wrapped, pitch: Math.min(Math.max(pitch - dy * degreesPerPixel, pitchMin), pitchMax) };
+}
+
+/** The ground direction a stick asks for when the player has turned `yaw` degrees: `y` is forward, `x` is right. Zero when centred. */
+export function walkDirection(stick: { x: number; y: number }, yaw: number): { x: number; z: number } {
+ const s = Math.sin(yaw * DEG2RAD), c = Math.cos(yaw * DEG2RAD);
+ // Forward at yaw 0 is -z, and a positive yaw turns it to -x.
+ const x = -s * stick.y + c * stick.x;
+ const z = -c * stick.y - s * stick.x;
+ const length = Math.hypot(x, z);
+ return length < 1e-6 ? { x: 0, z: 0 } : { x: x / length, z: z / length };
+}
+
+/** Whether the player is crouched after this step: crouched if asked to be, and kept down where there is no room to stand. */
+export function crouchAfter(crouching: boolean, wantsCrouch: boolean, roomToStand: boolean): boolean {
+ if (wantsCrouch) return true;
+ return crouching && !roomToStand;
+}
diff --git a/sdk/src/gameplay/GameplayPlugin.ts b/sdk/src/gameplay/GameplayPlugin.ts
index b7515576a..8e69eee34 100644
--- a/sdk/src/gameplay/GameplayPlugin.ts
+++ b/sdk/src/gameplay/GameplayPlugin.ts
@@ -30,6 +30,7 @@ import { Damage, applyDamage, type DamagePayload } from './Health';
import { MeleeAttacks, resolveMeleeHits } from './MeleeAttack';
import { huntTargets } from './Hunter';
import { q } from '../math/quat';
+import { look as lookFirstPerson, move as moveFirstPerson, installViewModels, TouchLook } from './firstPersonSystems';
import type { World } from '../ecs/world';
import type { Entity } from '../types';
import { Playthrough } from '../runtime/playthrough';
@@ -268,6 +269,7 @@ export function updateCameras(
export class GameplayPlugin implements Plugin {
name = 'gameplay';
private offDespawn_: (() => void) | null = null;
+ private offViewModels_: (() => void) | null = null;
/** Per App, not per module: two Apps in one process must not share swings. */
private readonly attacks_ = new MeleeAttacks();
@@ -329,6 +331,23 @@ export class GameplayPlugin implements Plugin {
{ name: 'ThirdPersonControllerSystem' },
), { runIf: playModeOnly });
+ // Looking is a per-frame thing (the pointer moves between steps); walking is asked of the character on the fixed clock, like the third-person layer.
+ const touchLook = new TouchLook();
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [Res(Time), Res(Input)],
+ (time: TimeData, input: InputState) => { lookFirstPerson(world, input, time.delta, touchLook); },
+ { name: 'FirstPersonLookSystem' },
+ ), { runIf: playModeOnly });
+ app.addSystemToSchedule(Schedule.FixedPreUpdate, defineSystem(
+ [Res(Time), Res(Input)],
+ (time: TimeData, input: InputState) => {
+ const queries = app.hasResource(Physics3D) ? app.getResource(Physics3D) : null;
+ moveFirstPerson(world, input, queries, time.fixedDelta);
+ },
+ { name: 'FirstPersonControllerSystem' },
+ ), { runIf: playModeOnly });
+ this.offViewModels_ = installViewModels(app);
+
// After it: what the world allowed. The animator hears this one.
app.addSystemToSchedule(Schedule.FixedPostUpdate, defineSystem(
[Res(Time)],
@@ -354,6 +373,8 @@ export class GameplayPlugin implements Plugin {
cleanup(): void {
this.offDespawn_?.();
this.offDespawn_ = null;
+ this.offViewModels_?.();
+ this.offViewModels_ = null;
lastPointer.clear();
this.attacks_.clear();
}
diff --git a/sdk/src/gameplay/firstPersonSystems.ts b/sdk/src/gameplay/firstPersonSystems.ts
new file mode 100644
index 000000000..aaebb6bce
--- /dev/null
+++ b/sdk/src/gameplay/firstPersonSystems.ts
@@ -0,0 +1,193 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file firstPersonSystems.ts
+ * @brief What a first-person player does each frame: look, ask for a walk, change height, and keep the view model's camera over the world's.
+ */
+import type { App } from '../app/app';
+import { defineSystem, Schedule } from '../ecs/system';
+import { playModeOnly } from '../ecs/env';
+import type { World } from '../ecs/world';
+import type { Entity } from '../types';
+import { Camera, Children, Transform, type ChildrenData, type TransformData } from '../ecs/component';
+import { ClearFlags, ProjectionType } from '../wasm/wasm.generated';
+import type { InputState } from '../input/input';
+import { CharacterController3D, type CharacterController3DData } from '../physics3d/Physics3DComponents';
+import type { Physics3DQueries } from '../physics3d/Physics3DQueries';
+import { Device } from '../device';
+import { approachVelocity } from './ThirdPersonController';
+import {
+ FirstPersonController, FirstPersonViewModel, lookAfter, pitchRotation, walkDirection, yawRotation, crouchAfter,
+ type FirstPersonControllerData, type FirstPersonViewModelData,
+} from './FirstPersonController';
+
+/** The keys a keyboard stands in for a stick with. */
+function stickOf(input: InputState): { x: number; y: number } {
+ const x = ((input.isKeyDown('KeyD') || input.isKeyDown('ArrowRight')) ? 1 : 0) - ((input.isKeyDown('KeyA') || input.isKeyDown('ArrowLeft')) ? 1 : 0);
+ const y = ((input.isKeyDown('KeyW') || input.isKeyDown('ArrowUp')) ? 1 : 0) - ((input.isKeyDown('KeyS') || input.isKeyDown('ArrowDown')) ? 1 : 0);
+ const length = Math.hypot(x, y);
+ return length > 1 ? { x: x / length, y: y / length } : { x, y };
+}
+
+const wantsCrouch = (input: InputState): boolean => input.isKeyDown('ControlLeft') || input.isKeyDown('KeyC');
+
+/** The camera a controller looks through: the one it names, or the first child that carries one. */
+function cameraOf(world: World, entity: Entity, data: FirstPersonControllerData): Entity | null {
+ if (data.camera > 0 && world.valid(data.camera) && world.has(data.camera, Camera)) return data.camera;
+ if (!world.has(entity, Children)) return null;
+ for (const c of (world.get(entity, Children) as ChildrenData).entities) if (world.valid(c) && world.has(c, Camera)) return c;
+ return null;
+}
+
+/** Fingers dragging to look: the ones that began far enough across the screen, and where each was last seen. */
+export class TouchLook {
+ private readonly last_ = new Map<number, { x: number; y: number }>();
+
+ /** How far the looking fingers moved since the last call. */
+ delta(input: InputState, from: number): { x: number; y: number } {
+ let dx = 0, dy = 0;
+ for (const t of input.getTouchesStarted()) if (t.x >= from) this.last_.set(t.id, { x: t.x, y: t.y });
+ for (const t of input.getTouches()) {
+ const was = this.last_.get(t.id);
+ if (!was) continue;
+ dx += t.x - was.x; dy += t.y - was.y;
+ was.x = t.x; was.y = t.y;
+ }
+ for (const t of input.getTouchesEnded()) this.last_.delete(t.id);
+ return { x: dx, y: dy };
+ }
+}
+
+/** Once a frame: where the player is looking, and the body and the camera turned to match. */
+export function look(world: World, input: InputState, dt: number, touch: TouchLook): void {
+ for (const entity of world.getEntitiesWithComponents([FirstPersonController, Transform])) {
+ const data = world.get(entity, FirstPersonController) as FirstPersonControllerData;
+ if (!data.enabled) continue;
+
+ let dx = 0, dy = 0;
+ const locked = data.pointerLock && Device.state().pointerLocked;
+ if (data.pointerLock && !locked && input.isMouseButtonPressed(0)) void Device.pointerLock(true);
+ if (locked || (!data.pointerLock && input.isMouseButtonDown(0))) {
+ const m = input.getMouseDelta();
+ dx += m.x * data.lookSensitivity; dy += m.y * data.lookSensitivity;
+ }
+ if (data.touchLook) {
+ const t = touch.delta(input, data.touchLookFrom);
+ dx += t.x * data.touchSensitivity; dy += t.y * data.touchSensitivity;
+ }
+ const next = lookAfter(data.yaw, data.pitch, dx, dy, 1, data.pitchMin, data.pitchMax);
+
+ // The eye settles toward the height of the stance it is in, a little a frame rather than all at once.
+ const target = data.crouching ? data.crouchEyeHeight : data.eyeHeight;
+ let eye = data.eye < 0 ? target : data.eye;
+ const step = data.eyeSpeed * dt;
+ eye = Math.abs(target - eye) <= step ? target : eye + Math.sign(target - eye) * step;
+
+ world.update(entity, FirstPersonController, (c: FirstPersonControllerData) => { c.yaw = next.yaw; c.pitch = next.pitch; c.eye = eye; });
+ const body = world.get(entity, Transform) as TransformData;
+ const turn = yawRotation(next.yaw);
+ body.rotation.x = turn.x; body.rotation.y = turn.y; body.rotation.z = turn.z; body.rotation.w = turn.w;
+ world.set(entity, Transform, body);
+
+ const eyeEntity = cameraOf(world, entity, data);
+ if (eyeEntity !== null && world.has(eyeEntity, Transform)) {
+ const t = world.get(eyeEntity, Transform) as TransformData;
+ const tilt = pitchRotation(next.pitch);
+ t.rotation.x = tilt.x; t.rotation.y = tilt.y; t.rotation.z = tilt.z; t.rotation.w = tilt.w;
+ t.position.x = 0; t.position.y = eye; t.position.z = 0;
+ world.set(eyeEntity, Transform, t);
+ }
+ }
+}
+
+/** Before the physics step: what the player asks of the character, and the height it asks to be. */
+export function move(world: World, input: InputState, queries: Physics3DQueries | null, dt: number): void {
+ for (const entity of world.getEntitiesWithComponents([FirstPersonController, CharacterController3D])) {
+ const data = world.get(entity, FirstPersonController) as FirstPersonControllerData;
+ if (!data.enabled) continue;
+ const character = world.get(entity, CharacterController3D) as CharacterController3DData;
+ const standHalf = data.standHalfHeight > 0 ? data.standHalfHeight : character.halfHeight;
+
+ // A capsule being made again: it was let go on the last step, and is made at its new height on this one.
+ if (data.rebuild === 1) {
+ world.update(entity, CharacterController3D, (c: CharacterController3DData) => { c.enabled = true; });
+ world.update(entity, FirstPersonController, (c: FirstPersonControllerData) => { c.rebuild = 0; });
+ continue;
+ }
+
+ const body = world.get(entity, Transform) as TransformData;
+ const roomToStand = (): boolean => {
+ if (!queries) return true;
+ // From the top of the crouched capsule, up as far as standing would take it, and a little more.
+ const top = { x: body.worldPosition.x, y: body.worldPosition.y + data.crouchHalfHeight + character.radius, z: body.worldPosition.z };
+ return queries.raycast(top, { x: 0, y: (standHalf - data.crouchHalfHeight) + 2, z: 0 }) === null;
+ };
+ const crouching = crouchAfter(data.crouching, wantsCrouch(input), data.crouching ? roomToStand() : true);
+
+ if (crouching !== data.crouching) {
+ // Feet stay where they are: the centre moves by the change in half height, and the character is made again at the new height.
+ const half = crouching ? data.crouchHalfHeight : standHalf;
+ const shift = half - character.halfHeight;
+ world.update(entity, CharacterController3D, (c: CharacterController3DData) => { c.halfHeight = half; c.enabled = false; });
+ const t = world.get(entity, Transform) as TransformData;
+ t.position.y += shift;
+ world.set(entity, Transform, t);
+ world.update(entity, FirstPersonController, (c: FirstPersonControllerData) => {
+ c.crouching = crouching; c.rebuild = 1; if (c.standHalfHeight <= 0) c.standHalfHeight = standHalf;
+ });
+ continue;
+ }
+ if (data.standHalfHeight <= 0) world.update(entity, FirstPersonController, (c: FirstPersonControllerData) => { c.standHalfHeight = standHalf; });
+
+ const direction = walkDirection(stickOf(input), data.yaw);
+ const speed = data.moveSpeed * (data.crouching ? data.crouchMultiplier : input.isKeyDown('ShiftLeft') ? data.sprintMultiplier : 1);
+ const authority = character.isOnFloor ? 1 : Math.max(0, Math.min(1, data.airControl));
+ const next = approachVelocity({ x: character.velocity.x, z: character.velocity.z }, { x: direction.x * speed, z: direction.z * speed },
+ data.acceleration * authority, data.deceleration * authority, dt);
+ const jumping = data.jumpSpeed > 0 && character.isOnFloor && !data.crouching && 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;
+ });
+ }
+}
+
+/**
+ * Keeps the view model's camera over the player's: one under each camera that carries a `FirstPersonViewModel`, with the field of view, near plane and layer it asks for, and the
+ * player's camera told not to draw that layer.
+ */
+export function installViewModels(app: App): () => void {
+ const world = app.world;
+ const cameras = new Map<Entity, Entity>();
+ const off = world.onDespawn((entity: Entity) => {
+ const own = cameras.get(entity);
+ cameras.delete(entity);
+ if (own !== undefined && world.valid(own)) world.despawn(own);
+ });
+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {
+ for (const entity of world.getEntitiesWithComponents([FirstPersonViewModel, Camera])) {
+ const model = world.get(entity, FirstPersonViewModel) as FirstPersonViewModelData;
+ const mask = (1 << (model.layer & 31)) >>> 0;
+ const parent = world.get(entity, Camera) as { priority: number; cullingMask: number };
+ let child = cameras.get(entity);
+ if (child === undefined || !world.valid(child)) {
+ child = world.spawn('ViewModel');
+ world.insert(child, Transform, {});
+ world.setParent(child, entity);
+ world.insert(child, Camera, {});
+ cameras.set(entity, child);
+ }
+ // The world's camera does not draw what is held; the held thing's camera draws nothing else.
+ const without = (parent.cullingMask & ~mask) >>> 0;
+ if (parent.cullingMask !== without) world.update(entity, Camera, (c: { cullingMask: number }) => { c.cullingMask = without; });
+ const own = world.get(child, Camera) as { projectionType: number; fov: number; nearPlane: number; farPlane: number; priority: number; cullingMask: number; clearFlags: number; isActive: boolean };
+ if (own.projectionType !== ProjectionType.Perspective || own.fov !== model.fov || own.nearPlane !== model.nearPlane || own.farPlane !== model.farPlane || own.cullingMask !== mask
+ || own.priority !== parent.priority + 1 || own.clearFlags !== ClearFlags.Depth || !own.isActive) {
+ world.update(child, Camera, (c: typeof own) => {
+ c.projectionType = ProjectionType.Perspective; c.fov = model.fov; c.nearPlane = model.nearPlane; c.farPlane = model.farPlane; c.cullingMask = mask;
+ c.priority = parent.priority + 1; c.clearFlags = ClearFlags.Depth; c.isActive = true;
+ });
+ }
+ }
+ }, { name: 'FirstPersonViewModelSystem' }), { runIf: playModeOnly });
+ return off;
+}
diff --git a/sdk/src/gameplay/index.ts b/sdk/src/gameplay/index.ts
index f0ba39ff0..73c78155f 100644
--- a/sdk/src/gameplay/index.ts
+++ b/sdk/src/gameplay/index.ts
@@ -22,6 +22,11 @@ export {
type MoveBasis,
} from './ThirdPersonController';
+export {
+ FirstPersonController, FirstPersonViewModel, lookAfter, walkDirection, crouchAfter, yawRotation, pitchRotation,
+ type FirstPersonControllerData, type FirstPersonViewModelData,
+} from './FirstPersonController';
+
export {
ThirdPersonCamera,
orbitOffset,
diff --git a/sdk/src/input/input.ts b/sdk/src/input/input.ts
index 492dcc97a..83a819140 100644
--- a/sdk/src/input/input.ts
+++ b/sdk/src/input/input.ts
@@ -84,6 +84,9 @@ export class InputState {
keysReleased = new Set<string>();
mouseX = 0;
mouseY = 0;
+ /** How far the pointer moved this frame, summed over its events: what a locked pointer has instead of a position. Cleared at the end of the frame. */
+ mouseDeltaX = 0;
+ mouseDeltaY = 0;
mouseButtons = new Set<number>();
mouseButtonsPressed = new Set<number>();
mouseButtonsReleased = new Set<number>();
@@ -131,6 +134,11 @@ export class InputState {
return { x: this.mouseX, y: this.mouseY };
}
+ /** How far the pointer moved this frame. Zero where the host does not say (a mini game has no pointer to lock). */
+ getMouseDelta(): { x: number; y: number } {
+ return { x: this.mouseDeltaX, y: this.mouseDeltaY };
+ }
+
isMouseButtonDown(button: number): boolean {
return this.mouseButtons.has(button);
}
@@ -382,6 +390,8 @@ export class InputState {
this.mouseButtonsReleased.clear();
this.scrollDeltaX = 0;
this.scrollDeltaY = 0;
+ this.mouseDeltaX = 0;
+ this.mouseDeltaY = 0;
this.touchesStarted.clear();
this.touchesEnded.clear();
}
@@ -464,8 +474,10 @@ export function inputEventCallbacks(state: InputState): InputEventCallbacks {
}
else if (state.keysDown.has(code)) state.noteKeyUp(code);
},
- onPointerMove(x, y) {
+ onPointerMove(x, y, dx, dy) {
if (executionOwners.has(state)) return;
+ // Summed before anything can consume the move: a look that follows the pointer is not a click UI should swallow.
+ if (dx !== undefined && dy !== undefined && Number.isFinite(dx) && Number.isFinite(dy)) { state.mouseDeltaX += dx; state.mouseDeltaY += dy; }
// Pointer position tracks the cursor even when consumed so
// gameplay code that reads `getMousePosition()` (e.g. HUD
// cursor rendering) doesn't freeze while the editor is
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index c9868be29..61003a956 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -52,7 +52,8 @@ export interface InputEventCallbacks {
/** Return true to cancel the host default (e.g. browser Tab traversal). */
onKeyDown(code: string): boolean | void;
onKeyUp(code: string): void;
- onPointerMove(x: number, y: number): void;
+ /** `dx` and `dy` are how far the pointer moved since the last event, where the host says (a locked pointer has no position to move, only this). */
+ onPointerMove(x: number, y: number, dx?: number, dy?: number): void;
onPointerDown(button: number, x: number, y: number): void;
onPointerUp(button: number): void;
onWheel(deltaX: number, deltaY: number): void;
diff --git a/sdk/src/platform/web.ts b/sdk/src/platform/web.ts
index 814dd1e93..88cc76fa4 100644
--- a/sdk/src/platform/web.ts
+++ b/sdk/src/platform/web.ts
@@ -214,7 +214,7 @@ class WebPlatformAdapter implements PlatformAdapter {
const onVisibilityChange = () => { if (document.hidden) onBlur(); };
const onMouseMove = (e: Event) => {
const me = e as MouseEvent;
- callbacks.onPointerMove(me.offsetX, me.offsetY);
+ callbacks.onPointerMove(me.offsetX, me.offsetY, me.movementX, me.movementY);
};
const onMouseDown = (e: Event) => {
const me = e as MouseEvent;
diff --git a/sdk/tests/first-person.test.ts b/sdk/tests/first-person.test.ts
new file mode 100644
index 000000000..67cbcd3c4
--- /dev/null
+++ b/sdk/tests/first-person.test.ts
@@ -0,0 +1,187 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
+import { World } from '../src/ecs/world';
+import { Camera, Children, Transform, Parent } from '../src/ecs/component';
+import type { CppRegistry, ESEngineModule } from '../src/wasm';
+import { CharacterController3D } from '../src/physics3d/Physics3DComponents';
+import {
+ FirstPersonController, FirstPersonViewModel, lookAfter, walkDirection, crouchAfter, yawRotation, pitchRotation,
+ type FirstPersonControllerData,
+} from '../src/gameplay/FirstPersonController';
+import { look, move, installViewModels, TouchLook } from '../src/gameplay/firstPersonSystems';
+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';
+
+describe('looking', () => {
+ it('turns right and up as the pointer goes right and up, and keeps the yaw in a turn', () => {
+ // The pointer going right is a positive dx, and up a negative dy.
+ const a = lookAfter(0, 0, 100, -50, 0.1, -85, 85);
+ expect(a.yaw).toBeCloseTo(-10);
+ expect(a.pitch).toBeCloseTo(5);
+ const wrapped = lookAfter(175, 0, -100, 0, 0.1, -85, 85);
+ expect(wrapped.yaw).toBeCloseTo(-175);
+ });
+
+ it('stops at the limits of looking up and down', () => {
+ expect(lookAfter(0, 80, 0, -1000, 0.1, -85, 85).pitch).toBe(85);
+ expect(lookAfter(0, -80, 0, 1000, 0.1, -85, 85).pitch).toBe(-85);
+ });
+
+ it('turns a quaternion that looks where the angles say', () => {
+ // Forward is -z; a quarter turn to the left is -x, and a tilt up is +y.
+ const rotate = (q: { w: number; x: number; y: number; z: number }, v: [number, number, number]) => {
+ const [x, y, z] = v, tx = 2 * (q.y * z - q.z * y), ty = 2 * (q.z * x - q.x * z), tz = 2 * (q.x * y - q.y * x);
+ return [x + q.w * tx + (q.y * tz - q.z * ty), y + q.w * ty + (q.z * tx - q.x * tz), z + q.w * tz + (q.x * ty - q.y * tx)];
+ };
+ const left = rotate(yawRotation(90), [0, 0, -1]);
+ expect(left[0]).toBeCloseTo(-1);
+ const up = rotate(pitchRotation(90), [0, 0, -1]);
+ expect(up[1]).toBeCloseTo(1);
+ });
+});
+
+describe('walking', () => {
+ it('goes the way it faces, and strafes to its right', () => {
+ const forward = walkDirection({ x: 0, y: 1 }, 0);
+ expect(forward.z).toBeCloseTo(-1);
+ const right = walkDirection({ x: 1, y: 0 }, 0);
+ expect(right.x).toBeCloseTo(1);
+ // Turned a quarter to the left, forward is -x and right is -z... that is, +z reversed: right of -x is -z.
+ const turned = walkDirection({ x: 0, y: 1 }, 90);
+ expect(turned.x).toBeCloseTo(-1);
+ expect(turned.z).toBeCloseTo(0, 6);
+ expect(walkDirection({ x: 1, y: 0 }, 90).z).toBeCloseTo(-1);
+ });
+
+ it('is still when nothing is asked, and a unit when it is', () => {
+ expect(walkDirection({ x: 0, y: 0 }, 33)).toEqual({ x: 0, z: 0 });
+ const d = walkDirection({ x: 1, y: 1 }, 40);
+ expect(Math.hypot(d.x, d.z)).toBeCloseTo(1);
+ });
+});
+
+describe('crouching', () => {
+ it('is crouched when asked, and kept down where there is no room to stand', () => {
+ expect(crouchAfter(false, true, true)).toBe(true);
+ expect(crouchAfter(true, false, true)).toBe(false);
+ expect(crouchAfter(true, false, false)).toBe(true);
+ expect(crouchAfter(false, false, false)).toBe(false);
+ });
+});
+
+/** An input that holds the keys it is told to, and a pointer that has moved by what it is told. */
+function fakeInput(keys: string[] = [], mouse = { x: 0, y: 0 }) {
+ const down = new Set(keys);
+ return {
+ isKeyDown: (k: string) => down.has(k),
+ isMouseButtonDown: (b: number) => b === 0,
+ isMouseButtonPressed: () => false,
+ getMouseDelta: () => mouse,
+ getTouches: () => [], getTouchesStarted: () => [], getTouchesEnded: () => [],
+ down,
+ } as never;
+}
+
+describe.skipIf(!HAS_WASM)('a first-person player in the engine world', () => {
+ let engine: ESEngineModule, registry: CppRegistry, world: World;
+ beforeAll(async () => { engine = await loadWasmModule(); });
+ beforeEach(() => { registry = new engine.Registry(); world = new World(); world.connectCpp(registry, engine); });
+ afterEach(() => { for (const e of world.getAllEntities()) world.despawn(e); world.disconnectCpp(); registry.delete(); });
+
+ /** A body with a character controller and a camera under it. */
+ function player(over: Partial<FirstPersonControllerData> = {}) {
+ const body = world.spawn();
+ world.insert(body, Transform);
+ world.insert(body, CharacterController3D, { radius: 30, halfHeight: 90, enabled: true });
+ const cam = world.spawn();
+ world.insert(cam, Transform);
+ world.insert(cam, Camera, {});
+ world.insert(cam, Parent, { entity: body });
+ world.insert(body, FirstPersonController, { pointerLock: false, touchLook: false, ...over });
+ return { body, cam };
+ }
+
+ it('turns its body with the yaw and tilts its camera with the pitch, at the height of its eye', () => {
+ const { body, cam } = player();
+ // The pointer moves 100 right and 100 up, at 0.12 degrees a pixel.
+ look(world, fakeInput([], { x: 100, y: -100 }), 1 / 60, new TouchLook());
+ const d = world.get(body, FirstPersonController) as FirstPersonControllerData;
+ expect(d.yaw).toBeCloseTo(-12);
+ expect(d.pitch).toBeCloseTo(12);
+ const turn = world.get(body, Transform).rotation;
+ expect(turn.y).toBeCloseTo(Math.sin((-12 * Math.PI / 180) / 2), 4);
+ const eye = world.get(cam, Transform);
+ expect(eye.rotation.x).toBeCloseTo(Math.sin((12 * Math.PI / 180) / 2), 4);
+ expect(eye.position.y).toBeCloseTo(70);
+ });
+
+ it('asks the character for a walk the way it faces, faster with sprint and slower crouched', () => {
+ const { body } = player();
+ move(world, fakeInput(['KeyW']), null, 1);
+ const walk = world.get(body, CharacterController3D).velocity;
+ expect(walk.z).toBeLessThan(0);
+ expect(Math.abs(walk.z)).toBeLessThanOrEqual(320 + 1e-6);
+ move(world, fakeInput(['KeyW', 'ShiftLeft']), null, 1);
+ const run = world.get(body, CharacterController3D).velocity;
+ expect(Math.abs(run.z)).toBeGreaterThan(Math.abs(walk.z));
+ });
+
+ it('crouches by making the capsule again at the new height with the feet where they were', () => {
+ const { body } = player();
+ world.update(body, Transform, (t: { position: { y: number } }) => { t.position.y = 100; });
+ move(world, fakeInput(['ControlLeft']), null, 1 / 60);
+ let c = world.get(body, CharacterController3D);
+ let d = world.get(body, FirstPersonController) as FirstPersonControllerData;
+ expect(d.crouching).toBe(true);
+ expect(c.halfHeight).toBe(45);
+ // Let go for one step, and the centre is 45 lower: the feet (centre minus half height) are where they were.
+ expect(c.enabled).toBe(false);
+ expect(d.rebuild).toBe(1);
+ expect(world.get(body, Transform).position.y).toBeCloseTo(55);
+ // The next step makes it again.
+ move(world, fakeInput(['ControlLeft']), null, 1 / 60);
+ c = world.get(body, CharacterController3D);
+ d = world.get(body, FirstPersonController) as FirstPersonControllerData;
+ expect(c.enabled).toBe(true);
+ expect(d.rebuild).toBe(0);
+ });
+
+ it('stands up again when the key is let go, if there is room', () => {
+ const { body } = player();
+ move(world, fakeInput(['ControlLeft']), null, 1 / 60);
+ move(world, fakeInput(['ControlLeft']), null, 1 / 60);
+ move(world, fakeInput([]), null, 1 / 60);
+ expect((world.get(body, FirstPersonController) as FirstPersonControllerData).crouching).toBe(false);
+ expect(world.get(body, CharacterController3D).halfHeight).toBe(90);
+ });
+
+ it('stays down under a low ceiling', () => {
+ const { body } = player();
+ move(world, fakeInput(['ControlLeft']), null, 1 / 60);
+ move(world, fakeInput(['ControlLeft']), null, 1 / 60);
+ const blocked = { raycast: () => ({ distance: 1 }) } as never;
+ move(world, fakeInput([]), blocked, 1 / 60);
+ expect((world.get(body, FirstPersonController) as FirstPersonControllerData).crouching).toBe(true);
+ });
+
+ it('draws what is held by a second camera over the world\'s, and keeps the world\'s from drawing it', () => {
+ const systems: Array<{ _fn: () => void }> = [];
+ installViewModels({ world, addSystemToSchedule: (_s: unknown, def: { _fn: () => void }) => { systems.push(def); } } as never);
+ const { cam } = player();
+ world.insert(cam, FirstPersonViewModel, { layer: 20, fov: 55, nearPlane: 2, farPlane: 800 });
+ for (const s of systems) s._fn();
+ const mask = (1 << 20) >>> 0;
+ const kids = (world.get(cam, Children) as { entities: number[] }).entities;
+ const held = kids.find((k) => world.has(k as never, Camera) && (world.get(k as never, Camera) as { cullingMask: number }).cullingMask === mask)!;
+ expect(held).toBeDefined();
+ const own = world.get(held as never, Camera) as { projectionType: number; fov: number; nearPlane: number; priority: number; clearFlags: number };
+ // Perspective, whatever a new camera starts as.
+ expect(own.projectionType).toBe(0);
+ expect(own.fov).toBeCloseTo(55);
+ expect(own.nearPlane).toBeCloseTo(2);
+ expect(own.priority).toBe((world.get(cam, Camera) as { priority: number }).priority + 1);
+ // Depth only, so the world stays under it.
+ expect(own.clearFlags).toBe(2);
+ expect(((world.get(cam, Camera) as { cullingMask: number }).cullingMask & mask) >>> 0).toBe(0);
+ });
+});
diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjs
index 63422afb9..d7c572f1f 100644
--- a/tools/check-corpus-authoring.mjs
+++ b/tools/check-corpus-authoring.mjs
@@ -134,6 +134,12 @@ const DISPOSITION = {
RectAnchors: ['owed', 'the Cocos importer writes it for a Widget; it arrives in the corpus with the first imported Cocos scene'],
GroupOpacity: ['owed', 'the Cocos importer writes it for a UIOpacity; it arrives in the corpus with the first imported Cocos scene'],
SpringBoneCollider: ['owed', 'no example has a spring-bone chain to keep out of anything; it arrives with the first SpringBone'],
+ FirstPersonController: ['owed', 'no example has a player who walks in the first person yet; the first-person template, when there is one, authors it'],
+ FirstPersonViewModel: ['owed', 'arrives with FirstPersonController in the first-person template; a held thing needs a character to be held by'],
+ PathFollower: ['owed', 'no example moves a thing along a spline yet; a platform or a cart on a track is the first to'],
+ Ragdoll: ['owed', 'no example carries a skinned character that is knocked down yet; the first one with a rigged enemy goes into one'],
+ RagdollJoint: ['owed', 'arrives with the first example that has a Ragdoll, which is the only place a bone needs a say of its own'],
+ TerrainBand2D: ['owed', 'no example draws a 2D ground from a spline yet; the first side-scroller built on one carries it'],
Replicated: ['code-only', 'multiplayer-arena declares its replicated set beside the server systems that own it; the wire table is a contract both ends compile against, not scene content'],
// — owed: a creator-facing component nothing in the shipped corpus authors.
diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjs
index 19cb42304..59cb8e52e 100644
--- a/tools/check-gizmo-coverage.mjs
+++ b/tools/check-gizmo-coverage.mjs
@@ -162,6 +162,12 @@ const DISPOSITION = {
'WaterBody.waveHeight': ['no-place', 'the height of the tallest wave, not a region of the entity'],
'WaterBody.bedDepth': ['renders', 'a river\'s bed is cut into the terrain, which draws it'],
'SpringBone.radius': ['no-place', 'the thickness of the strand, kept clear of the colliders; a margin on each bone, not a region of the root'],
+ 'FirstPersonController.eyeHeight': ['no-place', 'where the camera sits above the character\'s centre; the camera child is the place, and it is selected and drawn as a camera'],
+ 'FirstPersonController.crouchEyeHeight': ['no-place', 'where the camera sits above the centre when crouched; the camera child is the place'],
+ 'FirstPersonController.crouchHalfHeight': ['no-place', 'the half height the character\'s capsule is made again at when crouched; the CharacterController3D beside it draws the standing one'],
+ 'PathFollower.distance': ['no-place', 'how far along the Spline the entity is, a position on a curve the Spline already draws, not a region'],
+ 'TerrainBand2D.depth': ['renders', 'how far down the filled body goes below the surface; the band drawn at it is the outline'],
+ 'TerrainBand2D.edgeWidth': ['renders', 'the thickness of the lip along the surface; the lip drawn at it is the outline'],
'ContentRect.size': ['owed', 'a sprite or text on the entity follows it and is the outline, but a bare rect (a clip box, a hit area) draws nothing yet'],
'Sprite.size': ['renders', 'the sprite drawn at it is the outline'],
'Sprite.tileSize': ['renders', 'the repeat of a drawn sprite'],