camera

package
v0.0.0-...-94fff03 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 5, 2026 License: MIT Imports: 10 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package camera is a quick-start follow camera: mark an entity with a Target, pick a FollowMode in a Rig and run the System in the camera stage; it moves the render.Camera after the target every tick.

A tick runs a small pipeline on the Rig's own (unclamped) follow position: the goal (the target's position plus Target.Offset) goes through the optional look-ahead and dead-zone stages, a motion (hard, smooth or spring) moves the follow position toward the result, and the camera's Pos becomes the follow position clamped to Rig.Bounds. Each FollowMode is a preset of that pipeline; Rig.DeadZone.On and Rig.LookAhead.On add a stage to any preset.

game.Engine runs the System first in its camera stage and owns the Rig (Config.CameraRig, Engine.CameraRig). Without a game.Engine, add the System to a schedule after a step that calls Camera.Snapshot; see doc/guide/engine/camera.md.

The package imports ecs, ecs/system, gfx, render and extract, never game.

Index

Examples

Constants

View Source
const (
	DefaultSmoothTime      = 150 * time.Millisecond
	DefaultSpringFrequency = 2 // Hz
	DefaultSpringDamping   = 1 // critical
	DefaultLookDistance    = 48
	DefaultLookTime        = 300 * time.Millisecond
	DefaultLookMinSpeed    = 1 // world units per second
)

Default parameters, used where a Rig field is zero.

View Source
const (
	DefaultShakeFrequency = 20 // Hz
	DefaultShakeDecay     = 1  // trauma per second
	DefaultShakeExponent  = 2
)

Default shake parameters, used where a Shake field is zero.

Variables

View Source
var DefaultDeadZone = gfx.Vec2{X: 32, Y: 24}

DefaultDeadZone is the dead-zone half size used when DeadZone.HalfSize is zero, in world units.

View Source
var DefaultShakeOffset = gfx.Vec2{X: 6, Y: 6}

DefaultShakeOffset is the offset at full shake used when Shake.MaxOffset is zero, in world units.

Functions

This section is empty.

Types

type DeadZone

type DeadZone struct {
	// On adds the stage to modes other than deadzone.
	On bool
	// HalfSize is half the window size in world units (it does not scale
	// with Zoom). Zero means DefaultDeadZone.
	HalfSize gfx.Vec2
}

DeadZone configures the dead-zone stage: a window that moves only when the goal leaves it, by just enough to keep the goal on its edge.

type FollowMode

type FollowMode string

FollowMode selects how the camera follows its target. Each mode is a preset of a motion and the goal stages it turns on (see the package documentation and doc/guide/engine/camera.md):

mode       look-ahead  dead zone  motion
default    -           -          hard
smooth     -           -          smooth
deadzone   -           on         hard
spring     -           -          spring
lookahead  on          -          smooth

The zero value "" means FollowDefault. Values are plain strings so they read well in config files, Lua and logs.

const (
	// FollowDefault puts the camera on the target every tick.
	FollowDefault FollowMode = "default"
	// FollowSmooth eases toward the target, independent of the tick rate
	// (Rig.Smooth).
	FollowSmooth FollowMode = "smooth"
	// FollowDeadZone leaves the camera still while the target moves inside
	// a rectangle around the view center, and pushes it along when the
	// target reaches an edge (Rig.DeadZone).
	FollowDeadZone FollowMode = "deadzone"
	// FollowSpring follows with a damped spring, which can overshoot when
	// under-damped (Rig.Spring).
	FollowSpring FollowMode = "spring"
	// FollowLookAhead eases toward a point ahead of the target in its
	// direction of motion (Rig.LookAhead, Rig.Smooth).
	FollowLookAhead FollowMode = "lookahead"
)

The follow modes.

func (FollowMode) Check

func (m FollowMode) Check()

Check panics with `camera: unknown follow mode "x"` unless m is one of the FollowMode constants or the zero value.

func (FollowMode) String

func (m FollowMode) String() string

String returns the mode name, "default" for the zero value.

type LookAhead

type LookAhead struct {
	// On adds the stage to modes other than lookahead.
	On bool
	// Distance is how far ahead, in world units. Zero means
	// DefaultLookDistance.
	Distance float32
	// Time is the easing time constant of the look offset, toward the
	// motion direction and back to zero. Zero means DefaultLookTime.
	Time time.Duration
	// MinSpeed is the target speed, in world units per second, below which
	// the look offset returns to zero. Zero means DefaultLookMinSpeed.
	MinSpeed float32
}

LookAhead configures the look-ahead stage: the goal moves ahead of the target in its direction of motion.

type Rig

type Rig struct {
	// Mode is the follow preset; "" means FollowDefault. An unknown mode
	// panics in System.Run.
	Mode FollowMode
	// Smooth is the easing of the smooth motion (modes smooth, lookahead).
	Smooth Smooth
	// DeadZone configures the dead-zone stage (mode deadzone, or On).
	DeadZone DeadZone
	// Spring is the spring motion (mode spring).
	Spring Spring
	// LookAhead configures the look-ahead stage (mode lookahead, or On).
	LookAhead LookAhead
	// Bounds is the world rectangle the view must stay inside. The zero
	// Rect means unbounded. On an axis where Bounds is smaller than the
	// view, the camera is centered on Bounds. Rotation is ignored.
	Bounds gfx.Rect
	// TeleportDistance snaps the camera (see Snap) when the goal is further
	// than this from the follow position, so a teleported target does not
	// make the camera sweep across the level. 0 turns it off.
	TeleportDistance float32
	// Shake configures the screen shake that AddTrauma starts.
	Shake Shake
	// contains filtered or unexported fields
}

Rig configures the follow camera and holds its state between ticks. The System reads it as the world resource *Rig (game.Engine owns one, see Engine.CameraRig); change its fields at any time from any system or tool. Every zero field means its documented default, so the zero Rig is a hard follow without bounds.

The Rig keeps its own, unclamped follow position: Bounds only shapes the camera's Pos, and the next tick continues from the follow position, not from Camera.Pos. So offsets that later camera-stage systems add to Pos (a shake) do not feed back, and a system that overrides Pos does so for one tick only. The built-in shake (Shake, AddTrauma) works the same way.

Example

The presets cover the common cameras; the On flags add a stage to any of them. This one eases after the target but ignores small moves inside the dead zone, and leads it in its direction of motion.

package main

import (
	"fmt"
	"time"

	"github.com/weakpixel/engine/camera"
	"github.com/weakpixel/engine/gfx"
)

func main() {
	rig := camera.Rig{
		Mode:      camera.FollowSmooth,
		Smooth:    camera.Smooth{Time: 250 * time.Millisecond},
		DeadZone:  camera.DeadZone{On: true, HalfSize: gfx.Vec2{X: 24, Y: 16}},
		LookAhead: camera.LookAhead{On: true, Distance: 32},
		// Jump instead of sweeping when the target teleports.
		TeleportDistance: 400,
	}
	fmt.Println(rig.Mode)
}
Output:
smooth

func (*Rig) AddTrauma

func (r *Rig) AddTrauma(t float32)

AddTrauma adds t to the shake trauma, which stays in [0, 1]; a negative t reduces it. Call it from any system: an explosion adds 0.6, a hit 0.3.

func (*Rig) Snap

func (r *Rig) Snap()

Snap makes the next tick with a target jump straight to it: the follow position and the dead-zone window move to the goal, the spring velocity and look offset reset, and Camera.Prev is cleared (Camera.Jump) so the frame does not sweep. Call it after a teleport or a level load. The System also snaps on its own the first tick it has a target after a tick without one, and when TeleportDistance is exceeded.

func (*Rig) StopShake

func (r *Rig) StopShake()

StopShake sets the trauma to 0; the next System tick puts the camera back on its unshaken position.

func (*Rig) Trauma

func (r *Rig) Trauma() float32

Trauma returns the current shake trauma in [0, 1].

type Shake

type Shake struct {
	// MaxOffset is the offset at full shake, per axis, in world units.
	// Zero means DefaultShakeOffset.
	MaxOffset gfx.Vec2
	// MaxAngle is the rotation at full shake, in radians. 0 means no
	// rotation; a rotating shake turns off render.Camera.PixelSnap while
	// the view is rotated.
	MaxAngle float32
	// Frequency is the noise frequency in Hz: higher shakes faster. Zero
	// means DefaultShakeFrequency.
	Frequency float32
	// Decay is the trauma lost per second; 1 lets full trauma settle in a
	// second. Zero means DefaultShakeDecay.
	Decay float32
	// Exponent shapes the shake: the amplitude is trauma^Exponent. Zero
	// means DefaultShakeExponent.
	Exponent float32
	// InBounds clamps the shaken view to Rig.Bounds, so the shake never
	// shows outside the level but flattens against its edges. By default
	// the shake is added after the clamp and stays visible at an edge. It
	// only matters with a Target and non-zero Bounds.
	InBounds bool
	// Off turns the shake off (an accessibility setting): AddTrauma still
	// counts and trauma still decays, but the camera does not move.
	Off bool
}

Shake configures the trauma-based screen shake: Rig.AddTrauma adds trauma in [0, 1], trauma falls by Decay per second, and the camera is offset by MaxOffset (and rotated by MaxAngle) times trauma^Exponent times smooth noise. Small hits barely move the view, big ones shake hard, and several hits add up. Every zero field means its documented default.

type Smooth

type Smooth struct {
	// Time is the time constant: after Time the camera has covered 63% of
	// a jump. Zero means DefaultSmoothTime.
	Time time.Duration
}

Smooth configures exponential easing: each tick the follow position covers 1 - exp(-dt/Time) of the remaining distance, the same total motion at any tick rate.

type Spring

type Spring struct {
	// Frequency is the natural frequency in Hz; higher is stiffer. Zero
	// means DefaultSpringFrequency.
	Frequency float32
	// Damping is the damping ratio: 1 is critical (fastest without
	// overshoot), below 1 overshoots, above 1 is sluggish. Zero means
	// DefaultSpringDamping.
	Damping float32
}

Spring configures a damped spring, solved in closed form so it is stable at any tick rate.

type System

type System struct {
	// contains filtered or unexported fields
}

System moves the render.Camera after the Target entity, as configured by the Rig resource. Run it in the camera stage, after the game moved its entities and after the camera's view was recorded for this tick (render.Camera.Snapshot; game.Engine does both and runs it first in StageCamera). It only assigns Camera.Pos, clears Camera.Prev when it snaps (Camera.Jump), and assigns Camera.Rotation while a rotating shake runs.

Each tick it picks the target (highest Priority, then lowest entity ID), snaps when asked to (Rig.Snap, the first tick with a target after a tick without one, Rig.TeleportDistance), otherwise advances the Rig's pipeline by the tick's delta, and sets Camera.Pos to the follow position clamped to Rig.Bounds. It then adds the Rig's shake (see Shake); the shake also rotates Camera.Rotation by its change since the last tick. Without a target it moves Camera.Pos only by the change of the shake offset, so a camera the game moves itself shakes too and ends where it started.

It needs the resources *render.Camera and *extract.Screen; Init creates a zero *Rig resource if there is none. Run does not allocate. It panics with `camera: unknown follow mode "x"` for an unknown Rig.Mode.

Example

Without game.Engine: the camera stage needs the camera snapshot before it (game.Engine does that in its snapshot stage) and the *render.Camera and *extract.Screen resources.

package main

import (
	"fmt"
	"image"
	"time"

	"github.com/weakpixel/ecs"
	"github.com/weakpixel/ecs/system"
	"github.com/weakpixel/engine/camera"
	"github.com/weakpixel/engine/extract"
	"github.com/weakpixel/engine/gfx"
	"github.com/weakpixel/engine/render"
)

func main() {
	w := ecs.NewWorld()
	cam := &render.Camera{}
	ecs.SetResource(w, cam)
	ecs.SetResource(w, &extract.Screen{Size: image.Pt(320, 180)})
	ecs.SetResource(w, &camera.Rig{
		Mode:   camera.FollowSmooth,
		Bounds: gfx.Rect{Max: gfx.Vec2{X: 1000, Y: 1000}},
	})

	hero := ecs.NewEntity2(w, camera.Target{}, gfx.Transform{Pos: gfx.Vec2{X: 500, Y: 500}})

	var s system.Schedule
	s.AddStage("snapshot", extract.NewSnapshotTransforms(w).Run,
		func(*system.Context) { cam.Snapshot() })
	// ... input and simulation stages go here ...
	s.AddStage("camera")
	s.AddRunner(camera.NewSystem(w))

	s.Run(w, time.Second/60) // the first tick with a target snaps
	fmt.Println(cam.Pos)

	ecs.GetComp[gfx.Transform](w, hero).Pos = gfx.Vec2{X: 0, Y: 500}
	for range 120 {
		s.Run(w, time.Second/60)
	}
	fmt.Println(cam.Pos) // eased left, stopped by the bounds
}
Output:
{500 500}
{160 500}

func NewSystem

func NewSystem(w *ecs.World) *System

NewSystem returns the system for w.

func (*System) Init

func (s *System) Init(ctx *system.Context)

Init implements system.Initializer. It caches the resources, so set them (and replace the Rig, if at all) before the first Run.

func (*System) Run

func (s *System) Run(ctx *system.Context)

Run implements system.Runner.

type Target

type Target struct {
	// Offset is added to the target's position: the camera aims at
	// Transform.Pos + Offset, for example to frame a character's head.
	Offset gfx.Vec2
	// Priority picks among several targets; higher wins.
	Priority int16
}

Target marks the entity the camera follows; the entity also needs a gfx.Transform. It is a runtime-only component, not part of any Game Object schema: add it with ecs.SetComp.

With several targets the highest Priority wins, and among equal priorities the entity with the lowest ecs.Entity ID (stable, unlike view order, which changes when entities move between archetypes). With none the System leaves the camera alone.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL