Docs / The frame loop
Camera
Camera is an eye in the world: a position in meters, a yaw and a pitch, and the view matrix that follows from them. Pair it with simd_float4x4(perspectiveFovY:aspectRatio:nearZ:depthRange:) for the projection, and you have everything a frame needs to know about where it is looking from. For a view from behind the character, use OrbitCamera.
The Camera type
public nonisolated struct Camera: Sendable, Equatable { public var position: SIMD3<Float> // meters, Y is up public var yaw: Float // radians, 0 looks down -Z, positive turns left public var pitch: Float // radians, positive looks up public var tuning: Tuning // speeds and sensitivities public init(position: SIMD3<Float> = .zero, yaw: Float = 0, pitch: Float = 0, tuning: Tuning = Tuning()) }
Orientation is yaw and pitch with no roll. Pitch is clamped to Camera.pitchLimit, 89 degrees: at exactly 90 the look direction is parallel to world up, the right vector is undefined, and the image snaps. Yaw is kept wrapped to (-π, π] by Float.wrappedAngle(_:), because a session spinning steadily for an hour would otherwise reach angles a 32-bit float cannot resolve finely. Both hold however the angles are set — camera.pitch += recoil is clamped, camera.yaw += turned is wrapped.
The basis comes from those two angles:
| Property | What it is |
|---|---|
forward | The look direction. |
right | Horizontal only, so strafing never drifts up or down while looking at the sky. |
up | right × forward. |
viewMatrix | World space to view space. Right-handed: the camera looks down -Z, so anything in front of it has a negative view-space Z. |
An eye, not a body
advance(_:deltaTime:) flies along the look direction, through anything. That is right for an editor, a photo mode, or a game that genuinely flies. A game with feet moves a CharacterController instead and puts the camera at its eye — see character-controller. Walking is along the ground plane, not the look direction, which is why the two are separate types.
advance takes a MovementInput — axes rather than key names, so a stick or a replay can drive it as easily as a keyboard. Its direction is clamped to length 1, not normalized: two keys at once are not faster than one, and a stick pushed a third of the way goes a third as fast. Speeds are the camera's tuning.walkSpeed (6 m/s) and tuning.sprintSpeed (18 m/s).
camera.advance(MovementInput(forward: 1, strafe: 0, vertical: 0, isSprinting: false),
deltaTime: deltaTime)
Looking: mouse and stick are different quantities
There are two look methods, and mixing them up ruins the feel of one or the other.
look(mouseDelta:)is not scaled by time. A mouse delta is a displacement the player already made; scaling it by frame duration would make the same hand movement turn further on a slow frame.turn(rate:deltaTime:)is scaled by time. A stick reports a held position, which is a rate: hold it twice as long and you turn twice as far.
Sensitivities are tuning.lookSensitivity (0.0022 radians per unit of mouse movement) and tuning.stickLookSpeed (3.2 radians per second at full deflection) — your game's to change, per camera. A player's own sensitivity goes on top, through input.
Reversed-Z, with an infinite far plane
public extension simd_float4x4 { init(perspectiveFovY fovY: Float, aspectRatio: Float, nearZ: Float, depthRange: ClosedRange<Float> = 0...1) }
fovY is the vertical field of view in radians; Float.radians(fromDegrees:) converts.
This projection maps the near plane to depth 1 and infinite distance to depth 0 — the opposite of the conventional near-0, far-1. Depth is stored as floating point, and floats hold far more precision near zero, so the conventional mapping spends almost all of it in the first few meters and leaves the far field to z-fight. Reversed, the precision is where the distance is.
The far plane is gone, not merely large: depth approaches 0 asymptotically, so there is no view distance to tune and nothing to clip against at range. One consequence shows up in culling: a Ductane frustum has five planes, not six.
Three things must agree, so the engine owns them
Reversed-Z needs the projection, the depth compare function and the depth clear value to agree, and a mismatch renders nothing at all rather than rendering badly. So:
| Piece | Where it comes from |
|---|---|
| The projection | simd_float4x4(perspectiveFovY:aspectRatio:nearZ:depthRange:) |
Compare .greater (nearer is now larger) | FrameRenderer.makeDepthStencilState() |
| Clear to 0 | FrameRenderer.reversedZClearDepth |
Use all three and they cannot disagree.
Reversed-Z means larger is nearer. Any depth arithmetic you write yourself — a depth range, a bias, a comparison in a shader — has to read it that way round.
A slice of the depth buffer
depthRange confines the projection to part of the depth buffer, for drawing something held in the player's hands with its own field of view and in front of the world. 0...1, the default, is the whole buffer; 0.9...1 is the front tenth. Because depth is reversed, depthRange.upperBound is the near end.
How the sample drives it
The sample keeps two cameras — the last simulation step's and this one's — and blends between them for display, so motion stays smooth when the display and the simulation run at different rates (see fixed-timestep). Camera.interpolated(from:to:alpha:) takes yaw the short way across the ±π seam, so turning from 179° to -179° is 2° of movement, not 358°.
// Each simulation step previousCamera = camera camera.turn(rate: input.lookRate * settings.stickLookScale, deltaTime: deltaTime) // Each frame let view = Camera.interpolated(from: previousCamera, to: camera, alpha: interpolation) let projection = simd_float4x4( perspectiveFovY: Float.radians(fromDegrees: 70), aspectRatio: aspectRatio, nearZ: 0.1) let viewProjection = simd_mul(projection, view.viewMatrix)
Mouse look goes through camera.look(mouseDelta:) as events arrive. The sample's view also adds a head bob and a slide's dip to the displayed camera only, never to camera itself — the view moves, the aim does not.
A third-person camera
OrbitCamera sits behind a character and looks at it: it orbits a point on the character, follows it, keeps out of the scenery, and eases itself back behind the character while the player runs and does not steer.
public nonisolated struct OrbitCamera: Sendable, Equatable { public var focus: SIMD3<Float> // what it looks at, before the shoulder offset: the character's feet public var yaw: Float // radians, 0 looks down -Z, positive turns left, as Camera's public var pitch: Float // radians, positive raises the camera, so the view looks down public var distance: Float // what the player asked for, in meters public var shoulderHeight: Float // the aim point's height above the focus public var fieldOfView: Float // radians, vertical; 45° by default public var tuning: Tuning // ranges, easing times, and how it keeps clear public init(tuning: Tuning = Tuning()) }
Once a simulation step, after the character has moved:
camera.orbit(byYaw: look.x, pitch: look.y) // the player's hands
camera.zoom(by: -scroll * 0.05)
camera.follow(controller.feet, deltaTime: deltaTime)
camera.recentre(behind: facing, deltaTime: deltaTime, active: runningForward)
camera.keepClear(of: surroundings, deltaTime: deltaTime)
And each frame, between the last two steps:
let view = OrbitCamera.interpolated(from: previousCamera, to: camera, alpha: interpolation) let viewProjection = simd_mul(view.projectionMatrix(aspect: aspectRatio), view.viewMatrix)
Movement follows it: groundForward and groundRight are the camera's facing flattened onto the ground, which is what "forward" means in a third-person game.
Keeping out of the scenery
keepClear(of:deltaTime:) asks the same CharacterController.Surroundings the body walks in — see character-controller — so a pillar that stops the body also stops the camera. Solids are tested by their footprints, meshes by their triangles, and the ground by marching the camera's line, so a hill behind the character is found rather than only the ground under its feet. The camera is treated as a ball of tuning.probeRadius (0.4 m), so it stops short of a wall instead of on it, and is never pulled nearer than tuning.minimumDistance (0.8 m).
It pulls in at once and eases back out over tuning.recoveryHalfLife (0.6 s). Easing in would let a wall through the near plane first; snapping out would lurch every time the character clears a doorway. The player's zoom is never changed by it: the scenery's limit is kept apart from distance, so squeezing past a pillar does not leave the camera closer afterwards. OrbitCamera.allowedDistance(aimPoint:direction:desired:in:tuning:) is the question on its own.
Over the shoulder
Set shoulderOffset (meters, to the camera's right; 0 by default) and the whole orbit moves sideways: the camera looks past the character's right shoulder, the character sits left of centre, and the middle of the screen — where a shot goes — is clear of their back. The orbit stays a turn about that offset point, so the character holds its place on screen as the camera swings. A wall at the shoulder takes the offset in at once and lets it out over tuning.recoveryHalfLife, as the distance is (shoulderClearance, workingShoulderOffset); shoulder is the point over the character before the offset.
var camera = OrbitCamera(tuning: OrbitCamera.Tuning(distanceRange: 1.8...5, restingDistance: 2.5))
camera.shoulderOffset = 0.55
A shooter that aims down the camera usually does not ease the camera back behind the character either: there the camera is the aim. Leave recentre(behind:deltaTime:active:) out.
Easing back behind the character
recentre(behind:deltaTime:active:) brings the yaw, pitch and zoom back to rest after tuning.recentreWait (0.5 s) with no look input. A new camera opens at rest — tuning.restingPitch and tuning.restingDistance — so the first view is the one it comes home to. Pass active from the movement input — running roughly forwards and not steering — never from the character's facing: a character turns to face where it moves, so its facing agrees with a strafe, and recentring during one turns the camera, which turns "forward", which turns the character, in a slow involuntary circle.
The resting pitch and the field of view are one decision. What the player sees is where the horizon falls: the view's centre is pitch below it, so (pitch + fov/2) / fov of the frame is ground. The defaults, 7° at 45°, give the ground two thirds and put the horizon a third of the way down; 12° at 45° would fill three quarters with ground. Change one, and judge the other again.
Facing where the character goes
CharacterFacing turns the character the player is looking at. Give it the same movement input and the camera's yaw each step:
facing.turn(toward: axis, viewYaw: camera.yaw, deltaTime: deltaTime)
let pace = facing.backpedalled(runSpeed, axis: axis, minimum: walkClipSpeed)
It turns toward the movement over tuning.turnHalfLife (0.05 s), the short way round. Backing away keeps it facing forward: it faces the strafe and the forward part of the input, mirrored, so a strafe rolls into a backpedal without a flip, and isBackpedaling says when to run the stride backwards. Set isHeld for the length of an attack, so a swing thrown while strafing does not twist back to the strafe; the feet still move. backpedalled(_:axis:minimum:) makes backing away slower, 60% by default and in proportion to how backward the input is, because at full speed backing away from a foe while hitting it is free.
Shaking it when something lands
CameraShake is trauma: blows add to a 0…1 value that time bleeds away, and the camera moves by its square, so small hits stay a tremor and none stack into a screen nobody can read. took(force:) shakes, for a blow taken; landed(force:towards:) punches the camera toward what was hit and settles, for a blow landed. A force is 0…1 — map your game's kinds of hit onto it rather than passing damage, so a balance change cannot rebalance the camera.
shake.advance(by: deltaTime) // once a step let shaken = view.viewMatrix * simd_float4x4(translation: -shake.offset) // the view only, never the aim
Its distances are in meters, set for OrbitCamera's default framing: a half-force blow taken moves about 1% of the screen's height, a full one about 5%. Frame the camera differently and judge them again, in fractions of the screen.
Both views in one game
A game with a first-person view to fight and a third-person view to be seen keeps a Camera at the body's eye and an OrbitCamera on its feet, and draws through whichever is in use. Their yaws mean the same, so either can be handed the other's when the view switches; their pitches are opposite in sign.
Gotchas
MovementInputhas an explicit public initializer, so you can construct one from outside the module.Float.shortestAngle(from:to:)is the signed shortest turn between two yaws — whatCamera.interpolated(from:to:alpha:)blends by, so a frame across the ±π seam does not spin the long way round.Cameraknows nothing about collision. Put it at a body's eye if it should not walk through walls.OrbitCameradoes, throughkeepClear(of:deltaTime:).OrbitCamera's yaw is not wrapped; everything that turns or blends it goes the short way round whatever its value.