FERRETGame engine over Babylon.js
Ferret

@ferret/character

Character movement (capsule, walk, run, jump, steps, slopes), cameras and the player controller.

28 exports · source in packages/character/src

Classes

CameraRig class

class CameraRig

The player's camera: first or third person, switchable at run time. The third-person boom is a spring arm: it is shortened when a wall is in the way, so the camera never clips into the level. Inputs of Babylon's own are removed.

readonly camera: BABYLON.FreeCamera
view: ViewMode
yaw: number
pitch: number
distance: number
currentDistance: numberthe boom length actually used after collision
readonly o: Required<Omit<CameraRigOptions, 'mask'>> & { mask: number }
boom: ExternalBoom | nulla boom fixed on something else than the character (a ride); update uses it in place of the first/third person camera while it is set
constructor(scene: BABYLON.Scene, private physics: PhysicsService, opts: CameraRigOptions = {})
toggleView()
setView(v: ViewMode)
zoom(delta: number)
look(dyaw: number, dpitch: number)
groundForward(out = new BABYLON.Vector3())Forward on the ground plane for the current yaw (what "move forward" means).
groundRight(out = new BABYLON.Vector3())
setBoom(b: ExternalBoom | null)Fix the camera on a boom of its own (or back on the character with null).
blendFromCurrent(duration: number, exp = 2)Start a timed blend from where the camera is now to wherever update puts it (UE: SetViewTargetWithBlend, ease in-out).
get blending()
update(feet: BABYLON.Vector3, dt: number)Place the camera for a rendered frame; feet is the interpolated position of the character.

packages/character/src/camera.ts:46

CharacterBatch class

class CharacterBatch
static of(world: World): CharacterBatch
MIN_STEP_MS: numberbelow this many ms of the characters' steps in one tick the game's thread steps them itself (a message costs more)
costPerChar: number | undefinedthe cost of one character's step in the game's thread (ms), an average of what it took
reason: stringwhy the characters stay in the game's thread now (empty while they go to the workers)
stats: { steps: number; characters: number; pieces: number; rebuilds: number; }
get sched(): Scheduler
add()
remove()
observe(ms: number)the time the game's thread took for one character's own step
worth(): booleanare there enough characters, and workers, to be worth sending (asked every step: cached for the tick)
copy(): Snapshot | nullthe copy of the geometry the workers hold, or null while it cannot be used
send(item: CharItem): Promise<CharOut>queue a character's step: the promise of its answer
dispose()

packages/character/src/batch.ts:13

CharacterMovement class

class CharacterMovement extends Component<CharacterParams>

Capsule character movement against static geometry: walk, run, crouch, jump, step up, slopes, ground snapping, moving platforms. The same component moves the player and NPCs; they differ only in who sets the move input. The entity's node must be a Babylon Mesh (it carries the collision ellipsoid); its origin is at the feet.

p: Required<Omit<CharacterParams, 'groundMask'>> & { groundMask?: string[] }
velocity: Vector3
grounded: boolean
groundNormal: Vector3
groundMesh: BABYLON.AbstractMesh | null
crouching: boolean
running: boolean
submerged: number0..1: the part of the body inside water or mud (capability D); swimming when most of it is and the feet are off the ground
swimming: boolean
yaw: number
flying: booleanflying (UE: MOVE_Flying): no gravity, no ground; the vertical speed follows setVerticalInput times verticalSpeed; the horizontal speed is walk/run speed as on the ground
verticalSpeed: numberm/s at full vertical input in flying mode
prevPosition: Vector3where the body was at the previous fixed step (camera interpolation)
get mesh(): BABYLON.Mesh
get height()
get speed2d()
onAttach()
onDetach()
setMoveInput(dir: BABYLON.Vector3, run = false)Desired movement in world space; its length (0..1) scales the speed. The vertical part is used only while swimming: Unreal swims along the view direction, pitch included.
jump()
setVerticalInput(v: number)Flying mode: -1..1, up positive.
setFlying(on: boolean)Switch flying mode on or off (off: the character falls and lands by the normal rules).
motionState()what an Animator needs to know (see MotionSource in
setCrouch(on: boolean)
shift(d: BABYLON.Vector3): BABYLON.Vector3Move the capsule horizontally by d now, with collisions and step-ups, outside the velocity model (room-scale VR: the player walked in the room). Returns the distance actually moved.
teleport(pos: BABYLON.Vector3)
onFixedUpdate(dt: number)
wantsAsync(): booleanthe component class has work for the workers now (cheap: the world asks every step); a component that registers itself in world.asyncComponents is asked
onFixedUpdateAsync(dt: number): Promise<() => void> | nullthe character's step in a worker: its numbers go now, the result is put back when all the world's components have had their turn; null: it is stepped here
renderPosition(alpha: number, out = new BABYLON.Vector3())The interpolated position for the render frame (the camera follows this).

packages/character/src/movement.ts:72

PlayerController class

class PlayerController extends Component<PlayerParams>

The player controller: input actions -> movement and camera. First and third person; the third-person body faces where it moves, the first-person body faces where the camera looks.

viewOverride: ViewOverride | nullAnother owner of the view (a VR headset: the head owns the camera). While it is set, the controller does not move or aim the camera rig, look / turn are left to the owner, and "forward" is yaw().
rig: CameraRig
movement: CharacterMovement
onAttach()
get view(): ViewMode
setView(v: ViewMode)
toggleView()
onFixedUpdate(dt: number)
onUpdate(dt: number)
onDetach()

packages/character/src/player.ts:42

Functions

easeInOut function

function easeInOut(a: number, exp = 2): number

UE's FMath::InterpEaseInOut(0, 1, a, exp): slow at both ends.

packages/character/src/camera.ts:7

shiftCharacter function

function shiftCharacter(s: CharState, p: CharP, w: CharWorld, d: V3, want: number): void

the same walk without a step's worth of the rest: a move by d outside the velocity model (room-scale VR)

packages/character/src/step.ts:287

spawnCharacter function

function spawnCharacter(world: World, name: string, position: BABYLON.Vector3, params: CharacterParams & { layer?: string } = {}): SpawnedCharacter

A character entity: an invisible Mesh with the collision ellipsoid, a Collider on the Pawn layer and CharacterMovement. In a level docked into a parent game that holds the role player the parent's character is returned instead of a new one; with no dock nothing differs.

packages/character/src/movement.ts:271

stepCharacter function

function stepCharacter(s: CharState, p: CharP, w: CharWorld, dt: number): CharEvent[]

One fixed step. The state is changed in place; the events (jump, land) are returned for the caller to emit.

packages/character/src/step.ts:143

stepInWorld function

function stepInWorld(item: CharItem, st: Record<string, unknown>): CharOut

one character's step in a world held by st

packages/character/src/kernels-babylon.ts:24

Interfaces

CameraRigOptions interface

interface CameraRigOptions
view?: ViewMode
eyeHeight?: numbermetres above the feet where the eyes are (first person) and the boom pivots (third person)
distance?: numberthird person: distance behind the pivot, and its limits for zoom
minDistance?: number
maxDistance?: number
shoulder?: numberthird person: sideways offset of the pivot (over the shoulder)
pitchMin?: number
pitchMax?: number
probe?: numberthird person: radius kept free between the camera and the walls
mask?: numberlayers the spring arm collides with

packages/character/src/camera.ts:24

CharacterParams interface

interface CharacterParams

Parameters follow UE's Character Movement Component, in metres and seconds.

radius?: number
height?: number
crouchHeight?: number
eyeHeight?: number
walkSpeed?: number
runSpeed?: number
crouchSpeed?: number
jumpVelocity?: numberinitial vertical speed of a jump (UE: JumpZVelocity)
gravity?: number
mass?: numberkg: how much push a character has against water or mud (capability D), with thrust
bodyDensity?: numberkg/m³: below the density of the water it floats, above it sinks (people are about 985)
thrust?: numberm/s²: the push the character can make against drag in a medium (swimming, wading); the speed it reaches there follows from it
swimSpeed?: numberm/s: UE MaxSwimSpeed. Set, a character in a dense medium (swimming) moves at exactly this speed whatever the walk, run or crouch state, as Unreal's swimming mode does; unset, the speed follows from thrust and the drag
buoyancy?: numberUE Buoyancy: 1 = neutral (the weight is carried completely in the medium), below 1 sinks, above 1 rises. Unset: the density ratio medium / bodyDensity decides
outOfWaterZ?: numberUE OutofWaterZ, m/s: the upward speed of the water jump (swimming against a ledge, the input pointing up)
jumpOutOfWaterPitch?: numberUE JumpOutOfWaterPitch, degrees: the water jump needs the swim input to point at least this far above the horizon
maxOutOfWaterStepHeight?: numberUE MaxOutOfWaterStepHeight, m: how far above the body's centre the ledge may be for a water jump
swimAcceleration?: numberm/s²: UE MaxAcceleration while swimming (the push along the 3D swim input)
fluidFriction?: numberUE PhysicsVolume FluidFriction (0.3 by default) of the water; with BrakingDecelerationSwimming 0 a stopped swimmer coasts by it times BrakingFrictionFactor 2
maxWindAccel?: numberm/s²: the most the wind (the flow service) can push the character; 0 turns the wind off for it (a game's cap)
maxStepHeight?: number
walkableAngle?: numbersteepest slope that can be walked, degrees (UE: WalkableFloorAngle)
acceleration?: number
braking?: number
airControl?: numberfraction of the ground acceleration available in the air
snapDistance?: numberhow far below the feet the ground is still "ground" when walking down
groundMask?: string[]layer names the character collides with when probing the ground
faceMovement?: booleanturn the body to face where it moves (third person); first person sets the yaw from the camera
turnRate?: number
flyAcceleration?: numberflying mode: m/s²: how fast the vertical speed follows setVerticalInput

packages/character/src/movement.ts:9

CharHit interface

interface CharHit
point: V3
normal: V3
ref: unknown

packages/character/src/step.ts:20

CharItem interface

interface CharItem
dt: number
s: CharPlain
p: CharP
mask: number
pull?: number
wind: V3 | null

packages/character/src/kernels-babylon.ts:17

CharOut interface

interface CharOut
s: CharPlain
events: CharEvent[]

packages/character/src/kernels-babylon.ts:18

CharPlain interface

interface CharPlain

a character's state as numbers (what goes to the worker and comes back)

pos: V3
velocity: V3
groundNormal: V3
moveDir: V3
grounded: boolean
crouching: boolean
running: boolean
yaw: number
flying: boolean
verticalSpeed: number
verticalInput: number
leavingWater: boolean
jumpQueued: boolean
wantCrouch: boolean
submerged: number
swimming: boolean
ground: numberthe index in the world's list of the mesh the character stands on (-1: none)

packages/character/src/kernels-babylon.ts:10

CharState interface

interface CharState

a character's state between steps (the numbers; the ground it stands on is groundRef, kept by the side that knows the meshes)

pos: V3
velocity: V3
groundNormal: V3
grounded: boolean
crouching: boolean
running: boolean
yaw: number
flying: boolean
verticalSpeed: number
verticalInput: number
moveDir: V3
leavingWater: boolean
jumpQueued: boolean
wantCrouch: boolean
submerged: number
swimming: boolean
groundRef: unknownwhatever the world's raycast gave as the ground's reference (a mesh here, an index in a worker)

packages/character/src/step.ts:14

CharWorld interface

interface CharWorld

the world a character moves in

raycast(origin: V3, dir: V3, length: number): CharHit | nullthe first hit of a ray on the ground layers (the mask is the world's)
sweep(pos: V3, d: V3): voidmove the ellipsoid from pos by d with collisions and slide; pos ends where the body does
setBody(height: number): voidthe body's height changed (crouch or stand): the ellipsoid follows
platform?(): { shift: V3; turn: number } | nullwhat the character stands on moved or turned since the last step: the shift of its position and the turn of its yaw (only the game's thread knows)
column(pos: V3, height: number): { fraction: number; medium: Medium | null } | nullthe medium the column of the body is in (null: none)
pull(pos: V3): number | undefinedthe pull of gravity at a point, m/s² (undefined: the character's own value)
wind(pos: V3, bodyHeight: number): [number, number, number] | nullthe wind at a point, if the wind pushes characters here

packages/character/src/step.ts:23

ExternalBoom interface

interface ExternalBoom

A boom on a point of the game's own (a mount's seat): UE's spring arm with camera lag and an absolute rotation.

pivot: () => BABYLON.Vector3where the boom is fixed, world space, metres (read every frame)
arm: numberboom length, metres
socketZ?: numberlift of the camera above the boom's end (UE: SocketOffset.Z), metres
lag?: numbercamera lag speed (UE: CameraLagSpeed); 0 = no lag

packages/character/src/camera.ts:13

Medium interface

interface Medium
density: number
flow: [number, number, number]

packages/character/src/step.ts:21

PlayerActions interface

interface PlayerActions

The names of the game's actions that the controller reads. Anything left out is simply not used.

move?: string
look?: string
turn?: string
jump?: string
run?: string
crouch?: string
view?: string
zoom?: string

packages/character/src/player.ts:9

PlayerParams interface

interface PlayerParams
actions?: PlayerActions
camera?: CameraRigOptions
turnSpeed?: numberrad/s at full turn
alwaysRun?: booleana console has no run button: run when the stick is fully pushed, or always
bodyInFirstPerson?: booleanfirst person: show the body (arms/legs)
body?: BABYLON.AbstractMesh[]meshes that make up the visible body; hidden in first person unless bodyInFirstPerson

packages/character/src/player.ts:20

ViewOverride interface

interface ViewOverride
yaw(): numberthe yaw "move forward" follows, radians

packages/character/src/player.ts:33

Types

CharEvent type

type CharEvent = { kind: 'jump' } | { kind: 'land'; speed: number }

packages/character/src/step.ts:39

CharP type

type CharP = Required<Omit<CharacterParams, 'groundMask'>> & { groundMask?: string[] }

packages/character/src/step.ts:11

SpawnedCharacter type

type SpawnedCharacter = { entity: Entity; movement: CharacterMovement; mesh: BABYLON.Mesh }

packages/character/src/movement.ts:265

ViewMode type

type ViewMode = 'first' | 'third'

packages/character/src/camera.ts:4

Constants

SKIN const

const SKIN: 0.01

packages/character/src/step.ts:9

STEP_KERNEL const

const STEP_KERNEL: "character.step"

packages/character/src/batch.ts:10