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 character moves on the animation's terms, and the world still answers

esenginec9600455fd5c
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 1252e4da3..652094030 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 · 1578 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1581 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2495,6 +2495,11 @@ ScreenScalingData
{ readonly viewProjection: Float32Array<ArrayBuffer>; readonly vpX: 0; readonly vpY: 0; readonly vpW: 0; readonly vpH: 0; readonly screenW: 0; readonly screenH: 0; readonly worldLeft: 0; readonly worldBottom: 0; readonly worldRight: 0; readonly worldTop: 0; readonly worldMouseX: 0; readonly worldMouseY: 0; readonly valid: false; }
```
+## DODGE_KEY — const @experimental
+```
+"ShiftLeft"
+```
+
## DOMAIN_SCRIPTS — const @experimental
```
"scripts"
@@ -8217,6 +8222,11 @@ number
"timeline"
```
+## TPC_DODGE — const @experimental
+```
+"dodge"
+```
+
## TPC_GROUNDED — const @experimental
```
"grounded"
@@ -12068,7 +12078,7 @@ PrefabsPlugin
## q — const @experimental
```
-{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }
+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; scaled(a: Quat, t: number): Quat; }
```
## quat — const @experimental
@@ -12356,6 +12366,11 @@ ReplicationPlugin
(assets: AssetsData | null | undefined, ref: string): ResolvedTileset | undefined
```
+## rootMotionVelocity — function @experimental
+```
+(delta: { x: number; z: number; }, seconds: number): { x: number; z: number; }
+```
+
## rotateFlagsCW — function @experimental
```
(flags: TileFlags): TileFlags
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index d53821829..2a32d11a7 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 · 1597 experimental · 3 deprecated
+Symbols: 113 public · 89 beta · 1600 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2503,6 +2503,11 @@ ScreenScalingData
{ readonly viewProjection: Float32Array<ArrayBuffer>; readonly vpX: 0; readonly vpY: 0; readonly vpW: 0; readonly vpH: 0; readonly screenW: 0; readonly screenH: 0; readonly worldLeft: 0; readonly worldBottom: 0; readonly worldRight: 0; readonly worldTop: 0; readonly worldMouseX: 0; readonly worldMouseY: 0; readonly valid: false; }
```
+## DODGE_KEY — const @experimental
+```
+"ShiftLeft"
+```
+
## DOMAIN_SCRIPTS — const @experimental
```
"scripts"
@@ -8410,6 +8415,11 @@ number
"timeline"
```
+## TPC_DODGE — const @experimental
+```
+"dodge"
+```
+
## TPC_GROUNDED — const @experimental
```
"grounded"
@@ -12311,7 +12321,7 @@ PrefabsPlugin
## q — const @experimental
```
-{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }
+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; scaled(a: Quat, t: number): Quat; }
```
## quat — const @experimental
@@ -12599,6 +12609,11 @@ ReplicationPlugin
(assets: AssetsData | null | undefined, ref: string): ResolvedTileset | undefined
```
+## rootMotionVelocity — function @experimental
+```
+(delta: { x: number; z: number; }, seconds: number): { x: number; z: number; }
+```
+
## rotateFlagsCW — function @experimental
```
(flags: TileFlags): TileFlags
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 3ab0cebd3..2f5338b9e 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 · 1577 experimental · 3 deprecated
+Symbols: 113 public · 86 beta · 1580 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2490,6 +2490,11 @@ ScreenScalingData
{ readonly viewProjection: Float32Array<ArrayBuffer>; readonly vpX: 0; readonly vpY: 0; readonly vpW: 0; readonly vpH: 0; readonly screenW: 0; readonly screenH: 0; readonly worldLeft: 0; readonly worldBottom: 0; readonly worldRight: 0; readonly worldTop: 0; readonly worldMouseX: 0; readonly worldMouseY: 0; readonly valid: false; }
```
+## DODGE_KEY — const @experimental
+```
+"ShiftLeft"
+```
+
## DOMAIN_SCRIPTS — const @experimental
```
"scripts"
@@ -8212,6 +8217,11 @@ number
"timeline"
```
+## TPC_DODGE — const @experimental
+```
+"dodge"
+```
+
## TPC_GROUNDED — const @experimental
```
"grounded"
@@ -12073,7 +12083,7 @@ PrefabsPlugin
## q — const @experimental
```
-{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }
+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; scaled(a: Quat, t: number): Quat; }
```
## quat — const @experimental
@@ -12361,6 +12371,11 @@ ReplicationPlugin
(assets: AssetsData | null | undefined, ref: string): ResolvedTileset | undefined
```
+## rootMotionVelocity — function @experimental
+```
+(delta: { x: number; z: number; }, seconds: number): { x: number; z: number; }
+```
+
## rotateFlagsCW — function @experimental
```
(flags: TileFlags): TileFlags
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index f82353e59..249859e28 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 · 1599 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1602 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2490,6 +2490,11 @@ ScreenScalingData
{ readonly viewProjection: Float32Array<ArrayBuffer>; readonly vpX: 0; readonly vpY: 0; readonly vpW: 0; readonly vpH: 0; readonly screenW: 0; readonly screenH: 0; readonly worldLeft: 0; readonly worldBottom: 0; readonly worldRight: 0; readonly worldTop: 0; readonly worldMouseX: 0; readonly worldMouseY: 0; readonly valid: false; }
```
+## DODGE_KEY — const @experimental
+```
+"ShiftLeft"
+```
+
## DOMAIN_SCRIPTS — const @experimental
```
"scripts"
@@ -8458,6 +8463,11 @@ number
"timeline"
```
+## TPC_DODGE — const @experimental
+```
+"dodge"
+```
+
## TPC_GROUNDED — const @experimental
```
"grounded"
@@ -12330,7 +12340,7 @@ PrefabsPlugin
## q — const @experimental
```
-{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }
+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; scaled(a: Quat, t: number): Quat; }
```
## quat — const @experimental
@@ -12618,6 +12628,11 @@ ReplicationPlugin
(assets: AssetsData | null | undefined, ref: string): ResolvedTileset | undefined
```
+## rootMotionVelocity — function @experimental
+```
+(delta: { x: number; z: number; }, seconds: number): { x: number; z: number; }
+```
+
## rotateFlagsCW — function @experimental
```
(flags: TileFlags): TileFlags
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index a145f27f5..5657c03bf 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 · 1589 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1592 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2490,6 +2490,11 @@ ScreenScalingData
{ readonly viewProjection: Float32Array<ArrayBuffer>; readonly vpX: 0; readonly vpY: 0; readonly vpW: 0; readonly vpH: 0; readonly screenW: 0; readonly screenH: 0; readonly worldLeft: 0; readonly worldBottom: 0; readonly worldRight: 0; readonly worldTop: 0; readonly worldMouseX: 0; readonly worldMouseY: 0; readonly valid: false; }
```
+## DODGE_KEY — const @experimental
+```
+"ShiftLeft"
+```
+
## DOMAIN_SCRIPTS — const @experimental
```
"scripts"
@@ -8219,6 +8224,11 @@ number
"timeline"
```
+## TPC_DODGE — const @experimental
+```
+"dodge"
+```
+
## TPC_GROUNDED — const @experimental
```
"grounded"
@@ -12096,7 +12106,7 @@ PrefabsPlugin
## q — const @experimental
```
-{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }
+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; conjugate(a: Quat): Quat; rotate(a: Quat, v: Vec3): Vec3; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; rotationTo(from: Vec3, to: Vec3): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; scaled(a: Quat, t: number): Quat; }
```
## quat — const @experimental
@@ -12384,6 +12394,11 @@ ReplicationPlugin
(assets: AssetsData | null | undefined, ref: string): ResolvedTileset | undefined
```
+## rootMotionVelocity — function @experimental
+```
+(delta: { x: number; z: number; }, seconds: number): { x: number; z: number; }
+```
+
## rotateFlagsCW — function @experimental
```
(flags: TileFlags): TileFlags
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 8bd28762e..46d7e06ec 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -877,6 +877,7 @@ export {
ThirdPersonCamera,
TPC_SPEED,
TPC_GROUNDED,
+ TPC_DODGE,
desiredDirection,
approachVelocity,
facingYaw,
@@ -888,7 +889,9 @@ export {
orbitOffset,
dampFactor,
clampPitch,
+ rootMotionVelocity,
WORLD_BASIS,
+ DODGE_KEY,
type ThirdPersonControllerData,
type ThirdPersonCameraData,
type MoveBasis,
diff --git a/sdk/src/gameplay/GameplayPlugin.ts b/sdk/src/gameplay/GameplayPlugin.ts
index 26c372f02..38bc144de 100644
--- a/sdk/src/gameplay/GameplayPlugin.ts
+++ b/sdk/src/gameplay/GameplayPlugin.ts
@@ -21,12 +21,16 @@ import { CharacterController3D, type CharacterController3DData } from '../physic
import { Physics3D } from '../physics3d/Physics3DPlugin';
import type { Physics3DQueries } from '../physics3d/Physics3DQueries';
import { Animator, AnimatorController, type AnimatorControllerAPI } from '../animation/Animator';
+import {
+ AnimatorRootMotion, type AnimatorRootMotionData,
+} from '../animation/animatorRootMotion';
+import { q } from '../math/quat';
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,
+ desiredDirection, approachVelocity, facingYaw, turnToward, rootMotionVelocity,
+ yawQuaternion, yawOfQuaternion, WORLD_BASIS, DODGE_KEY, type MoveBasis,
} from './ThirdPersonController';
import {
ThirdPersonCamera, type ThirdPersonCameraData,
@@ -36,6 +40,19 @@ import {
/** Animator parameters this controller writes. Names, not clips. */
export const TPC_SPEED = 'speed';
export const TPC_GROUNDED = 'grounded';
+/** The trigger a dodge press sets. Whether any state answers it is the graph's. */
+export const TPC_DODGE = 'dodge';
+
+/**
+ * What the animation is asking this character to do, or null when nothing is.
+ * Presence of the component is the opt-in and `active` is the switch — "the
+ * delta is non-zero" is not, being false in the still moment inside a dodge.
+ */
+function rootMotionRequest(world: World, entity: Entity): AnimatorRootMotionData | null {
+ if (!world.has(entity, AnimatorRootMotion)) return null;
+ const data = world.get(entity, AnimatorRootMotion) as AnimatorRootMotionData;
+ return data.active ? data : null;
+}
/** The stick, from the keys a keyboard stands in for one with. */
function readStick(input: InputState): { x: number; y: number } {
@@ -60,27 +77,44 @@ function basisFor(world: World, data: ThirdPersonControllerData): MoveBasis {
* 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 {
+export function requestMotion(
+ world: World, input: InputState, dt: number,
+ animator: AnimatorControllerAPI | null = null,
+): void {
for (const entity of world.getEntitiesWithComponents([ThirdPersonController, CharacterController3D])) {
const data = world.get(entity, ThirdPersonController) as ThirdPersonControllerData;
if (!data.enabled) continue;
+ if (animator && world.has(entity, Animator) && input.isKeyPressed(DODGE_KEY)) {
+ animator.setTrigger(entity, TPC_DODGE);
+ }
+
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,
- );
+ // Which of the two states the character's movement: the stick, or the
+ // animation that declared itself in charge. Chosen HERE and not by the
+ // animator, which states a request and never a position.
+ const driven = rootMotionRequest(world, entity);
+ let next: { x: number; z: number };
+ if (driven) {
+ next = rootMotionVelocity(driven.deltaPosition, driven.deltaTime);
+ } else {
+ 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));
+ 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
+ // it stays 0, which the character controller reads as "walk". Not while an
+ // animation is driving: two things setting the vertical is one too many.
+ const jumping = !driven && data.jumpSpeed > 0 && character.isOnFloor
&& (input.isKeyPressed('Space') || input.isKeyDown('Space'));
world.update(entity, CharacterController3D, (c: CharacterController3DData) => {
@@ -110,14 +144,33 @@ export function observeMotion(world: World, animator: AnimatorControllerAPI | nu
animator.setBool(entity, TPC_GROUNDED, character.isOnFloor);
}
+ if (!world.has(entity, Transform)) continue;
+
+ // While an animation is driving, the heading is the animation's too —
+ // turning to face the motion as well would be a second author of the
+ // yaw, and the two disagree the moment a dodge goes sideways.
+ const driven = rootMotionRequest(world, entity);
+ if (driven) {
+ if (driven.deltaTime <= 0) continue;
+ // This step's share of the frame's turn: the animator states one per
+ // rendered frame, and this runs once per fixed step inside it.
+ const step = q.scaled(driven.deltaRotation, Math.min(dt / driven.deltaTime, 1));
+ world.update(entity, Transform, (t: TransformData) => {
+ const turned = q.normalize(q.mul(t.rotation, step));
+ t.rotation.w = turned.w; t.rotation.x = turned.x;
+ t.rotation.y = turned.y; t.rotation.z = turned.z;
+ });
+ continue;
+ }
+
// 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;
+ if (speed < data.idleThreshold) 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;
+ const yaw = yawQuaternion(turned);
+ t.rotation.w = yaw.w; t.rotation.x = yaw.x; t.rotation.y = yaw.y; t.rotation.z = yaw.z;
});
}
}
@@ -213,7 +266,9 @@ export class GameplayPlugin implements Plugin {
app.addSystemToSchedule(Schedule.FixedPreUpdate, defineSystem(
[Res(Time), Res(Input)],
(time: TimeData, input: InputState) => {
- requestMotion(world, input, time.fixedDelta);
+ const animator = app.hasResource(AnimatorController)
+ ? app.getResource(AnimatorController) : null;
+ requestMotion(world, input, time.fixedDelta, animator);
},
{ name: 'ThirdPersonControllerSystem' },
), { runIf: playModeOnly });
diff --git a/sdk/src/gameplay/ThirdPersonController.ts b/sdk/src/gameplay/ThirdPersonController.ts
index 3e8e911ca..e8a276d38 100644
--- a/sdk/src/gameplay/ThirdPersonController.ts
+++ b/sdk/src/gameplay/ThirdPersonController.ts
@@ -20,6 +20,9 @@ import { defineComponent, type ComponentDef } from '../ecs/component';
import type { Entity } from '../types';
import type { Vec3 } from '../types';
+/** The key a dodge is asked for on; the animator decides whether there is one. */
+export const DODGE_KEY = 'ShiftLeft';
+
/** The fields of the `ThirdPersonController` component. @experimental */
export interface ThirdPersonControllerData {
/** Top speed on the ground, world units per second. */
@@ -139,6 +142,18 @@ export function shortestAngleDelta(from: number, to: number): number {
return delta;
}
+/**
+ * The velocity a root-motion request comes to over the seconds it covers. A RATE,
+ * because the animator states one per rendered frame while the character steps on
+ * its own clock: adding the displacement moves twice on a frame with two steps.
+ */
+export function rootMotionVelocity(
+ delta: { x: number; z: number }, seconds: number,
+): { x: number; z: number } {
+ if (seconds <= 0) return { x: 0, z: 0 };
+ return { x: delta.x / seconds, z: delta.z / seconds };
+}
+
/**
* 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.
diff --git a/sdk/src/gameplay/index.ts b/sdk/src/gameplay/index.ts
index f8d4b3634..663cb3fd3 100644
--- a/sdk/src/gameplay/index.ts
+++ b/sdk/src/gameplay/index.ts
@@ -7,9 +7,11 @@ export {
facingYaw,
shortestAngleDelta,
turnToward,
+ rootMotionVelocity,
yawQuaternion,
yawOfQuaternion,
WORLD_BASIS,
+ DODGE_KEY,
type ThirdPersonControllerData,
type MoveBasis,
} from './ThirdPersonController';
@@ -28,6 +30,7 @@ export {
gameplayPlugin,
TPC_SPEED,
TPC_GROUNDED,
+ TPC_DODGE,
requestMotion,
observeMotion,
updateCameras,
diff --git a/sdk/src/math/quat.ts b/sdk/src/math/quat.ts
index 822a08c1b..72e3de7ca 100644
--- a/sdk/src/math/quat.ts
+++ b/sdk/src/math/quat.ts
@@ -154,4 +154,20 @@ export const q = {
/** The Z turn of a 2D rotation, in radians. */
angleZ(a: Pick<Quat, 'z' | 'w'>): number { return 2 * Math.atan2(a.z, a.w); },
+
+ /**
+ * The same turn, `t` of the way through it — the shortest arc, so a rotation
+ * stored as -q scales the short way round rather than the long one. What a
+ * caller handed one frame's worth of turn needs to spend it over two steps.
+ */
+ scaled(a: Quat, t: number): Quat {
+ const n = this.normalize(a);
+ const sign = n.w < 0 ? -1 : 1;
+ const w = Math.min(1, n.w * sign);
+ const sin = Math.sqrt(Math.max(0, 1 - w * w));
+ if (sin < 1e-8) return { w: 1, x: 0, y: 0, z: 0 };
+ const half = Math.acos(w) * t;
+ const k = (Math.sin(half) / sin) * sign;
+ return { w: Math.cos(half), x: n.x * k, y: n.y * k, z: n.z * k };
+ },
};
diff --git a/sdk/tests/thirdPerson.test.ts b/sdk/tests/thirdPerson.test.ts
index 8040be42c..7d88a391a 100644
--- a/sdk/tests/thirdPerson.test.ts
+++ b/sdk/tests/thirdPerson.test.ts
@@ -7,13 +7,17 @@
import { describe, it, expect } from 'vitest';
import {
ThirdPersonController, ThirdPersonCamera, requestMotion, observeMotion, updateCameras,
- TPC_SPEED, TPC_GROUNDED, cameraGroundBasis, desiredDirection, approachVelocity,
- facingYaw, turnToward,
+ TPC_SPEED, TPC_GROUNDED, TPC_DODGE, cameraGroundBasis, desiredDirection, approachVelocity,
+ facingYaw, turnToward, rootMotionVelocity, DODGE_KEY,
type ThirdPersonControllerData, type ThirdPersonCameraData,
} from '../src/gameplay';
import { CharacterController3D, type CharacterController3DData } from '../src/physics3d/Physics3DComponents';
-import { Animator, AnimatorControllerAPI, type AnimatorData } from '../src/animation';
+import {
+ Animator, AnimatorControllerAPI, AnimatorRootMotion,
+ type AnimatorData, type AnimatorRootMotionData,
+} from '../src/animation';
import { Transform, type TransformData } from '../src/ecs/component';
+import { q } from '../src/math/quat';
const PLAYER = 1;
const CAMERA = 2;
@@ -282,3 +286,137 @@ describe('the pure decisions', () => {
expect(turnToward(170, -170, 60, 0.1)).toBeCloseTo(176, 6);
});
});
+
+// =============================================================================
+// An animation that drives the character
+// =============================================================================
+
+/** Give the player a root-motion request of `delta` over `seconds`. */
+function asksToMove(
+ world: any, delta: { x: number; y: number; z: number },
+ seconds: number, turnDeg = 0, active = true,
+): void {
+ world.insert(PLAYER, AnimatorRootMotion, {
+ enabled: true,
+ active,
+ deltaPosition: { ...delta },
+ deltaRotation: q.axis('y', (turnDeg * Math.PI) / 180),
+ deltaTime: seconds,
+ } as AnimatorRootMotionData);
+}
+
+describe('a root-motion request becomes a rate', () => {
+ it('is the displacement over the seconds it covers', () => {
+ expect(rootMotionVelocity({ x: 2, z: -6 }, 0.5)).toEqual({ x: 4, z: -12 });
+ });
+
+ it('is nothing at all when it covers no time', () => {
+ expect(rootMotionVelocity({ x: 2, z: -6 }, 0)).toEqual({ x: 0, z: 0 });
+ });
+});
+
+describe('while an animation is driving', () => {
+ it('the character controller is asked for the animation, not the stick', () => {
+ const world = scene(0);
+ asksToMove(world, { x: 0, y: 0, z: -0.2 }, 1 / 60);
+ // A full stick the other way: if it reached the controller at all, the
+ // sign of x would show it.
+ requestMotion(world, stubInput(['KeyD']), 1 / 60);
+
+ const v = askedVelocity(world);
+ expect(v.z).toBeCloseTo(-12, 5);
+ expect(v.x).toBeCloseTo(0, 6);
+ });
+
+ it('and the stick is back in charge the moment it stops', () => {
+ const world = scene(0);
+ asksToMove(world, { x: 0, y: 0, z: -0.2 }, 1 / 60, 0, false);
+ requestMotion(world, stubInput(['KeyD']), 1 / 60);
+ expect(askedVelocity(world).x).toBeCloseTo(4, 5);
+ });
+
+ it('a jump is refused, so nothing else is setting the vertical', () => {
+ const world = scene(0, { jumpSpeed: 5 });
+ asksToMove(world, { x: 0, y: 0, z: -0.2 }, 1 / 60);
+ requestMotion(world, stubInput(['Space']), 1 / 60);
+ expect(askedVelocity(world).y).toBe(0);
+ });
+
+ it('the request still moves no transform of its own', () => {
+ const world = scene(0);
+ asksToMove(world, { x: 0, y: 0, z: -0.2 }, 1 / 60);
+ const before = { ...(world.get(PLAYER, Transform) as TransformData).position };
+ requestMotion(world, stubInput([]), 1 / 60);
+ expect((world.get(PLAYER, Transform) as TransformData).position).toEqual(before);
+ });
+
+ it('what the animator hears is still what the world allowed', () => {
+ const world = scene(0);
+ const animator = new AnimatorControllerAPI();
+ asksToMove(world, { x: 0, y: 0, z: -0.2 }, 1 / 60);
+ requestMotion(world, stubInput([]), 1 / 60);
+
+ // The request is large and the wall gave nothing back.
+ expect(askedVelocity(world).z).toBeCloseTo(-12, 5);
+ observeMotion(world, animator, 1 / 60);
+ expect(animator.getFloat(PLAYER, TPC_SPEED)).toBe(0);
+ });
+
+ it('the heading is the animation’s turn, spent over the steps of its frame', () => {
+ const world = scene(0);
+ const animator = new AnimatorControllerAPI();
+ // One rendered frame's worth of turn, consumed by two fixed steps.
+ asksToMove(world, { x: 0, y: 0, z: -0.2 }, 1 / 30, 90);
+ observeMotion(world, animator, 1 / 60);
+ observeMotion(world, animator, 1 / 60);
+
+ const rotation = (world.get(PLAYER, Transform) as TransformData).rotation;
+ expect(q.toEuler(rotation)[1]).toBeCloseTo(90, 4);
+ });
+
+ it('and the character does not also turn to face where it went', () => {
+ const world = scene(0);
+ const animator = new AnimatorControllerAPI();
+ // Moving hard along -X, which turn-to-face would answer with a quarter turn.
+ world.update(PLAYER, CharacterController3D, (c: CharacterController3DData) => {
+ c.realVelocity.x = -4;
+ });
+ asksToMove(world, { x: -0.2, y: 0, z: 0 }, 1 / 60, 0);
+ observeMotion(world, animator, 1 / 60);
+
+ const rotation = (world.get(PLAYER, Transform) as TransformData).rotation;
+ expect(q.toEuler(rotation)[1]).toBeCloseTo(0, 6);
+ });
+});
+
+describe('asking for a dodge', () => {
+ /** Idle until something sets the trigger; the controller names no state. */
+ const graph = {
+ parameters: [{ name: TPC_DODGE, type: 'trigger' as const }],
+ initialState: 'Idle',
+ states: [
+ {
+ name: 'Idle',
+ transitions: [{ to: 'Dodge', conditions: [{ param: TPC_DODGE, op: 'trigger' as const }] }],
+ },
+ { name: 'Dodge', transitions: [] },
+ ],
+ };
+
+ function press(keys: string[]): string {
+ const world = scene(0);
+ const animator = new AnimatorControllerAPI();
+ animator.registerController('x', graph);
+ requestMotion(world, stubInput(keys), 1 / 60, animator);
+ animator.update(world, 1 / 60);
+ return (world.get(PLAYER, Animator) as AnimatorData).currentState;
+ }
+
+ it('lets the graph decide there is one', () => {
+ expect(press([DODGE_KEY])).toBe('Dodge');
+ });
+
+ it('and stays put when nobody asked', () => {
+ expect(press([])).toBe('Idle');
+ });
+});