Documentation
¶
Overview ¶
+game:group:name=physics
Package physics moves entities with a gfx.Transform, a collision.Collider, a Body and a Velocity: gravity, damping, mass, bounce and friction for dynamic bodies, code-driven kinematic bodies (moving platforms, elevators), surface [Material]s (ice, trampolines, conveyors), one-way platforms, riders carried by the platform they stand on and the Touching flags game code reads for jumps. MoveAndSlide moves characters whose movement the game owns, and NewMoveSystem moves simple Velocity entities without collision.
Physics runs on package collision: NewSystem creates the World's collision.System and drives it, so layers, masks, events and queries work as without physics. A body is pushed out of a collider only when its own Mask has a layer the collider is on. Bodies stay upright: there is no rotation.
The resolver and per-contact behavior can be replaced with Config.Resolver, Config.PreSolve and Config.PostSolve. See doc/guide/engine/physics.md.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( CID_Body = ecs.RegisterComp[Body]() CID_Follow = ecs.RegisterComp[Follow]() CID_Material = ecs.RegisterComp[Material]() CID_Touching = ecs.RegisterComp[Touching]() CID_Velocity = ecs.RegisterComp[Velocity]() )
var FollowTarget = tween.NewLens(func(f *Follow) *gfx.Vec2 { return &f.Target }, tween.LerpVec2)
FollowTarget is the tween lens of Follow.Target:
tween.To(tw, platform, physics.FollowTarget, gfx.Vec2{X: 300, Y: 80}, 2)
Functions ¶
This section is empty.
Types ¶
type Body ¶
type Body struct {
// Kind is Dynamic (0) or Kinematic.
Kind BodyKind
// Mass is the mass of a dynamic body; zero means 1. Kinematic bodies
// have infinite mass. The editor starts a new Body at 1.
//
// +game:default=1
Mass float32
// Damping is the fraction of the velocity lost per second, per axis: 0
// keeps it, 0.5 halves it every second, 1 (or more) stops the body at
// once.
Damping gfx.Vec2
// GravityScale multiplies Config.Gravity for this body: 0 no gravity, 1
// full, 0.5 floaty, negative falls up. The editor starts a new Body at 1,
// so it falls; a Body added in code keeps 0.
//
// +game:default=1
GravityScale float32
// MaxSpeed bounds the speed per axis, in world units per second; zero
// means unlimited.
MaxSpeed gfx.Vec2
// LockX and LockY keep the body from moving along that axis (an
// elevator locks X).
LockX, LockY bool
// DropThrough makes the body ignore one-way colliders and tile grids.
// The game sets it (drop down through a platform); physics clears it
// once the body touches no one-way collider.
DropThrough bool
}
Body makes an entity with a gfx.Transform and a Velocity a physics body; add a collision.Collider for it to collide. It holds the tuning the integrator reads every tick.
A zero Body is a dynamic body of mass 1 without gravity: falling bodies set GravityScale to 1. The editor writes GravityScale 1 for a new Body.
+game:component
type BodyKind ¶
type BodyKind uint8
BodyKind selects how a Body moves.
+game:enum
const ( // Dynamic bodies are moved by gravity, their Velocity and contacts. Dynamic BodyKind = iota // Kinematic bodies move only by their Velocity (set by code, or by // [Follow]): they push dynamic bodies, carry the ones that stand on them // and are never pushed. They pass through statics and each other. Kinematic )
Body kinds. A static object is a collision.Collider without a Body.
type Config ¶
type Config struct {
// Gravity is the world gravity in world units per second squared:
// (0, 980) for a platformer, zero for top-down. Each body accelerates by
// Gravity * Body.GravityScale. Change it at run time with
// [System.SetGravity].
Gravity gfx.Vec2
// Substeps splits every tick into this many steps; zero is 1. More
// substeps keep fast bodies from passing through thin colliders, at the
// cost of one collision detection per substep.
Substeps int
// Iterations is the number of resolver passes per substep; zero is 4.
Iterations int
// DefaultMaterial is the material of colliders without a [Material];
// nil is {Bounce: 0, Friction: 0.4}.
DefaultMaterial *Material
// Collision configures the collision.System physics creates.
Collision collision.Config
// Resolver replaces the built-in impulse resolver for the whole World;
// nil uses it.
Resolver Resolver
// PreSolve, when set, is called for every solid contact of every
// substep before it is resolved. Returning false ignores the contact
// for that substep; it may change c.Bounce, c.Friction and c.SurfaceVel
// for this contact. It must not add or remove entities or components
// (queue those as commands).
PreSolve func(c *Contact) bool
// PostSolve, when set, is called for every resolved contact after the
// resolver, with the impulse it applied. Same rules as PreSolve.
PostSolve func(c *Contact)
}
Config configures the physics System of a World.
type Contact ¶
type Contact struct {
collision.Contact
// Bounce and Friction are the combined materials of both sides;
// SurfaceVel is the velocity Self is dragged to along the contact,
// relative to Other (Other's Material.SurfaceVel minus Self's).
Bounce, Friction float32
SurfaceVel gfx.Vec2
// ApproachSpeed is the relative speed along -Normal at the start of the
// resolution, positive when the sides move into each other.
ApproachSpeed float32
// Impulse is the normal impulse the resolver applied this substep, >= 0
// (mass x velocity); FrictionImpulse the tangential one. Before the
// first pass they hold the impulses of the same contact in the last
// substep, which the built-in resolver applies first (warm start), so
// stacks settle in few passes.
Impulse, FrictionImpulse float32
// contains filtered or unexported fields
}
Contact is one solid contact of a substep, as the resolver and the hooks see it. When both sides detect each other, the two mirrored collision.Contacts are merged into one, with the first in the Space's order as Self. Normal points from Self out of Other.
type Follow ¶
type Follow struct {
// Target is the position the body reaches at the end of the tick.
//
// +game:runtime
Target gfx.Vec2 `json:"-"`
// contains filtered or unexported fields
}
Follow moves a kinematic body to Target every tick by setting its Velocity to (Target - Pos) / dt, so a platform driven by a tween (see FollowTarget) is an ordinary kinematic body: it carries riders, drags crates by friction and pushes with momentum. Tweening Transform.Pos instead teleports the platform after physics has run.
A fresh Follow takes the body's position as its target on the first tick physics sees it, so it never jumps to the origin. Removing Follow leaves the body with its last Velocity: zero it.
+game:component
type Impact ¶
type Impact struct {
// Self is the detecting entity, Other the one it hit; Other is zero for
// a tile grid, then Tiles is set.
Self, Other ecs.Entity
Tiles collision.TileGrid
// Normal points from Self out of Other.
Normal gfx.Vec2
// Speed is the relative speed along the normal when the contact
// started, >= 0.
Speed float32
}
Impact is sent when a solid contact starts (not for sensors), once per detecting side and pair like collision.Enter, and once per (body, tile grid). Speed lets landing dust or hit sounds scale with the hit.
type Material ¶
type Material struct {
// Bounce is the restitution: 0 does not bounce, 1 keeps the speed, more
// than 1 adds to it (a trampoline).
Bounce float32
// Friction is the Coulomb friction coefficient; zero is ice.
Friction float32
// SurfaceVel is the speed the surface drags touching bodies toward, in
// world units per second, along the contact (a conveyor belt).
SurfaceVel gfx.Vec2
}
Material sets the surface behavior of a collider: a dynamic crate, a static wall or a kinematic platform. Without one, the collider uses Config.DefaultMaterial; a Material is taken literally, so Friction 0 is ice.
The two sides of a contact combine: bounce is the larger one, friction sqrt(a * b), the surface velocity is this side's SurfaceVel minus the other's.
+game:component
type MoveOptions ¶
type MoveOptions struct {
// Pixel moves in whole world units and carries the fraction over in
// *Remainder, so positions stay on the pixel grid. Remainder must be set
// with Pixel; the game keeps it (in its own component). A hit zeroes the
// remainder of that axis.
Pixel bool
Remainder *gfx.Vec2
// DropThrough ignores one-way colliders and tile grids for this move.
DropThrough bool
// CornerCorrect is the largest sideways shift, in world units, that
// lets an upward move clear a ceiling corner it only clips; zero is
// off. Downward hits are never corrected.
CornerCorrect float32
// LedgeCorrect is the largest up or down shift, in world units, that
// lets a sideways move clear a ledge or overhang edge it only clips;
// zero is off. It applies to any X hit.
LedgeCorrect float32
// Push is the mover's pushing mass, in the unit of Body.Mass; zero
// does not push. With Push set, an X move into dynamic bodies pushes
// them: mover and bodies move by the part of the move past the first
// body times Push / (Push + M), where M is the bodies' total mass.
Push float32
}
MoveOptions tune MoveAndSlide.
type MoveResult ¶
type MoveResult struct {
// Moved is how far the entity moved.
Moved gfx.Vec2
// HitX and HitY report that the move stopped on that axis;
// HitXEntity and HitYEntity are the colliders hit (zero for a tile),
// HitXTiles and HitYTiles the tile grids and HitXCell and HitYCell the
// cells of a tile hit.
HitX, HitY bool
HitXEntity, HitYEntity ecs.Entity
HitXTiles, HitYTiles collision.TileGrid
HitXCell, HitYCell image.Point
// OnGround is set when the move hit something going down, or when the
// mover ends on or less than one unit above a solid without moving up
// (also a move of zero, as a pixel move that rounds to nothing);
// OnCeiling is set for
// a hit going up; OnWall is -1 for a hit going left, +1 going right.
OnGround, OnCeiling bool
OnWall int8
// CornerShift is the X shift of a corner correction and LedgeShift the
// Y shift of a ledge correction, signed, zero when none. Moved includes
// them.
CornerShift, LedgeShift float32
// Pushed is the first body a move with MoveOptions.Push pushed, and
// PushedMass the total mass of the bodies it pushed; both are zero when
// it pushed nothing (also when the bodies were blocked: then HitX is set
// and HitXEntity is the first body).
Pushed ecs.Entity
PushedMass float32
}
MoveResult is what a MoveAndSlide call did.
func MoveAndSlide ¶
func MoveAndSlide(w *ecs.World, e ecs.Entity, delta gfx.Vec2, opts MoveOptions) MoveResult
MoveAndSlide moves e's Transform.Pos by delta against the solids its Collider.Mask detects: colliders that are not sensors, tile grids, and one-way colliders and grids from their blocking side. It moves along X first, then Y, each axis stopping flush at the first blocker, so a diagonal move into a wall slides along it. If e has a Touching, it is written from the result.
It finds the colliders through the World's collision Space and tests them where they are now (their Transform and Collider), so a platform or box that moved after the last detection is not entered; a collider that moved more than 16 units since then can be missed. It works with only a collision.System running. A mover that ends on or less than one unit above a solid is OnGround even when the move does not go down. A mover with a Touching that stands on a kinematic body is moved with it by the physics System. Blockers are tested by their bounds; a circle mover moves as its bounds. Solids the mover already overlaps by more than one unit do not block it; smaller overlaps (something moved into the mover) block it where it is. It does not allocate.
With MoveOptions.Push, an X move into a dynamic body pushes it, and a row of up to 8 touching dynamic bodies in front of it, by moving their Transform.Pos (their Velocity is left alone): see MoveOptions.Push for the speed. The row stops flush at whatever blocks one of its bodies, a ninth body in the row blocks it, and kinematic bodies, bodies with LockX, colliders without a Body and tiles block as without Push. Y moves never push, and bodies standing on a pushed body are not moved with it. In pixel mode the pushed move is rounded toward zero to whole units and the fraction carried over in the remainder. A push comes before ledge correction: a blocked push can still be ledge-corrected.
Panics with "physics: MoveAndSlide needs a rect, anim-body or circle collider" for a custom shape kind, and as ecs.GetComp when e has no Transform or Collider.
type MoveSystem ¶
type MoveSystem struct {
// contains filtered or unexported fields
}
MoveSystem moves every entity with a gfx.Transform and a Velocity but no Body by Velocity x dt each tick: no gravity, no collision. Use it for bullets, drifting clouds and props; bodies are left to the physics System. It works without the physics System, for example next to a collision.System that reports bullet hits.
func NewMoveSystem ¶
func NewMoveSystem(w *ecs.World) *MoveSystem
NewMoveSystem returns the MoveSystem of w. With game.Engine, add it to a stage with game.Wrap.
func (*MoveSystem) Run ¶
func (m *MoveSystem) Run(ctx *system.Context)
Run implements system.Runner.
type Resolver ¶
Resolver resolves the contacts of a substep by changing velocities. It is called Config.Iterations times per substep with the same contacts; the System then pushes overlapping bodies apart (position correction) on its own.
type Solve ¶
type Solve struct {
// Dt is the substep length in seconds; Pass the index of the pass.
Dt float32
Pass int
// contains filtered or unexported fields
}
Solve is what a Resolver works with. It is valid only during the call.
func (*Solve) InvMass ¶
InvMass returns the per-axis inverse masses of the two sides of c: zero for a side that must not be changed (no body, kinematic, a locked axis, or a side whose Mask does not have the other's layer).
func (*Solve) RestThreshold ¶
RestThreshold returns the approach speed below which the built-in resolver does not bounce, so resting bodies do not jitter: twice what gravity adds in a substep.
type System ¶
type System struct {
// contains filtered or unexported fields
}
System moves the bodies of its World every tick: integrate, detect, resolve, write the Touching flags, once per substep, then send the tick's collision events once. Add it to the simulate stage after the systems that set Velocity (input, AI) and before the ones that read Touching or contacts.
func NewSystem ¶
NewSystem creates w's collision.System with cfg.Collision and returns the physics system that drives it. Use it instead of collision.NewSystem, not with it. With game.Engine, add it to a stage with game.Wrap.
Panics with "collision: Space already has a system" when w already has a collision or physics system, and "physics: negative Substeps" or "physics: negative Iterations" for bad counts.
func (*System) SetGravity ¶
SetGravity changes the world gravity from the next substep on.
func (*System) SetTileMaterial ¶
SetTileMaterial sets the material of the cells of grid (an ice layer, a conveyor layer: one grid per material). Grids without one use Config.DefaultMaterial. The grid does not have to be in the Space yet.
type Touching ¶
type Touching struct {
// OnGround is set while the entity stands on something.
//
// +game:runtime
OnGround bool `json:"-"`
// OnCeiling is set while something blocks it from above.
//
// +game:runtime
OnCeiling bool `json:"-"`
// OnWall is -1 while a wall blocks it on the left, +1 on the right,
// else 0.
//
// +game:runtime
OnWall int8 `json:"-"`
// Ground is the entity it stands on; zero for a tile grid or nothing.
//
// +game:runtime
Ground ecs.Entity `json:"-"`
// GroundNormal is the unit normal of the ground, pointing up out of it.
//
// +game:runtime
GroundNormal gfx.Vec2 `json:"-"`
}
Touching reports what a body or a MoveAndSlide mover touches: physics writes it every tick for bodies that have it, MoveAndSlide on every call. It is runtime state, never serialized.
+game:component
type Velocity ¶
Velocity is the speed of an entity in world units per second. Physics moves bodies by it, NewMoveSystem moves other entities by it, and game code sets it (a jump: v.Vel.Y = -300) or reads it (walk or idle).
While a dynamic body stands on a kinematic body, its Velocity is relative to that body (the platform's motion is added on top); when it leaves, the platform's velocity is added to it.
+game:component