La referencia de API proviene de los comentarios de documentación de Go en el código fuente y está redactada en inglés.
package physics
import "github.com/nsgo-dev/game/pkg/physics"Índice
- Constantes
- func CanCollide(a, b *Body) bool
- func CanCollideRigid(a, b *RigidBody) bool
- func DrawBody(d *core.Drawing, b *Body, style DebugStyle)
- func DrawContact(d *core.Drawing, c Contact, style DebugStyle)
- func DrawRaycast(d *core.Drawing, from, to core.Point, hits []RaycastHit, style DebugStyle)
- func DrawShape(d *core.Drawing, s Shape, style DebugStyle)
- func DrawSoftWorld(d *core.Drawing, sw *SoftWorld, style DebugStyle)
- func DrawTileContacts(d *core.Drawing, grid TileGrid, contacts []TileContact, style DebugStyle)
- func DrawTileGrid(d *core.Drawing, grid TileGrid, visible core.Bounds, style DebugStyle)
- func DrawWorld(d *core.Drawing, w *World, visible core.Bounds, contacts []Contact, style DebugStyle)
- type AreaConstraint
- type AreaEffect
- type AreaOverrideMode
- type AreaSettings
- type BendingConstraint
- type Body
- type BodySnapshot
- type Box
- type Capsule
- type Chain
- type CharacterBody
- func NewCharacterBody(body *Body) *CharacterBody
- func (c *CharacterBody) EffectiveGravity() (gx, gy float32)
- func (c *CharacterBody) EffectiveGravityScale() float32
- func (c *CharacterBody) Move(grid TileGrid, slopes []Slope, platforms []*MovingPlatform, dt time.Duration) MoveResult
- func (c *CharacterBody) MoveWorld(world *World, slopes []Slope, platforms []*MovingPlatform, dt time.Duration) MoveResult
- func (c *CharacterBody) SetGravityScale(scale float32)
- type Circle
- type Contact
- type ContactEvent
- type ContactEventKind
- type DebugStyle
- type DistanceConstraint
- type DistanceJoint
- func NewDistanceJoint(a, b *RigidBody, anchorA, anchorB core.Point, length float32) *DistanceJoint
- func NewRopeJoint(a, b *RigidBody, anchorA, anchorB core.Point, maxLength float32) *DistanceJoint
- func (r *DistanceJoint) Broken() bool
- func (r *DistanceJoint) ReactionForce() (fx, fy float32)
- func (r *DistanceJoint) ReactionTorque() float32
- type GravityFalloff
- type Grid
- func NewGrid(cols, rows int, tileWidth, tileHeight float32) *Grid
- func (g *Grid) FillRect(col, row, w, h int, flags TileFlags)
- func (g *Grid) GridOrigin() (x, y float32)
- func (g *Grid) GridSize() (cols, rows int)
- func (g *Grid) Set(col, row int, flags TileFlags)
- func (g *Grid) TileFlagsAt(col, row int) TileFlags
- func (g *Grid) TileSize() (width, height float32)
- type GridSnapshot
- type Joint
- type JointBreakEvent
- type LayerMask
- type MotionMode
- type MouseJoint
- type MoveOptions
- type MoveResult
- type MovingPlatform
- type OverlapHit
- type Particle
- type Polygon
- type PrismaticJoint
- func NewPrismaticJoint(a, b *RigidBody, worldAnchor, worldAxis core.Point) *PrismaticJoint
- func (r *PrismaticJoint) Broken() bool
- func (j *PrismaticJoint) JointSpeed() float32
- func (j *PrismaticJoint) JointTranslation() float32
- func (r *PrismaticJoint) ReactionForce() (fx, fy float32)
- func (r *PrismaticJoint) ReactionTorque() float32
- type QueryMask
- type RaycastHit
- type RevoluteJoint
- func NewRevoluteJoint(a, b *RigidBody, worldPivot core.Point) *RevoluteJoint
- func (r *RevoluteJoint) Broken() bool
- func (j *RevoluteJoint) JointAngle() float32
- func (j *RevoluteJoint) JointSpeed() float32
- func (r *RevoluteJoint) ReactionForce() (fx, fy float32)
- func (r *RevoluteJoint) ReactionTorque() float32
- type RigidAttachment
- type RigidBody
- func NewRigidBody(s Shape, mass float32) *RigidBody
- func NewRigidBox(x, y, w, h, mass float32) *RigidBody
- func NewRigidCircle(x, y, r, mass float32) *RigidBody
- func NewStaticRigidBody(s Shape) *RigidBody
- func NewStaticRigidBox(x, y, w, h float32) *RigidBody
- func NewStaticRigidCircle(x, y, r float32) *RigidBody
- func (b *RigidBody) ApplyForce(fx, fy float32)
- func (b *RigidBody) ApplyImpulse(ix, iy float32)
- func (b *RigidBody) ApplyImpulseAtPoint(ix, iy float32, worldPoint core.Point)
- func (b *RigidBody) ApplyTorque(torque float32)
- func (b *RigidBody) EffectiveGravityScale() float32
- func (b *RigidBody) LocalToWorld(local core.Point) core.Point
- func (b *RigidBody) SetGravityScale(scale float32)
- func (b *RigidBody) SetTargetPose(x, y, angle float32)
- func (b *RigidBody) Sleeping() bool
- func (b *RigidBody) Wake()
- func (b *RigidBody) WorldShape() Shape
- func (b *RigidBody) WorldToLocal(world core.Point) core.Point
- type RigidBodySnapshot
- type RigidContactPointSnapshot
- type RigidContactSnapshot
- type RigidJointBreakEventSnapshot
- type RigidJointSnapshot
- type RigidSenseSnapshot
- type RigidTouchSnapshot
- type RigidWorld
- func (w *RigidWorld) AddBody(bodies ...*RigidBody)
- func (w *RigidWorld) AddJoint(joints ...Joint)
- func (w *RigidWorld) AddTrigger(triggers ...*Trigger)
- func (w *RigidWorld) AreaEffectAtShape(shape Shape, layer, mask LayerMask) AreaEffect
- func (w *RigidWorld) Checksum() uint64
- func (w *RigidWorld) ContactEvents() []ContactEvent
- func (w *RigidWorld) GravityAt(x, y float32) (gx, gy float32)
- func (w *RigidWorld) JointBreakEvents() []JointBreakEvent
- func (w *RigidWorld) QueryOverlap(shape Shape, mask QueryMask, layerMask LayerMask) []OverlapHit
- func (w *RigidWorld) QueryPoint(x, y float32, mask QueryMask, layerMask LayerMask) []*RigidBody
- func (w *RigidWorld) Raycast(from, to core.Point, mask QueryMask, layerMask LayerMask) []RaycastHit
- func (w *RigidWorld) RaycastFirst(from, to core.Point, mask QueryMask, layerMask LayerMask) (RaycastHit, bool)
- func (w *RigidWorld) RemoveBody(b *RigidBody) bool
- func (w *RigidWorld) RemoveJoint(j Joint) bool
- func (w *RigidWorld) RemoveTrigger(tr *Trigger) bool
- func (w *RigidWorld) Restore(snap RigidWorldSnapshot) error
- func (w *RigidWorld) Save() RigidWorldSnapshot
- func (w *RigidWorld) SensorEvents() []SensorEvent
- func (w *RigidWorld) ShapeCast(shape Shape, dx, dy float32, layerMask LayerMask) (ShapeCastHit, bool)
- func (w *RigidWorld) ShapeCastAll(shape Shape, dx, dy float32, layerMask LayerMask) []ShapeCastHit
- func (w *RigidWorld) ShapeCastAllWith(shape Shape, dx, dy float32, opts ShapeCastOptions) []ShapeCastHit
- func (w *RigidWorld) ShapeCastWith(shape Shape, dx, dy float32, opts ShapeCastOptions) (ShapeCastHit, bool)
- func (w *RigidWorld) Step(dt time.Duration)
- type RigidWorldSnapshot
- type RopeConfig
- type Segment
- type SensorEvent
- type Shape
- func BoxShape(b Box) Shape
- func CapsuleShape(c Capsule) Shape
- func ChainShape(points []core.Point, loop bool) Shape
- func CircleShape(c Circle) Shape
- func PolygonShape(p Polygon) Shape
- func SegmentShape(s Segment) Shape
- func (s Shape) Area() float32
- func (s Shape) Bounds() Box
- func (s Shape) Centroid() (x, y float32)
- func (s Shape) Contains(x, y float32) bool
- func (s Shape) Empty() bool
- func (s Shape) MomentOfInertia(mass float32) float32
- func (s Shape) Translated(dx, dy float32) Shape
- type ShapeCastHit
- type ShapeCastOptions
- type ShapeKind
- type ShapeMatchConstraint
- type SlideCollision
- type SlideResult
- type Slope
- type SoftBodyConfig
- type SoftWorld
- func NewSoftWorld() *SoftWorld
- func (sw *SoftWorld) AddArea(particles []int, pressure, compliance float32) int
- func (sw *SoftWorld) AddBending(a, b, c int, compliance float32) int
- func (sw *SoftWorld) AddDistance(a, b int, restLength, compliance float32) int
- func (sw *SoftWorld) AddParticle(p Particle) int
- func (sw *SoftWorld) AddRope(cfg RopeConfig) []int
- func (sw *SoftWorld) AddShapeMatch(particles []int, stiffness float32) int
- func (sw *SoftWorld) AddSoftBody(cfg SoftBodyConfig) []int
- func (sw *SoftWorld) AddTether(a, b int, maxLength, compliance float32) int
- func (sw *SoftWorld) AttachRigidBody(particleIdx int, body *RigidBody, localAnchor core.Point, compliance float32) int
- func (sw *SoftWorld) PinParticle(idx int)
- func (sw *SoftWorld) PolygonArea(particles []int) float32
- func (sw *SoftWorld) RopeLength(particles []int) float32
- func (sw *SoftWorld) Step(dt time.Duration)
- func (sw *SoftWorld) UnpinParticle(idx int)
- type SpringJoint
- type TileContact
- type TileFlags
- type TileGrid
- type TileGridOrigin
- type Trigger
- type TriggerSnapshot
- type WeldJoint
- type WheelJoint
- func NewWheelJoint(a, b *RigidBody, worldAnchor, worldAxis core.Point) *WheelJoint
- func (r *WheelJoint) Broken() bool
- func (j *WheelJoint) JointSpeed() float32
- func (j *WheelJoint) JointTranslation() float32
- func (r *WheelJoint) ReactionForce() (fx, fy float32)
- func (r *WheelJoint) ReactionTorque() float32
- type World
- func (w *World) Add(bodies ...*Body)
- func (w *World) AddTrigger(triggers ...*Trigger)
- func (w *World) AreaEffectAtShape(shape Shape, layer, mask LayerMask) AreaEffect
- func (w *World) Checksum() uint64
- func (w *World) GravityAt(x, y float32) (gx, gy float32)
- func (w *World) MoveAndSlide(body *Body, dt time.Duration) SlideResult
- func (w *World) MoveAndSlideWith(body *Body, dt time.Duration, opts MoveOptions) SlideResult
- func (w *World) QueryOverlap(shape Shape) []OverlapHit
- func (w *World) QueryOverlapLayer(shape Shape, mask QueryMask, layerMask LayerMask) []OverlapHit
- func (w *World) QueryOverlapMask(shape Shape, mask QueryMask) []OverlapHit
- func (w *World) QueryPoint(x, y float32) []*Body
- func (w *World) QueryPointLayer(x, y float32, layerMask LayerMask) []*Body
- func (w *World) Raycast(from, to core.Point, mask QueryMask) []RaycastHit
- func (w *World) RaycastFirst(from, to core.Point, mask QueryMask) (RaycastHit, bool)
- func (w *World) RaycastFirstLayer(from, to core.Point, mask QueryMask, layerMask LayerMask) (RaycastHit, bool)
- func (w *World) RaycastLayer(from, to core.Point, mask QueryMask, layerMask LayerMask) []RaycastHit
- func (w *World) Remove(b *Body) bool
- func (w *World) RemoveTrigger(tr *Trigger) bool
- func (w *World) Restore(snap WorldSnapshot) error
- func (w *World) Save() WorldSnapshot
- func (w *World) ShapeCast(shape Shape, dx, dy float32, mask QueryMask) (ShapeCastHit, bool)
- func (w *World) ShapeCastAll(shape Shape, dx, dy float32, mask QueryMask) []ShapeCastHit
- func (w *World) ShapeCastAllLayer(shape Shape, dx, dy float32, mask QueryMask, layerMask LayerMask) []ShapeCastHit
- func (w *World) ShapeCastAllWith(shape Shape, dx, dy float32, opts ShapeCastOptions) []ShapeCastHit
- func (w *World) ShapeCastLayer(shape Shape, dx, dy float32, mask QueryMask, layerMask LayerMask) (ShapeCastHit, bool)
- func (w *World) ShapeCastWith(shape Shape, dx, dy float32, opts ShapeCastOptions) (ShapeCastHit, bool)
- func (w *World) StepTriggers()
- type WorldSnapshot
- type WorldTriggerActiveSnapshot
Constantes
const (
// DefaultSleepLinearThreshold is the speed, in pixels per second, below which a rigid body counts as resting.
DefaultSleepLinearThreshold = 2
// DefaultSleepAngularThreshold is the angular speed, in radians per second, below which a rigid body counts as resting (2 degrees per second, as in Box2D).
DefaultSleepAngularThreshold = 2 * math.Pi / 180
// DefaultTimeToSleep is how many seconds every body of an island must rest before the island sleeps.
DefaultTimeToSleep = 0.5
)Sleep defaults for RigidWorld, in NSGo's pixel units.
const (
// DefaultMaxSlides is the default maximum number of slide iterations performed by World.MoveAndSlide.
DefaultMaxSlides = 4
// DefaultFloorMaxAngle is the default maximum angle in radians between a contact normal and the up direction
// for a surface to be classified as a floor (45 degrees, matching DefaultMaxSlopeAngle).
DefaultFloorMaxAngle float32 = DefaultMaxSlopeAngle
)const (
// DefaultSoftSubsteps is the default number of XPBD substeps per SoftWorld.Step.
DefaultSoftSubsteps = 8
// DefaultSoftIterations is the default number of constraint solver iterations per substep.
DefaultSoftIterations = 6
)const DefaultMaxSlopeAngle float32 = math.Pi / 4DefaultMaxSlopeAngle is the default maximum walkable slope angle (45 degrees in radians).
const DefaultSolverIterations = 10DefaultSolverIterations is the default number of sequential impulse iterations per RigidWorld.Step.
const DefaultTileFriction = 0.4DefaultTileFriction is the friction RigidWorld gives its Tiles when TileFriction is zero, the same as NewRigidBox gives a body.
const MaxPolygonVertices = 8MaxPolygonVertices is the most vertices a Polygon holds, as in Box2D.
const SnapshotVersion = 2SnapshotVersion is the schema version stored in WorldSnapshot and RigidWorldSnapshot. Version 2 added the kinematic and sensor flags, kinematic targets, Tiles and their settings, the contact and sensor overlap state, tile entries in the contact cache and a grid's origin; Restore still reads version 1 snapshots, which have none of them, and refuses any other version, so a build that only knows version 1 refuses a version 2 snapshot instead of dropping what it cannot read.
Funciones
func CanCollide(a, b *Body) boolCanCollide reports whether bodies a and b are allowed to collide based on their Layer and Mask fields. Zero Layer or Mask values default to LayerAll.
func CanCollideRigid(a, b *RigidBody) boolCanCollideRigid reports whether two rigid bodies are allowed to collide based on their Layer and Mask fields.
func DrawBody(d *core.Drawing, b *Body, style DebugStyle)DrawBody draws b's collision shape and, when style.VelocityScale > 0, its velocity vector. It preserves d's drawing state.
func DrawContact(d *core.Drawing, c Contact, style DebugStyle)DrawContact draws a contact point marker and a normal arrow from (c.PointX, c.PointY) along (c.NormalX, c.NormalY) when c.Hit is true. It preserves d's drawing state.
func DrawRaycast(d *core.Drawing, from, to core.Point, hits []RaycastHit, style DebugStyle)DrawRaycast draws a ray segment from from to to in RayColor along with hit markers and surface normal arrows for each hit in hits. It preserves d's drawing state.
func DrawShape(d *core.Drawing, s Shape, style DebugStyle)DrawShape draws s as a wireframe outline in d using style: a rectangle for ShapeBox, a circle with a +X orientation radius tick for ShapeCircle, the outline of a polygon (with rounded corners when it has a Radius) for ShapePolygon, the stadium outline and core segment of a capsule for ShapeCapsule, a line for ShapeSegment and a polyline for ShapeChain. It preserves d's drawing state.
func DrawSoftWorld(d *core.Drawing, sw *SoftWorld, style DebugStyle)DrawSoftWorld draws XPBD particles, structural distance constraints, area polygons, and rigid-body attachments from sw onto d using style. Pinned particles are highlighted in ContactColor and free particles in CircleColor. It preserves d's drawing state.
func DrawTileContacts(d *core.Drawing, grid TileGrid, contacts []TileContact, style DebugStyle)DrawTileContacts draws contact points and surface normal arrows for each TileContact returned by MoveAndSlide, using grid's tile dimensions to place each contact on the contacted tile face. It preserves d's drawing state.
func DrawTileGrid(d *core.Drawing, grid TileGrid, visible core.Bounds, style DebugStyle)DrawTileGrid draws solid and one-way collision tiles from grid that intersect visible. Solid tiles draw as full cell rectangles in SolidTileColor; one-way tiles draw as top-edge platforms with downward end ticks in OneWayTileColor. An empty visible bounds draws nothing. It preserves d's drawing state.
func DrawWorld(d *core.Drawing, w *World, visible core.Bounds, contacts []Contact, style DebugStyle)DrawWorld draws visible tiles from w.Tiles, every body in w.Bodies and every active contact with its normal arrow. It works directly inside a core.Canvas or debug overlay under any camera transform and preserves d's drawing state.
Tipos
type AreaConstraint struct {
Particles []int
RestArea float32
Pressure float32
Compliance float32
// contains filtered or unexported fields
}AreaConstraint preserves (or inflates, via Pressure) the signed area of a closed polygon loop of particles. Pressure <= 0 defaults to 1.0.
type AreaEffect struct {
GravityX, GravityY float32
LinearDamping float32
AngularDamping float32
HasLinearDamping bool
HasAngularDamping bool
SubmergedFraction float32
BuoyancyAccelX float32
BuoyancyAccelY float32
FluidLinearDrag float32
FluidAngularDrag float32
FluidVelX float32
FluidVelY float32
}AreaEffect holds the resolved gravity, damping, and fluid state at a point or shape from all overlapping active Triggers.
type AreaOverrideMode uint8AreaOverrideMode controls how a Trigger's AreaSettings combines its gravity or damping value with overlapping areas and the world or body default.
const (
// AreaOverrideNone leaves the world or body default unchanged (zero value).
AreaOverrideNone AreaOverrideMode = iota
// AreaOverrideCombine sums this area's value with other equal-priority
// Combine or Add areas (plus any higher-priority Add areas) and replaces
// lower-priority areas and the world/body default.
AreaOverrideCombine
// AreaOverrideReplace replaces lower- and equal-priority areas and the
// world/body default with this area's value. Higher-priority Add areas
// still add on top.
AreaOverrideReplace
// AreaOverrideAdd adds this area's value on top of lower-priority areas
// and the world/body default.
AreaOverrideAdd
)type AreaSettings struct {
// Priority orders overlapping areas: higher Priority takes precedence.
// Equal priorities break ties deterministically by trigger slice order.
Priority int
// GravityMode controls whether and how this area overrides gravity.
GravityMode AreaOverrideMode
// GravityX and GravityY are the directional gravity acceleration (units/s^2)
// used when PointGravity is false.
GravityX, GravityY float32
// PointGravity switches gravity from directional (GravityX, GravityY) to a
// radial field centered at (GravityPointX, GravityPointY).
PointGravity bool
// GravityPointX and GravityPointY are the world-space point-gravity center.
GravityPointX, GravityPointY float32
// GravityStrength is the acceleration magnitude (units/s^2) toward the point
// center (negative values repel).
GravityStrength float32
// GravityFalloff selects distance attenuation for PointGravity.
GravityFalloff GravityFalloff
// GravityUnitDistance is the reference distance for GravityFalloffInverse
// and GravityFalloffInverseSquare (defaults to 1 when <= 0), or the cutoff
// radius for GravityFalloffLinear (defaults to the trigger's outer radius
// when <= 0).
GravityUnitDistance float32
// LinearDampingMode controls whether and how LinearDamping overrides a body's damping.
LinearDampingMode AreaOverrideMode
// LinearDamping is the linear damping coefficient (1/s) applied according to LinearDampingMode.
LinearDamping float32
// AngularDampingMode controls whether and how AngularDamping overrides a body's damping.
AngularDampingMode AreaOverrideMode
// AngularDamping is the angular damping coefficient (1/s) applied according to AngularDampingMode.
AngularDamping float32
// FluidDensity enables Archimedes buoyancy when > 0 (mass per unit area in 2D).
// A body with implicit density Mass/Area settles at submerged fraction
// (Mass / Area) / FluidDensity.
FluidDensity float32
// FluidLinearDrag is the linear fluid drag coefficient (1/s), scaled by the
// submerged fraction of the body's bounds.
FluidLinearDrag float32
// FluidAngularDrag is the angular fluid drag coefficient (1/s), scaled by the
// submerged fraction of the body's bounds.
FluidAngularDrag float32
// FluidVelX and FluidVelY are the fluid flow velocity (units/s) relative to
// which FluidLinearDrag acts.
FluidVelX, FluidVelY float32
}AreaSettings configures gravity, damping, and buoyancy/fluid drag overrides for a 2D Trigger. The zero value has no physical effect.
func (a AreaSettings) Active() boolActive reports whether a enables any gravity, damping, or fluid effect.
type BendingConstraint struct {
A, B, C int
RestAngle float32
Compliance float32
// contains filtered or unexported fields
}BendingConstraint constrains the signed angle at hinge particle B between edges (A - B) and (C - B) toward RestAngle (in radians).
type Body struct {
ID int
Tag string
Shape Shape
VX, VY float32
Layer LayerMask
Mask LayerMask
Grounded bool
// OnCeiling, OnLeftWall and OnRightWall report contacts from the last MoveAndSlide, World.MoveAndSlide or CharacterBody.Move call.
OnCeiling bool
OnLeftWall bool
OnRightWall bool
// OneWay marks this body as a one-way platform collider: during World.MoveAndSlide (and CharacterBody.Move when using a World), it blocks movement only from its upward-facing side when the moving body starts outside on that side and does not have OneWayDrop set.
OneWay bool
// OneWayDrop lets the body fall through TileOneWay platforms, OneWay bodies and OneWay moving platforms during movement.
OneWayDrop bool
UserData any
}Body is a movable physics shape with velocity, collision filtering and tile contact state.
func NewBoxBody(x, y, w, h float32) *BodyNewBoxBody returns a Body whose Shape is a Box at (x, y) with size (w, h).
func NewCircleBody(x, y, r float32) *BodyNewCircleBody returns a Body whose Shape is a Circle centered at (x, y) with radius r.
func (b *Body) Bounds() BoxBounds returns the axis-aligned bounding box of b's shape.
func (b *Body) Translate(dx, dy float32)Translate shifts b's shape by (dx, dy).
type BodySnapshot struct {
ID int `json:"id"`
Tag string `json:"tag,omitempty"`
Shape Shape `json:"shape"`
VX float32 `json:"vx"`
VY float32 `json:"vy"`
Layer LayerMask `json:"layer"`
Mask LayerMask `json:"mask"`
Grounded bool `json:"grounded,omitempty"`
OnCeiling bool `json:"onCeiling,omitempty"`
OnLeftWall bool `json:"onLeftWall,omitempty"`
OnRightWall bool `json:"onRightWall,omitempty"`
OneWay bool `json:"oneWay,omitempty"`
OneWayDrop bool `json:"oneWayDrop,omitempty"`
}BodySnapshot is a JSON-serializable snapshot of one physics.Body.
type Box struct {
X, Y, W, H float32
}Box is an axis-aligned rectangle whose top-left corner sits at X, Y with width W and height H. A box with W <= 0 or H <= 0 is empty and never overlaps anything.
func (b Box) Bottom() float32Bottom returns the box's bottom edge (Y + H).
func (b Box) Contains(x, y float32) boolContains reports whether (x, y) lies inside or on the boundary of b.
func (b Box) Right() float32Right returns the box's right edge (X + W).
func (b Box) Translated(dx, dy float32) BoxTranslated returns a copy of b shifted by (dx, dy).
type Capsule struct {
X1, Y1, X2, Y2, R float32
}Capsule is a segment from (X1, Y1) to (X2, Y2) swept by radius R: two half circles joined by a rectangle. Its round ends let characters slide over tile seams and step edges without snagging. A capsule with R <= 0 is empty; one with equal endpoints is a circle.
func (c Capsule) Bounds() BoxBounds returns the tightest axis-aligned Box enclosing c, or a zero Box when c is empty.
func (c Capsule) Center() (x, y float32)Center returns the midpoint of c's segment.
func (c Capsule) Contains(x, y float32) boolContains reports whether (x, y) lies inside or on the boundary of c.
func (c Capsule) Empty() boolEmpty reports whether c has no positive radius.
func (c Capsule) Translated(dx, dy float32) CapsuleTranslated returns a copy of c shifted by (dx, dy).
type Chain struct {
Points []core.Point
Loop bool
}Chain is a static polyline through Points, closed back to the first point when Loop is true, for level terrain drawn as lines. Contacts at its interior vertices only use normals the neighbouring segments allow, so a body sliding or rolling along a flat run of segments never catches on the seams between them (Box2D's ghost collisions). Like Segment, it collides on both sides and never with another Chain or a Segment.
An open chain needs at least 2 points and a loop at least 3; consecutive points must differ.
func (c *Chain) Bounds() BoxBounds returns the axis-aligned Box spanning every point of c.
func (c *Chain) Empty() boolEmpty reports whether c is nil or has too few points for one segment (two, or three for a loop).
func (c *Chain) Segment(i int) SegmentSegment returns segment i of c, from Points[i] to the next point.
func (c *Chain) SegmentCount() intSegmentCount returns the number of segments in c.
func (c *Chain) Translated(dx, dy float32) *ChainTranslated returns a new Chain with every point of c shifted by (dx, dy).
type CharacterBody struct {
Body *Body
// MaxSlopeAngle is the steepest walkable slope angle in radians.
// Values <= 0 default to DefaultMaxSlopeAngle (45 degrees).
MaxSlopeAngle float32
// SnapDist is the maximum downward distance to snap onto a walkable slope while walking downhill, or onto a tile top when walking off the lower end of a slope.
SnapDist float32
// Grounded reports whether the character is supported by a tile, walkable slope, or platform.
Grounded bool
// GroundNormal is the unit surface normal of the ground supporting the character, or zero when airborne.
GroundNormal core.Point
// Riding is the MovingPlatform currently carrying the character, or nil.
Riding *MovingPlatform
// World is an optional physics World whose GravityX/GravityY and Triggers
// override gravity and damping for this character during Move.
World *World
// GravityScale multiplies the effective gravity applied when World is set.
// NewCharacterBody initializes it to 1; on a zero-initialized CharacterBody
// literal it defaults to 1 unless SetGravityScale(0) is called.
GravityScale float32
// contains filtered or unexported fields
}CharacterBody wraps a Body with kinematic platformer movement supporting tiles, walkable and steep slopes, downhill snapping, and moving platforms.
func NewCharacterBody(body *Body) *CharacterBodyNewCharacterBody returns a CharacterBody wrapping body with DefaultMaxSlopeAngle and a default SnapDist of 8.
func (c *CharacterBody) EffectiveGravity() (gx, gy float32)EffectiveGravity returns the scaled gravity acceleration acting on c from c.World and any overlapping Triggers, or (0, 0) when c.World is nil.
func (c *CharacterBody) EffectiveGravityScale() float32EffectiveGravityScale returns c's active gravity multiplier, defaulting to 1 when unset on a zero-initialized CharacterBody.
func (c *CharacterBody) Move(grid TileGrid, slopes []Slope, platforms []*MovingPlatform, dt time.Duration) MoveResultMove advances c by carrying it with any riding MovingPlatform and then moving by (Body.VX*dt, Body.VY*dt), resolving solid and one-way tiles, moving platforms, walkable slopes (up to MaxSlopeAngle), downhill slope snapping (up to SnapDist), and blocking steeper slopes. When c.World is non-nil, Move integrates effective gravity (world gravity combined with overlapping Trigger.Area overrides, scaled by GravityScale) along with area linear damping and fluid linear drag into Body.VX/Body.VY before moving, and also collides against bodies (including OneWay bodies) and static RigidBody colliders in c.World (using c.World.Tiles when grid is nil).
func (c *CharacterBody) MoveWorld(world *World, slopes []Slope, platforms []*MovingPlatform, dt time.Duration) MoveResultMoveWorld advances c against world (its Bodies, Tiles, and static RigidBody colliders in world.RigidWorld) together with slopes and platforms. Area gravity and damping are applied only when c.World is set, so callers such as platformer.Controller that integrate their own gravity can pass a World without double-applying gravity.
func (c *CharacterBody) SetGravityScale(scale float32)SetGravityScale sets the per-character gravity multiplier on c, including 0 for weightless characters. Non-finite values are ignored.
type Circle struct {
X, Y, R float32
}Circle is a disk centered at X, Y with radius R. A circle with R <= 0 is empty and never overlaps anything.
func (c Circle) Bounds() BoxBounds returns the tightest axis-aligned Box enclosing c.
func (c Circle) Contains(x, y float32) boolContains reports whether (x, y) lies inside or on the boundary of c.
func (c Circle) Empty() boolEmpty reports whether c has no positive radius.
func (c Circle) Translated(dx, dy float32) CircleTranslated returns a copy of c shifted by (dx, dy).
type Contact struct {
Hit bool
NormalX, NormalY float32
Depth float32
PointX, PointY float32
}Contact describes an overlap between two shapes A and B.
When Hit is true, (NormalX, NormalY) is a unit vector pointing from B toward A: translating A by (NormalX*Depth, NormalY*Depth) separates A from B along the minimum translation axis. Shapes that only touch along an edge or point with zero penetration report Hit == false.
func TestBoxBox(a, b Box) ContactTestBoxBox tests whether boxes a and b overlap. The returned Contact normal points from b toward a. For concentric boxes where horizontal and vertical penetration depths are equal, the normal falls back to (0, -1).
func TestBoxCircle(a Box, b Circle) ContactTestBoxCircle tests whether box a and circle b overlap. The returned Contact normal points from b toward a.
func TestCircleBox(a Circle, b Box) ContactTestCircleBox tests whether circle a and box b overlap. The returned Contact normal points from b toward a.
func TestCircleCircle(a, b Circle) ContactTestCircleCircle tests whether circles a and b overlap. The returned Contact normal points from b toward a. Concentric circles use the deterministic fallback normal (0, -1).
func TestShapes(a, b Shape) ContactTestShapes tests whether shapes a and b overlap. The returned Contact normal points from b toward a, and translating a by (NormalX*Depth, NormalY*Depth) separates them.
Pairs of boxes and circles use TestBoxBox, TestBoxCircle, TestCircleBox and TestCircleCircle. Every pair involving a Polygon, Capsule, Segment or Chain uses the separating axis test on the shapes' cores plus their rounding radii, reporting the contact point between the two surfaces. Segments and chains collide with every shape with area but never with each other; a chain reports its deepest segment contact, using only normals its neighbouring segments allow at interior vertices.
type ContactEvent struct {
Kind ContactEventKind
BodyA, BodyB *RigidBody
Tile bool
Col, Row int
TileFlags TileFlags
Point core.Point
// NormalX and NormalY form the unit contact normal from BodyA toward BodyB, or toward the tile.
NormalX, NormalY float32
ApproachSpeed float32
}ContactEvent reports a contact between two bodies of a RigidWorld, or between a body and its Tiles, that began or ended in the last Step. It is the 2D counterpart of physics3d.ContactEvent, which also reports contacts that stay and whose normal points the other way, from BodyB toward BodyA.
BodyA and BodyB are in RigidWorld.Bodies order. A contact with Tiles has Tile set, BodyB nil and the body in BodyA, and the bodies touching any number of tiles count as one contact, so a crate sliding across a tiled floor begins touching it once. Col, Row and TileFlags name the tile the event's point is on.
A ContactBegin event carries the point of the contact that was approaching fastest, the unit normal there pointing from BodyA toward BodyB (or the tile), and ApproachSpeed, how fast in pixels per second the two closed along the normal before the step resolved the contact, which is the impact speed for playing a sound or dealing damage. A ContactEnd event carries the bodies and, for Tiles, the last tile touched, with no point, normal or speed.
type ContactEventKind uint8ContactEventKind says whether a ContactEvent or SensorEvent reports a touch that began or one that ended.
const (
// ContactBegin reports two bodies, or a body and Tiles, that touch after a Step and did not before it.
ContactBegin ContactEventKind = iota
// ContactEnd reports two bodies, or a body and Tiles, that touched before a Step and are now more than 0.25 px apart, or one of which left RigidWorld.Bodies, became a sensor or can no longer collide with the other.
ContactEnd
)func (k ContactEventKind) String() stringString returns "begin" or "end".
type DebugStyle struct {
BoxColor core.Color
CircleColor core.Color
SolidTileColor core.Color
OneWayTileColor core.Color
ContactColor core.Color
NormalColor core.Color
RayColor core.Color
VelocityColor core.Color
// PolygonColor outlines polygons, CapsuleColor capsules, and SegmentColor segments and chains.
PolygonColor core.Color
CapsuleColor core.Color
SegmentColor core.Color
LineWidth float32
Zoom float32
NormalLength float32
ContactRadius float32
// VelocityScale draws each body's velocity vector scaled by this duration in seconds
// when positive. Leave 0 to omit velocity vectors.
VelocityScale float32
}DebugStyle configures colors and screen-space annotation sizes for physics debug drawing. Zero fields fall back to DefaultDebugStyle values.
LineWidth, NormalLength and ContactRadius are given in screen points and divided by the active camera zoom (Zoom when positive, otherwise inferred from the drawing's current transform) so outlines, contact markers and normal arrows stay crisp at every zoom.
func DefaultDebugStyle() DebugStyleDefaultDebugStyle returns a high-contrast DebugStyle suitable for drawing over game scenes.
type DistanceConstraint struct {
A, B int
RestLength float32
Compliance float32
MaxOnly bool
// contains filtered or unexported fields
}DistanceConstraint constrains the Euclidean distance between particles A and B. When MaxOnly is true, the constraint acts as a unilateral tether that only pulls particles together when their distance exceeds RestLength.
type DistanceJoint struct {
A, B *RigidBody
AnchorA core.Point
AnchorB core.Point
Length float32
MinLength float32 // optional minimum distance (active when MinLength > 0 or MaxLength > 0)
MaxLength float32 // optional maximum distance (active when > 0; slack between MinLength and MaxLength)
MaxOnly bool // rope / max-distance mode: slack when distance <= max length, pulls only when stretched
Stiffness float32
Compliance float32
Damping float32
BreakForce float32 // max reaction force before breaking (<= 0 disables)
BreakTorque float32 // max reaction torque before breaking (<= 0 disables)
CollideConnected bool
// contains filtered or unexported fields
}DistanceJoint constrains two local anchor points on bodies A and B to stay at a target Length (or within [MinLength, MaxLength], or <= Length when MaxOnly is true for rope/tether mode). With default zero Compliance and Stiffness, it acts as a rigid rod; positive Compliance or Stiffness in (0, 1) softens the constraint.
func NewDistanceJoint(a, b *RigidBody, anchorA, anchorB core.Point, length float32) *DistanceJointNewDistanceJoint creates a DistanceJoint between local anchors on a and b. If length <= 0 and both bodies are non-nil, Length is initialized to the current distance between the anchors.
func NewRopeJoint(a, b *RigidBody, anchorA, anchorB core.Point, maxLength float32) *DistanceJointNewRopeJoint creates a DistanceJoint configured in rope/max-distance mode (MaxOnly = true), allowing the anchors to move closer than maxLength without pushing apart while pulling taut when distance reaches maxLength. If maxLength <= 0, it initializes to the current anchor distance.
func (r *DistanceJoint) Broken() boolBroken reports whether the joint has exceeded its break threshold and been removed.
func (r *DistanceJoint) ReactionForce() (fx, fy float32)ReactionForce returns the world-space constraint force (fx, fy) applied to body B (or the attached body for MouseJoint) during the most recent RigidWorld.Step.
func (r *DistanceJoint) ReactionTorque() float32ReactionTorque returns the scalar constraint torque (clockwise positive in screen space) applied to body B during the most recent RigidWorld.Step.
type GravityFalloff uint8GravityFalloff controls how point-gravity acceleration varies with distance from (GravityPointX, GravityPointY).
const (
// GravityFalloffNone applies constant GravityStrength regardless of distance (zero value).
GravityFalloffNone GravityFalloff = iota
// GravityFalloffLinear decreases acceleration linearly from GravityStrength at
// distance 0 to 0 at GravityUnitDistance (or the trigger shape's outer radius
// when GravityUnitDistance <= 0).
GravityFalloffLinear
// GravityFalloffInverse scales acceleration as GravityStrength * (unitDist / dist).
GravityFalloffInverse
// GravityFalloffInverseSquare scales acceleration as GravityStrength * (unitDist / dist)^2.
GravityFalloffInverseSquare
)type Grid struct {
Cols, Rows int
TileWidth, TileHeight float32
// OriginX and OriginY place cell (0, 0)'s top-left corner in world coordinates.
OriginX, OriginY float32
Cells []TileFlags
}Grid is a row-major TileGrid backed by a flat slice of TileFlags.
func NewGrid(cols, rows int, tileWidth, tileHeight float32) *GridNewGrid returns a Grid with cols columns and rows rows of tiles sized tileWidth by tileHeight.
func (g *Grid) FillRect(col, row, w, h int, flags TileFlags)FillRect sets flags on all cells in the rectangle [col, col+w) x [row, row+h).
func (g *Grid) GridOrigin() (x, y float32)GridOrigin returns the world-space origin of cell (0, 0).
func (g *Grid) GridSize() (cols, rows int)GridSize returns the grid dimensions in tiles.
func (g *Grid) Set(col, row int, flags TileFlags)Set writes flags to (col, row), ignoring coordinates outside the grid.
func (g *Grid) TileFlagsAt(col, row int) TileFlagsTileFlagsAt returns the flags at (col, row), or 0 when out of bounds.
func (g *Grid) TileSize() (width, height float32)TileSize returns the tile width and height.
type GridSnapshot struct {
Cols int `json:"cols"`
Rows int `json:"rows"`
TileWidth float32 `json:"tileWidth"`
TileHeight float32 `json:"tileHeight"`
OriginX float32 `json:"originX,omitempty"`
OriginY float32 `json:"originY,omitempty"`
Cells []TileFlags `json:"cells,omitempty"`
}GridSnapshot is a JSON-serializable snapshot of a *Grid tile grid.
type Joint interface {
// contains filtered or unexported methods
}Joint constrains the relative motion of one or two RigidBodies inside RigidWorld.Step.
type JointBreakEvent struct {
Joint Joint
BodyA *RigidBody
BodyB *RigidBody
ForceX float32
ForceY float32
Torque float32
}JointBreakEvent reports a joint that broke during RigidWorld.Step because its reaction force or torque exceeded its BreakForce or BreakTorque threshold.
type LayerMask uint32LayerMask is a 32-bit bitmask identifying collision layers or collision filter masks. A zero LayerMask defaults to LayerAll so bodies, triggers and queries with unset layer fields remain compatible with unfiltered collision checks.
func LayerBit(index uint) LayerMaskLayerBit returns the LayerMask with bit index set, or 0 when index >= 32.
type MotionMode uint8MotionMode controls how World.MoveAndSlideWith classifies contact normals into floor, wall and ceiling states.
const (
// MotionGrounded classifies contacts against UpDirection and FloorMaxAngle into floor, wall and ceiling
// states (the zero value, for side-view platformers).
MotionGrounded MotionMode = iota
// MotionFloating treats every contact as a wall without floor or ceiling classification (for top-down games).
MotionFloating
)type MouseJoint struct {
Body *RigidBody
Anchor core.Point // local anchor point on Body
Target core.Point // world-space target point
MaxForce float32 // maximum pulling force (must be > 0 to apply force)
FrequencyHz float32 // spring natural frequency in Hz (default 5 in NewMouseJoint)
DampingRatio float32 // damping ratio for FrequencyHz (default 0.7 in NewMouseJoint)
Stiffness float32 // optional direct spring stiffness (used when FrequencyHz <= 0)
Damping float32 // optional direct damping (used when FrequencyHz <= 0)
BreakForce float32 // max reaction force before breaking (<= 0 disables)
BreakTorque float32 // max reaction torque before breaking (<= 0 disables)
// contains filtered or unexported fields
}MouseJoint (target joint) pulls a local Anchor on Body toward a settable world Target point using a damped spring capped at MaxForce.
func NewMouseJoint(body *RigidBody, worldTarget core.Point, maxForce float32) *MouseJointNewMouseJoint creates a MouseJoint grabbing body at worldTarget with a maximum pulling force maxForce, default FrequencyHz = 5, and DampingRatio = 0.7.
func (r *MouseJoint) Broken() boolBroken reports whether the joint has exceeded its break threshold and been removed.
func (r *MouseJoint) ReactionForce() (fx, fy float32)ReactionForce returns the world-space constraint force (fx, fy) applied to body B (or the attached body for MouseJoint) during the most recent RigidWorld.Step.
func (r *MouseJoint) ReactionTorque() float32ReactionTorque returns the scalar constraint torque (clockwise positive in screen space) applied to body B during the most recent RigidWorld.Step.
func (j *MouseJoint) SetTarget(target core.Point)SetTarget updates the world-space target point that MouseJoint pulls Body.Anchor toward.
type MoveOptions struct {
// Mode selects MotionGrounded (default) or MotionFloating (top-down, every hit is a wall).
Mode MotionMode
// UpX and UpY define the upward direction for floor, wall and ceiling classification in MotionGrounded mode
// (and the pass-through direction for one-way colliders). When both are 0, defaults to (0, -1) (screen up).
UpX, UpY float32
// FloorMaxAngle is the steepest angle in radians between a contact normal and Up that counts as a floor
// (or between a contact normal and -Up that counts as a ceiling). Values <= 0 default to DefaultFloorMaxAngle (45 degrees).
FloorMaxAngle float32
// MaxSlides is the maximum number of slide iterations per call. Values <= 0 default to DefaultMaxSlides (4).
MaxSlides int
// Mask optionally restricts which collider kinds are tested. Zero defaults to QueryAll
// (World.Bodies, static RigidBody colliders, TileSolid and TileOneWay tiles).
Mask QueryMask
// RigidBodies supplies optional extra static RigidBody colliders to test in addition to World.RigidWorld. Dynamic, kinematic and sensor rigid bodies are ignored.
RigidBodies []*RigidBody
// Exclude skips the listed Body pointers during movement in addition to the moving body itself.
Exclude []*Body
}MoveOptions configures World.MoveAndSlideWith. The zero value uses MotionGrounded with Up (0, -1), FloorMaxAngle DefaultFloorMaxAngle (45 degrees), MaxSlides DefaultMaxSlides (4), and collides against World.Bodies, World.Tiles (solid and one-way), and the static RigidBody colliders in World.RigidWorld that are not sensors.
type MoveResult struct {
Contacts []TileContact
Collisions []SlideCollision
Grounded bool
OnWall bool
OnCeiling bool
OnLeftWall bool
OnRightWall bool
}MoveResult summarizes the contacts and surface flags from one MoveAndSlide or CharacterBody.Move call.
func MoveAndSlide(b *Body, grid TileGrid, dt time.Duration) MoveResultMoveAndSlide advances b by (VX*dt, VY*dt) and resolves axis-aligned collisions against grid, resolving X before Y. It zeroes velocity along blocked axes, updates b's Grounded, OnCeiling, OnLeftWall and OnRightWall flags, and subdivides large displacements so fast bodies do not tunnel through single-tile walls or platforms.
Tiles are resolved against the bounding box of b's shape, so a Polygon or Capsule body moves as its bounds do and keeps its shape; the whole shape is translated by the resolved movement.
type MovingPlatform struct {
Body *Body
DeltaX, DeltaY float32
OneWay bool
}MovingPlatform is a kinematic platform body with its per-step displacement (DeltaX, DeltaY). Callers update the platform's Body position and record its displacement in DeltaX and DeltaY (or call Move) before stepping CharacterBody.Move.
func (p *MovingPlatform) Move(dx, dy float32)Move records (dx, dy) as the platform's per-step displacement and translates Body accordingly.
type OverlapHit struct {
// Body is non-nil when the hit is a body from World.Bodies.
Body *Body
// RigidBody is non-nil when the hit is a body from RigidWorld.Bodies.
RigidBody *RigidBody
// Tile is true when the hit is a tile from World.Tiles or RigidWorld.Tiles at (Col, Row).
Tile bool
Col, Row int
TileFlags TileFlags
// Contact holds the overlap normal (pointing from the hit toward the query shape), depth and contact point.
Contact Contact
}OverlapHit is one body or tile overlapping a query shape.
type Particle struct {
X, Y float32
PrevX, PrevY float32
VX, VY float32
InvMass float32
Radius float32
Friction float32
Restitution float32
Pinned bool
Layer LayerMask
Mask LayerMask
// contains filtered or unexported fields
}Particle is a 2D point mass simulated by SoftWorld using Extended Position-Based Dynamics (XPBD).
Coordinates follow NSGo's screen space (+X right, +Y down). Set Pinned to true or InvMass to 0 to fix a particle in place. Zero Layer or Mask values default to LayerAll.
func (p *Particle) ApplyForce(fx, fy float32)ApplyForce accumulates a world-space force applied to p during the next SoftWorld.Step.
func (p *Particle) IsPinned() boolIsPinned reports whether p has infinite mass (Pinned is true or InvMass <= 0).
func (p *Particle) SetMass(mass float32)SetMass sets p's inverse mass to 1/mass when mass > 0, or 0 when mass <= 0.
type Polygon struct {
Vertices [MaxPolygonVertices]core.Point
Count int
Radius float32
}Polygon is a convex polygon of 3 to MaxPolygonVertices vertices in world coordinates, optionally rounded by Radius: the shape is every point within Radius of the polygon, as Box2D's rounded polygons are. Rounding keeps stacked props and characters from catching on each other's corners.
Vertices[:Count] wind with a positive signed area in NSGo's X-right, Y-down space, which is clockwise on screen, and the outward normal of the edge from vertex i to vertex i+1 is (dy, -dx) normalized. Build polygons with NewPolygon or NewBoxPolygon, which compute the convex hull and the winding; a Polygon written by hand must already be convex, wound that way and free of repeated vertices.
func NewBoxPolygon(cx, cy, w, h, angle float32) PolygonNewBoxPolygon returns a w by h rectangle centered at (cx, cy) and rotated by angle radians (clockwise on screen), as a Polygon for ramps, wedges and rotated props. Like a Box, a rectangle whose w or h is not positive is empty: NewBoxPolygon then returns the zero Polygon, which reports Empty, as it does when an argument is not finite.
func NewPolygon(points []core.Point, radius float32) (Polygon, bool)NewPolygon returns the convex hull of points rounded by radius. It merges points closer than 1e-4 and drops vertices that lie on an edge. It reports false when the hull has fewer than 3 or more than MaxPolygonVertices vertices, when a coordinate is not finite, or when radius is negative or not finite.
func (p Polygon) Bounds() BoxBounds returns the tightest axis-aligned Box enclosing p and its rounding, or a zero Box when p is empty.
func (p Polygon) Contains(x, y float32) boolContains reports whether (x, y) lies inside or on the boundary of p, including its rounding.
func (p Polygon) Empty() boolEmpty reports whether p holds no valid polygon: fewer than 3 or more than MaxPolygonVertices vertices, or a negative Radius.
func (p Polygon) Translated(dx, dy float32) PolygonTranslated returns a copy of p shifted by (dx, dy).
type PrismaticJoint struct {
A, B *RigidBody
AnchorA core.Point
AnchorB core.Point
LocalAxisA core.Point // unit slide axis in A's local space (defaults to {X: 1, Y: 0})
ReferenceAngle float32 // locked relative angle B.Angle - A.Angle
EnableLimit bool
LowerTranslation float32
UpperTranslation float32
EnableMotor bool
MotorSpeed float32 // target linear speed along slide axis (units/s)
MaxMotorForce float32 // max linear motor force
BreakForce float32 // max reaction force before breaking (<= 0 disables)
BreakTorque float32 // max reaction torque before breaking (<= 0 disables)
CollideConnected bool
// contains filtered or unexported fields
}PrismaticJoint (slider) constrains body B to translate relative to body A along LocalAxisA with locked relative orientation, optional translation limits, a linear motor, and break thresholds.
func NewPrismaticJoint(a, b *RigidBody, worldAnchor, worldAxis core.Point) *PrismaticJointNewPrismaticJoint creates a PrismaticJoint sliding along worldAxis through worldAnchor. If worldAxis is zero, LocalAxisA defaults to {X: 1, Y: 0}.
func (r *PrismaticJoint) Broken() boolBroken reports whether the joint has exceeded its break threshold and been removed.
func (j *PrismaticJoint) JointSpeed() float32JointSpeed returns the current relative linear velocity along the world slide axis.
func (j *PrismaticJoint) JointTranslation() float32JointTranslation returns the current signed displacement of AnchorB relative to AnchorA along the world slide axis.
func (r *PrismaticJoint) ReactionForce() (fx, fy float32)ReactionForce returns the world-space constraint force (fx, fy) applied to body B (or the attached body for MouseJoint) during the most recent RigidWorld.Step.
func (r *PrismaticJoint) ReactionTorque() float32ReactionTorque returns the scalar constraint torque (clockwise positive in screen space) applied to body B during the most recent RigidWorld.Step.
type QueryMask uint32QueryMask selects which targets a query inspects. A zero QueryMask is treated as QueryAll.
const (
// QueryBodies includes bodies in World.Bodies.
QueryBodies QueryMask = 1 << iota
// QueryTiles includes solid tiles (TileSolid) in World.Tiles.
QueryTiles
// QueryOneWay includes one-way platform tiles (TileOneWay) in World.Tiles.
// During raycasts, a one-way tile only hits when the ray enters its top edge moving downward.
QueryOneWay
// QueryAll includes bodies, solid tiles and one-way tiles.
QueryAll = QueryBodies | QueryTiles | QueryOneWay
)const QuerySensors QueryMask = 1 << 3QuerySensors includes RigidBody sensors in RigidWorld queries, which QueryBodies and QueryAll leave out. World queries ignore it.
type RaycastHit struct {
// T is the normalized distance along the ray from From (0) to To (1).
T float32
// Point is the world-space intersection point.
Point core.Point
// NormalX and NormalY form the unit surface normal at Point, or (0, 0) when the ray starts inside a shape. Segments and chains are hit from either side, with the normal facing the ray's start; a ray running along one misses it.
NormalX, NormalY float32
// Body is non-nil when the hit is a body from World.Bodies.
Body *Body
// RigidBody is non-nil when the hit is a body from RigidWorld.Bodies.
RigidBody *RigidBody
// Tile is true when the hit is a tile from World.Tiles or RigidWorld.Tiles at (Col, Row).
Tile bool
Col, Row int
TileFlags TileFlags
}RaycastHit is one intersection of a ray segment with a body or tile.
type RevoluteJoint struct {
A, B *RigidBody
AnchorA core.Point
AnchorB core.Point
ReferenceAngle float32 // initial relative angle B.Angle - A.Angle
EnableLimit bool
LowerAngle float32 // radians
UpperAngle float32 // radians
EnableMotor bool
MotorSpeed float32 // target relative angular velocity (rad/s)
MaxMotorTorque float32 // maximum motor torque
BreakForce float32 // max reaction force before breaking (<= 0 disables)
BreakTorque float32 // max reaction torque before breaking (<= 0 disables)
CollideConnected bool
// contains filtered or unexported fields
}RevoluteJoint pins a local anchor on A to a local anchor on B so both world anchor points remain coincident while allowing relative rotation around the hinge, with optional angular limits, angular motor, and break thresholds.
func NewRevoluteJoint(a, b *RigidBody, worldPivot core.Point) *RevoluteJointNewRevoluteJoint creates a RevoluteJoint pinning a and b together at worldPivot.
func (r *RevoluteJoint) Broken() boolBroken reports whether the joint has exceeded its break threshold and been removed.
func (j *RevoluteJoint) JointAngle() float32JointAngle returns the current relative rotation in radians: B.Angle - A.Angle - ReferenceAngle.
func (j *RevoluteJoint) JointSpeed() float32JointSpeed returns the current relative angular velocity in rad/s: B.AngularVel - A.AngularVel.
func (r *RevoluteJoint) ReactionForce() (fx, fy float32)ReactionForce returns the world-space constraint force (fx, fy) applied to body B (or the attached body for MouseJoint) during the most recent RigidWorld.Step.
func (r *RevoluteJoint) ReactionTorque() float32ReactionTorque returns the scalar constraint torque (clockwise positive in screen space) applied to body B during the most recent RigidWorld.Step.
type RigidAttachment struct {
Particle int
Body *RigidBody
LocalAnchor core.Point
Compliance float32
// contains filtered or unexported fields
}RigidAttachment couples particle Particle to RigidBody Body at LocalAnchor. When Compliance is 0, the attachment acts as a rigid two-way pin; positive Compliance makes it elastic while still transferring reaction impulses back to Body.
type RigidBody struct {
ID int
Tag string
Shape Shape
X, Y float32
VX, VY float32
Angle float32
AngularVel float32
Mass float32
InvMass float32
Inertia float32
InvInertia float32
Restitution float32
Friction float32
LinearDamping float32
AngularDamping float32
// GravityScale multiplies the effective gravity applied to this body during
// RigidWorld.Step. NewRigidBox and NewRigidCircle initialize it to 1; on a
// zero-initialized RigidBody literal it defaults to 1 unless SetGravityScale(0)
// is called or GravityScale is modified after AddBody.
GravityScale float32
Static bool
// Kinematic makes the body move only as it is told: by VX, VY and AngularVel, which Step integrates with no gravity, force, damping or area effect, or by SetTargetPose. The solver treats it as having infinite mass, so it pushes and carries the dynamic bodies it touches and nothing it touches moves it; it never collides with static or other kinematic bodies or tiles, and never sleeps. Step zeroes InvMass and InvInertia while it is set and derives them again from Mass and Inertia once it is cleared. Static takes precedence: a body with both set is static. A kinematic body never uses Mass, but NewRigidBox, NewRigidCircle and NewRigidBody make a body static when its mass is not positive, so build it with a positive mass or clear Static after building it with zero.
Kinematic bool
// Sensor makes the body detect overlaps instead of colliding: it takes part in no contact, is not hit by continuous collision, and reports a SensorEvent when a body that is not a sensor starts or stops overlapping it. A sensor moves as its kind (static, kinematic or dynamic) says, and never detects another sensor.
Sensor bool
Layer LayerMask
Mask LayerMask
// Bullet sweeps the body against static bodies on every step and stops it at the first surface it reaches, so it never passes into one, except that a surface it already touches at the start of a step and is driven into by no more than half its half thickness is left to the regular contacts. Without it the body is swept only on steps where a point of it moves farther than half its thickness, when it could otherwise pass through a thin wall, and a shallow overlap is left to the regular contacts.
Bullet bool
UserData any
// contains filtered or unexported fields
}RigidBody is a 2D dynamic or static rigid body simulated by RigidWorld.
(X, Y) is the world-space center of mass and Angle is the rotation in radians (increasing clockwise in NSGo's +X right, +Y down screen space). Shape holds the body's geometry in world space and is synchronized with (X, Y) after each simulation step. A Box keeps its axis-aligned extents centered on (X, Y) and a Circle its center, with Angle applied by the solver; a Polygon, Capsule, Segment or Chain is stored rotated by Angle, so World queries and debug drawing see its true pose.
A Polygon or Capsule assigned to Shape, in a struct literal or between steps, keeps its world position: the next Step moves (X, Y) to its Centroid, so the body turns about its center of mass, and replaces an Inertia the body derived itself (left zero, or computed by a constructor or an earlier Step) with the new shape's MomentOfInertia; an Inertia set to any other value is kept. A Segment or Chain is anchored at the current (X, Y).
Segment and Chain shapes have no area, so a body holding one is always static.
func NewRigidBody(s Shape, mass float32) *RigidBodyNewRigidBody returns a RigidBody holding s, a shape in world coordinates, with its center of mass at s's Centroid and its inertia computed from s for mass spread evenly over its area. If mass <= 0, or s is a Segment or Chain, the body is static. A Box or Circle gives the same body as NewRigidBox or NewRigidCircle.
func NewRigidBox(x, y, w, h, mass float32) *RigidBodyNewRigidBox returns a dynamic rectangular RigidBody centered at (x, y) with size (w, h) and mass. If mass <= 0, the body is created as Static.
func NewRigidCircle(x, y, r, mass float32) *RigidBodyNewRigidCircle returns a dynamic circular RigidBody centered at (x, y) with radius r and mass. If mass <= 0, the body is created as Static.
func NewStaticRigidBody(s Shape) *RigidBodyNewStaticRigidBody returns a static (infinite-mass) RigidBody holding s, such as level terrain built from a Polygon, Segment or Chain.
func NewStaticRigidBox(x, y, w, h float32) *RigidBodyNewStaticRigidBox returns a static (infinite-mass) rectangular RigidBody centered at (x, y) with size (w, h).
func NewStaticRigidCircle(x, y, r float32) *RigidBodyNewStaticRigidCircle returns a static (infinite-mass) circular RigidBody centered at (x, y) with radius r.
func (b *RigidBody) ApplyForce(fx, fy float32)ApplyForce accumulates a world-space force applied to b's center of mass on the next Step. A static or kinematic body ignores it.
func (b *RigidBody) ApplyImpulse(ix, iy float32)ApplyImpulse immediately changes b's linear velocity by (ix, iy)*InvMass. A static or kinematic body ignores it.
func (b *RigidBody) ApplyImpulseAtPoint(ix, iy float32, worldPoint core.Point)ApplyImpulseAtPoint immediately applies world-space impulse (ix, iy) at worldPoint, updating both linear and angular velocity. A static or kinematic body ignores it.
func (b *RigidBody) ApplyTorque(torque float32)ApplyTorque accumulates a torque applied to b on the next Step. A static or kinematic body ignores it.
func (b *RigidBody) EffectiveGravityScale() float32EffectiveGravityScale returns b's active gravity multiplier. For a zero-initialized RigidBody literal whose GravityScale has not been set, this defaults to 1.
func (b *RigidBody) LocalToWorld(local core.Point) core.PointLocalToWorld transforms a local-space point relative to b's center into world coordinates.
func (b *RigidBody) SetGravityScale(scale float32)SetGravityScale sets the per-body gravity multiplier on b, including 0 for weightless bodies. Non-finite values are ignored.
func (b *RigidBody) SetTargetPose(x, y, angle float32)SetTargetPose moves a kinematic body to (x, y) at angle over the next Step, the way an animation drives a moving platform. That Step sets VX, VY and AngularVel to the velocity that covers the distance in one step, so the bodies the platform pushes and carries move with it, and ends with the body exactly at the pose. A body given no new target before the following Step stops there, unless its velocity was changed in between. Step ignores a target while the body is not Kinematic, and SetTargetPose ignores a pose that is not finite.
Assigning X, Y and Angle directly also moves a kinematic body, but as a teleport: the bodies it lands in are pushed out without being given its motion.
func (b *RigidBody) Sleeping() boolSleeping reports whether b rests in a sleeping island. RigidWorld neither moves nor solves a sleeping body until something wakes it: Wake, a force, torque or impulse, a change to its pose or velocity, a joint or contact linking it to an awake body, or the removal or movement of a static body it touches.
func (b *RigidBody) Wake()Wake makes b take part in the next Step and restarts the time it must rest before it can sleep again. The rest of b's island wakes with it on that step.
func (b *RigidBody) WorldShape() ShapeWorldShape returns b's shape at its current pose in world coordinates: a Box or Circle where (X, Y) puts it, a Box turned by a non-zero Angle as a Polygon, and a Polygon, Capsule, Segment or Chain as Step last placed it, or where its current pose puts it if it was moved since.
func (b *RigidBody) WorldToLocal(world core.Point) core.PointWorldToLocal transforms a world-space point into b's local coordinate frame.
type RigidBodySnapshot struct {
ID int `json:"id"`
Tag string `json:"tag,omitempty"`
Shape Shape `json:"shape"`
X float32 `json:"x"`
Y float32 `json:"y"`
VX float32 `json:"vx"`
VY float32 `json:"vy"`
Angle float32 `json:"angle"`
AngularVel float32 `json:"angularVel"`
Mass float32 `json:"mass"`
InvMass float32 `json:"invMass"`
Inertia float32 `json:"inertia"`
InvInertia float32 `json:"invInertia"`
Restitution float32 `json:"restitution"`
Friction float32 `json:"friction"`
LinearDamping float32 `json:"linearDamping"`
AngularDamping float32 `json:"angularDamping"`
GravityScale float32 `json:"gravityScale"`
GravityScaleSet bool `json:"gravityScaleSet,omitempty"`
Static bool `json:"static,omitempty"`
Layer LayerMask `json:"layer"`
Mask LayerMask `json:"mask"`
ForceX float64 `json:"forceX,omitempty"`
ForceY float64 `json:"forceY,omitempty"`
Torque float64 `json:"torque,omitempty"`
// Local is the body's Polygon, Capsule, Segment or Chain shape relative to (X, Y) at Angle 0, which the solver rotates each step; nil for a Box or Circle.
Local *Shape `json:"local,omitempty"`
// Synced reports that Shape is the world shape last derived from Local at pose (SyncX, SyncY, SyncAngle), so it is not re-derived on the next step.
Synced bool `json:"synced,omitempty"`
SyncX float32 `json:"syncX,omitempty"`
SyncY float32 `json:"syncY,omitempty"`
SyncAngle float32 `json:"syncAngle,omitempty"`
// DerivedInertia is the Inertia the body last derived from its shape.
DerivedInertia float32 `json:"derivedInertia,omitempty"`
Bullet bool `json:"bullet,omitempty"`
// Sleeping reports that the body rests in a sleeping island; SleepEnv is the gravity, damping and fluid it fell asleep in.
Sleeping bool `json:"sleeping,omitempty"`
SleepEnv *AreaEffect `json:"sleepEnv,omitempty"`
// SleepTime is how long, in seconds, the body has moved slower than the sleep thresholds.
SleepTime float64 `json:"sleepTime,omitempty"`
// RestValid reports that (RestX, RestY, RestAngle) is the pose the body ended its last step with, which tells the next step whether it was moved by hand.
RestValid bool `json:"restValid,omitempty"`
RestX float32 `json:"restX,omitempty"`
RestY float32 `json:"restY,omitempty"`
RestAngle float32 `json:"restAngle,omitempty"`
Kinematic bool `json:"kinematic,omitempty"`
Sensor bool `json:"sensor,omitempty"`
// TargetPending reports a pose (TargetX, TargetY, TargetAngle) that SetTargetPose asked the next Step to reach.
TargetPending bool `json:"targetPending,omitempty"`
TargetX float32 `json:"targetX,omitempty"`
TargetY float32 `json:"targetY,omitempty"`
TargetAngle float32 `json:"targetAngle,omitempty"`
// TargetDriven reports that the last Step moved the body to a target with velocity (TargetVX, TargetVY, TargetAngularVel), which the next Step stops unless a new target is set.
TargetDriven bool `json:"targetDriven,omitempty"`
TargetVX float32 `json:"targetVX,omitempty"`
TargetVY float32 `json:"targetVY,omitempty"`
TargetAngularVel float32 `json:"targetAngularVel,omitempty"`
}RigidBodySnapshot captures the complete public and private simulation state of one RigidBody.
type RigidContactPointSnapshot struct {
// Feature names the pair of shape features in contact.
Feature uint32 `json:"feature"`
NormalImpulse float64 `json:"normalImpulse"`
TangentImpulse float64 `json:"tangentImpulse"`
}RigidContactPointSnapshot captures the impulses one contact point ended a step with, which warm-start the next step.
type RigidContactSnapshot struct {
BodyAIndex int `json:"bodyAIndex"`
BodyBIndex int `json:"bodyBIndex"`
Tile bool `json:"tile,omitempty"`
Sub int `json:"sub,omitempty"`
Points []RigidContactPointSnapshot `json:"points,omitempty"`
}RigidContactSnapshot captures one cached contact manifold of a RigidWorld: the pair of bodies, as indices into RigidWorldSnapshot.Bodies, the manifold's index within the pair (the chain segment against a Chain, 0 otherwise) and its points. A contact with the world's Tiles has Tile set, BodyBIndex -1 and the tile's row*cols + col in Sub.
type RigidJointBreakEventSnapshot struct {
Joint *RigidJointSnapshot `json:"joint,omitempty"`
BodyAIndex int `json:"bodyAIndex"`
BodyBIndex int `json:"bodyBIndex"`
DetachedA *RigidBodySnapshot `json:"detachedA,omitempty"`
DetachedB *RigidBodySnapshot `json:"detachedB,omitempty"`
ForceX float32 `json:"forceX"`
ForceY float32 `json:"forceY"`
Torque float32 `json:"torque"`
}RigidJointBreakEventSnapshot captures one JointBreakEvent from the most recent RigidWorld.Step.
type RigidJointSnapshot struct {
Kind string `json:"kind"` // "distance", "spring", "revolute", "prismatic", "weld", "wheel", "mouse"
BodyAIndex int `json:"bodyAIndex"`
BodyBIndex int `json:"bodyBIndex"`
DetachedA *RigidBodySnapshot `json:"detachedA,omitempty"`
DetachedB *RigidBodySnapshot `json:"detachedB,omitempty"`
AnchorAX float32 `json:"anchorAX"`
AnchorAY float32 `json:"anchorAY"`
AnchorBX float32 `json:"anchorBX"`
AnchorBY float32 `json:"anchorBY"`
LocalAxisAX float32 `json:"localAxisAX,omitempty"`
LocalAxisAY float32 `json:"localAxisAY,omitempty"`
TargetX float32 `json:"targetX,omitempty"`
TargetY float32 `json:"targetY,omitempty"`
Length float32 `json:"length,omitempty"`
MinLength float32 `json:"minLength,omitempty"`
MaxLength float32 `json:"maxLength,omitempty"`
MaxOnly bool `json:"maxOnly,omitempty"`
RestLength float32 `json:"restLength,omitempty"`
ReferenceAngle float32 `json:"referenceAngle,omitempty"`
EnableLimit bool `json:"enableLimit,omitempty"`
LowerAngle float32 `json:"lowerAngle,omitempty"`
UpperAngle float32 `json:"upperAngle,omitempty"`
LowerTranslation float32 `json:"lowerTranslation,omitempty"`
UpperTranslation float32 `json:"upperTranslation,omitempty"`
EnableMotor bool `json:"enableMotor,omitempty"`
MotorSpeed float32 `json:"motorSpeed,omitempty"`
MaxMotorTorque float32 `json:"maxMotorTorque,omitempty"`
MaxMotorForce float32 `json:"maxMotorForce,omitempty"`
MaxForce float32 `json:"maxForce,omitempty"`
FrequencyHz float32 `json:"frequencyHz,omitempty"`
DampingRatio float32 `json:"dampingRatio,omitempty"`
Stiffness float32 `json:"stiffness,omitempty"`
Compliance float32 `json:"compliance,omitempty"`
Damping float32 `json:"damping,omitempty"`
BreakForce float32 `json:"breakForce,omitempty"`
BreakTorque float32 `json:"breakTorque,omitempty"`
CollideConnected bool `json:"collideConnected,omitempty"`
StepImpulseX float64 `json:"stepImpulseX,omitempty"`
StepImpulseY float64 `json:"stepImpulseY,omitempty"`
StepAngImpulse float64 `json:"stepAngImpulse,omitempty"`
LastDt float64 `json:"lastDt,omitempty"`
Broken bool `json:"broken,omitempty"`
Initialized bool `json:"initialized,omitempty"`
Active bool `json:"active,omitempty"`
Soft bool `json:"soft,omitempty"`
RotLocked bool `json:"rotLocked,omitempty"`
SpringActive bool `json:"springActive,omitempty"`
Dt float64 `json:"dt,omitempty"`
UX float64 `json:"ux,omitempty"`
UY float64 `json:"uy,omitempty"`
AX float64 `json:"ax,omitempty"`
AY float64 `json:"ay,omitempty"`
PX float64 `json:"px,omitempty"`
PY float64 `json:"py,omitempty"`
RAX float64 `json:"rAx,omitempty"`
RAY float64 `json:"rAy,omitempty"`
RBX float64 `json:"rBx,omitempty"`
RBY float64 `json:"rBy,omitempty"`
S1 float64 `json:"s1,omitempty"`
S2 float64 `json:"s2,omitempty"`
A1 float64 `json:"a1,omitempty"`
A2 float64 `json:"a2,omitempty"`
EffMass float64 `json:"effMass,omitempty"`
PerpMass float64 `json:"perpMass,omitempty"`
AxisMass float64 `json:"axisMass,omitempty"`
SpringMass float64 `json:"springMass,omitempty"`
MotorMass float64 `json:"motorMass,omitempty"`
M11 float64 `json:"m11,omitempty"`
M12 float64 `json:"m12,omitempty"`
M22 float64 `json:"m22,omitempty"`
KA float64 `json:"kA,omitempty"`
KB float64 `json:"kB,omitempty"`
KC float64 `json:"kC,omitempty"`
KD float64 `json:"kD,omitempty"`
KE float64 `json:"kE,omitempty"`
KF float64 `json:"kF,omitempty"`
Gamma float64 `json:"gamma,omitempty"`
GammaAng float64 `json:"gammaAng,omitempty"`
Bias float64 `json:"bias,omitempty"`
BiasX float64 `json:"biasX,omitempty"`
BiasY float64 `json:"biasY,omitempty"`
BiasAng float64 `json:"biasAng,omitempty"`
AccImpulse float64 `json:"accImpulse,omitempty"`
ImpulseX float64 `json:"impulseX,omitempty"`
ImpulseY float64 `json:"impulseY,omitempty"`
AngImpulse float64 `json:"angImpulse,omitempty"`
SpringImpulse float64 `json:"springImpulse,omitempty"`
MotorImpulse float64 `json:"motorImpulse,omitempty"`
LimitImpulse float64 `json:"limitImpulse,omitempty"`
Mode int `json:"mode,omitempty"`
LimitState int `json:"limitState,omitempty"`
TargetLen float64 `json:"targetLen,omitempty"`
}RigidJointSnapshot captures the complete public and private solver state of one RigidWorld Joint.
type RigidSenseSnapshot struct {
SensorIndex int `json:"sensorIndex"`
VisitorIndex int `json:"visitorIndex"`
}RigidSenseSnapshot captures one body overlapping a sensor, both as indices into RigidWorldSnapshot.Bodies.
type RigidTouchSnapshot struct {
BodyAIndex int `json:"bodyAIndex"`
BodyBIndex int `json:"bodyBIndex"`
Tile bool `json:"tile,omitempty"`
Col int `json:"col,omitempty"`
Row int `json:"row,omitempty"`
TileFlags TileFlags `json:"tileFlags,omitempty"`
}RigidTouchSnapshot captures one contact a RigidWorld reported begun and not yet ended: two bodies, as indices into RigidWorldSnapshot.Bodies, or a body and the Tiles, with Tile set, BodyBIndex -1 and the last tile touched.
type RigidWorld struct {
Bodies []*RigidBody
Joints []Joint
Triggers []*Trigger
GravityX float32
GravityY float32
SolverIterations int
// DisableSleep keeps every body awake. Step wakes bodies that were sleeping when it is set.
DisableSleep bool
// SleepLinearThreshold is the speed in pixels per second below which a body counts as resting; zero, a negative value, NaN or an infinity means DefaultSleepLinearThreshold.
SleepLinearThreshold float32
// SleepAngularThreshold is the angular speed in radians per second below which a body counts as resting; zero, a negative value, NaN or an infinity means DefaultSleepAngularThreshold.
SleepAngularThreshold float32
// TimeToSleep is how many seconds every body of an island must rest before the island sleeps; zero, a negative value, NaN or an infinity means DefaultTimeToSleep.
TimeToSleep float32
// OnJointBreak is invoked deterministically for each joint broken during Step, in joint insertion order.
OnJointBreak func(JointBreakEvent)
// OnContact is invoked at the end of Step for each of ContactEvents, in order.
OnContact func(ContactEvent)
// OnSensor is invoked at the end of Step for each of SensorEvents, in order.
OnSensor func(SensorEvent)
// Tiles is an optional tile grid whose TileSolid cells collide with the dynamic bodies from every side and whose TileOneWay cells hold them up from above only. A tile's sides that a neighbouring solid tile covers never push a body, so bodies slide and roll across the seams of a tiled floor or wall. Tiles collide by TileLayer and TileMask like a body, and with TileFriction and TileRestitution.
Tiles TileGrid
// TileLayer and TileMask filter which bodies collide with Tiles, as a body's Layer and Mask do (zero means LayerAll).
TileLayer LayerMask
TileMask LayerMask
// TileFriction is the friction of Tiles, combined with a body's as two bodies' are; zero means DefaultTileFriction and a negative value makes tiles frictionless.
TileFriction float32
// TileRestitution is the restitution of Tiles, combined with a body's as two bodies' are.
TileRestitution float32
// contains filtered or unexported fields
}RigidWorld simulates 2D rigid bodies and joints with deterministic symplectic Euler integration, a sort-and-sweep broadphase, warm-started sequential impulse contact resolution with friction, positional slop correction, island sleeping and continuous collision of fast bodies against static ones.
A dynamic body that moves slower than SleepLinearThreshold and turns slower than SleepAngularThreshold for TimeToSleep seconds is ready to sleep, and the island of bodies connected to it by contacts and joints falls asleep together once every body in it is ready. A sleeping body costs no integration or solving; see RigidBody.Sleeping for what wakes it.
Static, kinematic (RigidBody.Kinematic) and dynamic bodies collide with each other, and dynamic ones with Tiles; sensors (RigidBody.Sensor) only detect overlaps. After each Step, ContactEvents and SensorEvents list the contacts and overlaps that began or ended, and Raycast, RaycastFirst, QueryPoint, QueryOverlap and ShapeCast query the bodies and tiles.
func (w *RigidWorld) AddBody(bodies ...*RigidBody)AddBody appends non-nil rigid bodies to w.Bodies.
func (w *RigidWorld) AddJoint(joints ...Joint)AddJoint appends non-nil joints to w.Joints and wakes any sleeping bodies they connect.
func (w *RigidWorld) AddTrigger(triggers ...*Trigger)AddTrigger appends non-nil triggers to w.Triggers so their Area settings apply to overlapping RigidBodies during Step.
func (w *RigidWorld) AreaEffectAtShape(shape Shape, layer, mask LayerMask) AreaEffectAreaEffectAtShape resolves all active Triggers in w overlapping shape (filtered by layer and mask) using w.GravityX/GravityY as the base gravity.
func (w *RigidWorld) Checksum() uint64Checksum returns a deterministic 64-bit FNV-1a hash of w's complete state, including private body forces/torques and joint solver state.
func (w *RigidWorld) ContactEvents() []ContactEventContactEvents returns the contacts that began or ended in the most recent Step, in deterministic order: the ContactBegin events in the order the step found the contacts (pairs of bodies in RigidWorld.Bodies order, then each body with Tiles), then the ContactEnd events in the order the previous Step listed those contacts, then, in RigidWorld.Bodies order, a ContactBegin for each fast body continuous collision stopped at a surface it was not touching, which carries the speed it struck at. A contact the step did not find carries over while its bodies may still collide and are both asleep or not dynamic, or are still within 0.25 px of each other; it ends once they are farther apart, a body leaves RigidWorld.Bodies or becomes a sensor, or both become static or kinematic. The slice is reused by the next Step.
func (w *RigidWorld) GravityAt(x, y float32) (gx, gy float32)GravityAt returns the effective gravity acceleration at world point (x, y) in w, combining w.GravityX/GravityY with any overlapping active Triggers.
func (w *RigidWorld) JointBreakEvents() []JointBreakEventJointBreakEvents returns the deterministic slice of JointBreakEvents produced by the most recent RigidWorld.Step, in joint insertion order.
func (w *RigidWorld) QueryOverlap(shape Shape, mask QueryMask, layerMask LayerMask) []OverlapHitQueryOverlap returns the bodies and tiles of w matching mask and layerMask that overlap shape, in deterministic order: bodies in RigidWorld.Bodies order, then tiles in row-major order. Each hit's Contact normal points from the hit toward shape.
func (w *RigidWorld) QueryPoint(x, y float32, mask QueryMask, layerMask LayerMask) []*RigidBodyQueryPoint returns the bodies of w matching mask and layerMask whose shape contains (x, y), in RigidWorld.Bodies order. Tiles are not bodies, so QueryTiles and QueryOneWay select nothing here; read a tile with TileFlagsAt.
func (w *RigidWorld) Raycast(from, to core.Point, mask QueryMask, layerMask LayerMask) []RaycastHitRaycast casts the segment from from to to against the bodies and tiles of w matching mask and layerMask and returns every hit sorted by ascending T in [0, 1]. Equal distances keep bodies, in RigidWorld.Bodies order, before tiles, in the order the ray crosses them. A segment with an end that is not finite hits nothing.
func (w *RigidWorld) RaycastFirst(from, to core.Point, mask QueryMask, layerMask LayerMask) (RaycastHit, bool)RaycastFirst returns the nearest hit along the segment from from to to among the bodies and tiles of w matching mask and layerMask, with its point and surface normal. Of hits at the same distance, the body first in RigidWorld.Bodies wins, and a body wins over a tile. A segment with an end that is not finite hits nothing.
func (w *RigidWorld) RemoveBody(b *RigidBody) boolRemoveBody deletes the first occurrence of b from w.Bodies, preserving the order of remaining bodies, and wakes any sleeping bodies that touched or were jointed to b.
func (w *RigidWorld) RemoveJoint(j Joint) boolRemoveJoint deletes the first occurrence of j from w.Joints, preserving the order of remaining joints, and wakes any sleeping bodies it connected.
func (w *RigidWorld) RemoveTrigger(tr *Trigger) boolRemoveTrigger deletes the first occurrence of tr from w.Triggers, preserving the order of remaining triggers.
func (w *RigidWorld) Restore(snap RigidWorldSnapshot) errorRestore replaces w's state from snap. Existing *RigidBody, Joint, and *Trigger pointers are reused in place when possible so caller handles, UserData, and callbacks stay valid across rollback restores.
func (w *RigidWorld) Save() RigidWorldSnapshotSave captures a deep, deterministic, JSON-serializable snapshot of w.
func (w *RigidWorld) SensorEvents() []SensorEventSensorEvents returns the sensor overlaps that began or ended in the most recent Step, tested at the bodies' poses at the end of the step: the ContactBegin events in pair order (by RigidWorld.Bodies index), then the ContactEnd events in the order the previous Step listed those overlaps. The slice is reused by the next Step.
func (w *RigidWorld) ShapeCast(shape Shape, dx, dy float32, layerMask LayerMask) (ShapeCastHit, bool)ShapeCast sweeps shape by (dx, dy) against the bodies that are not sensors and the tiles of w, bodies matching layerMask, and returns the earliest hit. A zero layerMask defaults to LayerAll. Ties break in RigidWorld.Bodies order, and a body wins over a tile.
func (w *RigidWorld) ShapeCastAll(shape Shape, dx, dy float32, layerMask LayerMask) []ShapeCastHitShapeCastAll sweeps shape by (dx, dy) against the bodies that are not sensors and the tiles of w, bodies matching layerMask, and returns all hits sorted by ascending Fraction in [0, 1]. A zero layerMask defaults to LayerAll. Equal fractions keep bodies, in RigidWorld.Bodies order, before tiles, in row-major order.
func (w *RigidWorld) ShapeCastAllWith(shape Shape, dx, dy float32, opts ShapeCastOptions) []ShapeCastHitShapeCastAllWith sweeps shape by (dx, dy) against the bodies and tiles of w matching opts, selected as ShapeCastWith selects them, and returns all hits sorted by ascending Fraction in [0, 1]. Equal fractions keep bodies, in RigidWorld.Bodies order, before tiles, in row-major order.
func (w *RigidWorld) ShapeCastWith(shape Shape, dx, dy float32, opts ShapeCastOptions) (ShapeCastHit, bool)ShapeCastWith sweeps shape by (dx, dy) against the bodies and tiles of w matching opts and returns the earliest hit. opts.QueryMask selects targets as RigidWorld's other queries do: QueryBodies the bodies that are not sensors, QuerySensors the sensors, and QueryTiles and QueryOneWay the tiles, with zero meaning QueryAll, which leaves sensors out. Ties break in RigidWorld.Bodies order, and a body wins over a tile.
func (w *RigidWorld) Step(dt time.Duration)Step advances all bodies and joints in w by dt using symplectic Euler integration, deterministic warm-started sequential impulse solving against other bodies and Tiles, continuous collision for fast bodies and positional slop correction, then puts resting islands to sleep and reports the contacts and sensor overlaps that began or ended (ContactEvents, SensorEvents).
type RigidWorldSnapshot struct {
Version int `json:"version"`
GravityX float32 `json:"gravityX"`
GravityY float32 `json:"gravityY"`
SolverIterations int `json:"solverIterations"`
DisableSleep bool `json:"disableSleep,omitempty"`
SleepLinearThreshold float32 `json:"sleepLinearThreshold,omitempty"`
SleepAngularThreshold float32 `json:"sleepAngularThreshold,omitempty"`
TimeToSleep float32 `json:"timeToSleep,omitempty"`
Bodies []RigidBodySnapshot `json:"bodies,omitempty"`
Joints []RigidJointSnapshot `json:"joints,omitempty"`
JointBreakEvents []RigidJointBreakEventSnapshot `json:"jointBreakEvents,omitempty"`
Triggers []TriggerSnapshot `json:"triggers,omitempty"`
// Contacts is the warm-start cache between bodies of Bodies, and LastDt the length in seconds of the step that filled it.
Contacts []RigidContactSnapshot `json:"contacts,omitempty"`
LastDt float64 `json:"lastDt,omitempty"`
// Grid is the world's Tiles when they are a *Grid, with the settings they collide with. CustomTiles reports Tiles of another TileGrid type, which Save cannot capture: Restore keeps the caller's Tiles then, and clears them when neither is set, as for a world without Tiles or a version 1 snapshot.
Grid *GridSnapshot `json:"grid,omitempty"`
CustomTiles bool `json:"customTiles,omitempty"`
TileLayer LayerMask `json:"tileLayer,omitempty"`
TileMask LayerMask `json:"tileMask,omitempty"`
TileFriction float32 `json:"tileFriction,omitempty"`
TileRestitution float32 `json:"tileRestitution,omitempty"`
// Touching and Sensing are the contacts and sensor overlaps the next Step compares its own with to report ContactEvents and SensorEvents. Entries with a body outside Bodies are not saved, so the end of such a contact is not reported after Restore.
Touching []RigidTouchSnapshot `json:"touching,omitempty"`
Sensing []RigidSenseSnapshot `json:"sensing,omitempty"`
}RigidWorldSnapshot captures the complete deterministic state of a RigidWorld, including all rigid bodies (and pending forces/torques, sleep state and timers), joints and their private constraint state, joint-break events, the warm-start contact cache, area triggers, gravity, and solver and sleep configuration. It marshals cleanly with encoding/json.
type RopeConfig struct {
StartX, StartY float32
EndX, EndY float32
Segments int
TotalMass float32
ParticleRadius float32
Compliance float32
EnableBending bool
BendingCompliance float32
PinStart bool
PinEnd bool
Layer LayerMask
Mask LayerMask
Friction float32
}RopeConfig configures a 2D rope constructed by SoftWorld.AddRope.
type Segment struct {
X1, Y1, X2, Y2 float32
}Segment is a line segment from (X1, Y1) to (X2, Y2) with no thickness, for static ledges and walls. It collides with polygons, boxes, circles and capsules on both sides but never with another Segment or a Chain, as in Box2D. A segment of zero length is empty.
func (s Segment) Bounds() BoxBounds returns the axis-aligned Box spanning s; it has zero width or height when s is vertical or horizontal.
func (s Segment) Empty() boolEmpty reports whether s has zero length.
func (s Segment) Translated(dx, dy float32) SegmentTranslated returns a copy of s shifted by (dx, dy).
type SensorEvent struct {
Kind ContactEventKind
Sensor *RigidBody
Visitor *RigidBody
}SensorEvent reports that a body that is not a sensor began or ended overlapping a sensor in the last Step, or left RigidWorld.Bodies while overlapping it.
type Shape struct {
Kind ShapeKind
Box Box
Circle Circle
Polygon Polygon
Capsule Capsule
Segment Segment
Chain *Chain
}Shape holds one of Box, Circle, Polygon, Capsule, Segment or Chain, selected by Kind, so bodies, triggers and queries handle every shape uniformly. Shapes are comparable with ==; a chain compares by its pointer.
func CapsuleShape(c Capsule) ShapeCapsuleShape returns a Shape wrapping c.
func ChainShape(points []core.Point, loop bool) ShapeChainShape returns a Shape holding a Chain through a copy of points, closed when loop is true.
func CircleShape(c Circle) ShapeCircleShape returns a Shape wrapping c.
func PolygonShape(p Polygon) ShapePolygonShape returns a Shape wrapping p.
func SegmentShape(s Segment) ShapeSegmentShape returns a Shape wrapping s.
func (s Shape) Area() float32Area returns the area of s. Segments and chains have none.
func (s Shape) Bounds() BoxBounds returns the axis-aligned Box enclosing s, or a zero Box when s is empty. The bounds of a horizontal or vertical segment or chain have zero height or width.
func (s Shape) Centroid() (x, y float32)Centroid returns the center of mass of s, taken as uniformly dense: the area's centroid for boxes, circles, polygons and capsules, and the midpoint of the line, weighted by length, for segments and chains. It returns (0, 0) when s is empty.
func (s Shape) Contains(x, y float32) boolContains reports whether (x, y) lies inside or on the boundary of s. Segments and chains have no inside and contain no point.
func (s Shape) Empty() boolEmpty reports whether s holds no usable geometry: a Box or Circle without positive area, a Polygon or Capsule that is empty, a Segment of zero length or a Chain without a segment. Segments and chains have no area but are not empty.
func (s Shape) MomentOfInertia(mass float32) float32MomentOfInertia returns the rotational inertia of s about its Centroid for a body of the given mass spread evenly over its area, as RigidBody uses. Segments, chains and empty shapes return 0.
func (s Shape) Translated(dx, dy float32) ShapeTranslated returns a copy of s shifted by (dx, dy). A chain is copied into a new Chain.
type ShapeCastHit struct {
// Fraction is the normalized time of impact in [0, 1] along the displacement.
Fraction float32
// Point is the world-space contact point on the struck surface at the time of impact.
Point core.Point
// NormalX and NormalY form the unit surface normal at Point, pointing from the struck
// target toward the cast shape.
NormalX, NormalY float32
// Body is non-nil when the hit is a body from World.Bodies.
Body *Body
// RigidBody is non-nil when the hit is a body from RigidWorld.Bodies.
RigidBody *RigidBody
// Tile is true when the hit is a tile from World.Tiles at (Col, Row).
Tile bool
Col, Row int
TileFlags TileFlags
}ShapeCastHit describes one contact encountered when sweeping a Shape along a displacement vector.
func ShapeCastShape(moving Shape, dx, dy float32, target Shape) (ShapeCastHit, bool)ShapeCastShape sweeps moving by (dx, dy) against stationary target and returns the exact time of impact, contact point, and outward unit normal pointing from target toward moving. Initial overlaps report Fraction == 0 with the overlap contact from TestShapes.
type ShapeCastOptions struct {
// QueryMask selects which target kinds (bodies, solid tiles, one-way tiles, and in a RigidWorld sensors) to inspect. Zero defaults to QueryAll, which leaves sensors out.
QueryMask QueryMask
// LayerMask filters bodies by their Layer bitmask. Zero defaults to LayerAll.
LayerMask LayerMask
// IgnoreBody optionally excludes one World body from the cast.
IgnoreBody *Body
// IgnoreRigidBody optionally excludes one RigidWorld body from the cast.
IgnoreRigidBody *RigidBody
}ShapeCastOptions configures filtering for World.ShapeCastWith, World.ShapeCastAllWith, RigidWorld.ShapeCastWith, and RigidWorld.ShapeCastAllWith.
type ShapeKind uint8ShapeKind identifies which geometry a Shape holds.
const (
// ShapeNone is the empty zero shape.
ShapeNone ShapeKind = iota
// ShapeBox holds an axis-aligned Box.
ShapeBox
// ShapeCircle holds a Circle.
ShapeCircle
// ShapePolygon holds a convex, optionally rounded Polygon.
ShapePolygon
// ShapeCapsule holds a Capsule.
ShapeCapsule
// ShapeSegment holds a Segment.
ShapeSegment
// ShapeChain holds a Chain.
ShapeChain
)type ShapeMatchConstraint struct {
Particles []int
RestOffsets [][2]float32
Stiffness float32
}ShapeMatchConstraint pulls a group of particles toward the closest rigid-body transformation (translation + 2D rotation) of their rest offsets.
type SlideCollision struct {
// Body is non-nil when the collision was with a Body in World.Bodies.
Body *Body
// RigidBody is non-nil when the collision was with a static RigidBody collider.
RigidBody *RigidBody
// Tile is true when the collision was with a tile in World.Tiles at (Col, Row).
Tile bool
Col, Row int
TileFlags TileFlags
// NormalX and NormalY form the unit surface normal pointing from the hit collider toward the moving body.
NormalX, NormalY float32
// Position is the world-space contact point on the colliding surface.
Position core.Point
// Remainder is the remaining displacement vector at the moment of impact before sliding.
Remainder core.Point
}SlideCollision describes one contact encountered during World.MoveAndSlide or World.MoveAndSlideWith.
type SlideResult struct {
// Collisions lists each contact encountered during the slide iterations, in order of impact.
Collisions []SlideCollision
// Travel is the net displacement actually moved by the body during the step.
Travel core.Point
// OnFloor reports whether a floor surface was contacted (normal within FloorMaxAngle of Up).
OnFloor bool
// OnWall reports whether a wall surface was contacted.
OnWall bool
// OnCeiling reports whether a ceiling surface was contacted (normal within FloorMaxAngle of -Up).
OnCeiling bool
// OnLeftWall reports whether a wall contact had its normal pointing toward the right side of Up.
OnLeftWall bool
// OnRightWall reports whether a wall contact had its normal pointing toward the left side of Up.
OnRightWall bool
// FloorNormal is the unit normal of the last floor contact, or zero when OnFloor is false.
FloorNormal core.Point
// WallNormal is the unit normal of the last wall contact, or zero when OnWall is false.
WallNormal core.Point
// CeilingNormal is the unit normal of the last ceiling contact, or zero when OnCeiling is false.
CeilingNormal core.Point
}SlideResult summarizes the contacts, displacement and surface state from one World.MoveAndSlide call.
type Slope struct {
A, B core.Point
}Slope is a line segment representing a ramp or slanted surface for CharacterBody movement. The walkable side is the upward-facing normal (NormalY <= 0 in screen coordinates).
func (s Slope) Angle() float32Angle returns the slope inclination from horizontal in radians, in [0, math.Pi/2].
func (s Slope) Normal() core.PointNormal returns the upward-facing unit surface normal of s (NormalY <= 0).
type SoftBodyConfig struct {
CenterX, CenterY float32
RadiusX, RadiusY float32
Segments int
TotalMass float32
ParticleRadius float32
EdgeCompliance float32
EnableBending bool
BendingCompliance float32
AreaCompliance float32
Pressure float32
UseShapeMatching bool
ShapeMatchStiffness float32
Layer LayerMask
Mask LayerMask
Friction float32
Restitution float32
}SoftBodyConfig configures a 2D pressurized and/or shape-matched soft body constructed by SoftWorld.AddSoftBody.
type SoftWorld struct {
Particles []Particle
Distances []DistanceConstraint
Bendings []BendingConstraint
Areas []AreaConstraint
ShapeMatches []ShapeMatchConstraint
Attachments []RigidAttachment
// World provides optional static/kinematic bodies and a TileGrid to collide against.
World *World
// RigidWorld provides optional 2D rigid bodies to collide against and couple with.
RigidWorld *RigidWorld
// Tiles provides an optional standalone TileGrid (collided in addition to World.Tiles when distinct).
Tiles TileGrid
// TileLayer and TileMask filter particle collisions against tiles (zero defaults to LayerAll).
TileLayer LayerMask
TileMask LayerMask
GravityX float32
GravityY float32
Damping float32
Substeps int
Iterations int
// contains filtered or unexported fields
}SoftWorld simulates 2D XPBD particles, constraints (distance, bending, area/pressure, shape matching), two-way rigid-body attachments, and collisions against World bodies, RigidWorld bodies, and TileGrid tiles in deterministic order.
func NewSoftWorld() *SoftWorldNewSoftWorld returns a SoftWorld configured with sensible defaults (8 substeps, 6 solver iterations, and mild linear damping).
func (sw *SoftWorld) AddArea(particles []int, pressure, compliance float32) intAddArea adds a closed-polygon area/pressure constraint over particles. RestArea is computed from the current particle positions, and pressure <= 0 defaults to 1.0.
func (sw *SoftWorld) AddBending(a, b, c int, compliance float32) intAddBending adds a 3-particle angular bending constraint centered at hinge b, recording the current signed angle between (a - b) and (c - b) as RestAngle.
func (sw *SoftWorld) AddDistance(a, b int, restLength, compliance float32) intAddDistance adds a bilateral distance constraint between particles a and b. If restLength < 0, the current Euclidean distance between a and b is used.
func (sw *SoftWorld) AddParticle(p Particle) intAddParticle appends p to sw.Particles, initializes its previous position to (p.X, p.Y), and returns its index.
func (sw *SoftWorld) AddRope(cfg RopeConfig) []intAddRope constructs a chain of Segments+1 particles from (StartX, StartY) to (EndX, EndY) connected by distance constraints (plus unilateral tethers when Compliance == 0 so heavy attached loads cannot over-stretch the chain, and optional bending constraints).
func (sw *SoftWorld) AddShapeMatch(particles []int, stiffness float32) intAddShapeMatch adds a 2D rigid shape-matching constraint over particles, capturing their current positions relative to their weighted center of mass as rest offsets.
func (sw *SoftWorld) AddSoftBody(cfg SoftBodyConfig) []intAddSoftBody builds a closed 2D soft-body loop around (CenterX, CenterY) with perimeter distance constraints, an AreaConstraint (pressure), and optional ShapeMatchConstraint / bending.
func (sw *SoftWorld) AddTether(a, b int, maxLength, compliance float32) intAddTether adds a unilateral maximum-distance constraint between particles a and b that activates only when their separation exceeds maxLength.
func (sw *SoftWorld) AttachRigidBody(particleIdx int, body *RigidBody, localAnchor core.Point, compliance float32) intAttachRigidBody couples particleIdx to body at localAnchor with two-way reaction impulses. Set compliance to 0 for a rigid pin attachment or > 0 for an elastic attachment.
func (sw *SoftWorld) PinParticle(idx int)PinParticle marks particle idx as pinned (immovable).
func (sw *SoftWorld) PolygonArea(particles []int) float32PolygonArea returns the signed shoelace area of the closed polygon formed by particles.
func (sw *SoftWorld) RopeLength(particles []int) float32RopeLength returns the total Euclidean polyline length along the ordered particle indices.
func (sw *SoftWorld) Step(dt time.Duration)Step advances the 2D XPBD particle and constraint simulation by dt deterministically. Call this on the fixed game loop after stepping RigidWorld so two-way rigid attachments stay synchronized without over-stretching.
func (sw *SoftWorld) UnpinParticle(idx int)UnpinParticle clears particle idx's Pinned flag.
type SpringJoint struct {
A, B *RigidBody
AnchorA core.Point
AnchorB core.Point
RestLength float32
Stiffness float32
Damping float32
BreakForce float32 // max reaction force before breaking (<= 0 disables)
BreakTorque float32 // max reaction torque before breaking (<= 0 disables)
CollideConnected bool
// contains filtered or unexported fields
}SpringJoint connects local anchor points on bodies A and B with a damped Hooke's law spring.
func NewSpringJoint(a, b *RigidBody, anchorA, anchorB core.Point, restLength, stiffness, damping float32) *SpringJointNewSpringJoint creates a SpringJoint between local anchors on a and b. If restLength <= 0 and both bodies are non-nil, RestLength is initialized to the current anchor distance.
func (r *SpringJoint) Broken() boolBroken reports whether the joint has exceeded its break threshold and been removed.
func (r *SpringJoint) ReactionForce() (fx, fy float32)ReactionForce returns the world-space constraint force (fx, fy) applied to body B (or the attached body for MouseJoint) during the most recent RigidWorld.Step.
func (r *SpringJoint) ReactionTorque() float32ReactionTorque returns the scalar constraint torque (clockwise positive in screen space) applied to body B during the most recent RigidWorld.Step.
type TileContact struct {
Col, Row int
Flags TileFlags
NormalX, NormalY float32
}TileContact records one tile hit during MoveAndSlide. (NormalX, NormalY) points away from the tile surface into the body.
type TileFlags uint32TileFlags marks how a tile cell participates in collision resolution and queries.
const (
// TileSolid blocks movement from all four directions.
TileSolid TileFlags = 1 << 0
// TileOneWay blocks downward movement only when the body starts at or above the tile's top edge, unless Body.OneWayDrop is set.
TileOneWay TileFlags = 1 << 1
)type TileGrid interface {
// TileSize returns the width and height of one tile in world coordinates.
TileSize() (width, height float32)
// GridSize returns the number of columns and rows in the grid.
GridSize() (cols, rows int)
// TileFlagsAt returns the collision flags of the tile at (col, row), or 0 when out of bounds or empty.
TileFlagsAt(col, row int) TileFlags
}TileGrid exposes a regular grid of collision tiles to physics resolution and queries without depending on a specific tilemap type.
type TileGridOrigin interface {
GridOrigin() (x, y float32)
}TileGridOrigin is an optional interface a TileGrid may implement to place cell (0, 0) at a non-zero world-space origin (x, y) instead of (0, 0).
When implemented, cell (col, row) occupies [x + col*tileW, x + (col+1)*tileW) × [y + row*tileH, y + (row+1)*tileH), and GridSize still gives the valid cell index span [0, cols) × [0, rows).
type Trigger struct {
ID int
Tag string
Shape Shape
Layer LayerMask
Mask LayerMask
OnEnter func(*Body)
OnStay func(*Body)
OnExit func(*Body)
Area AreaSettings
UserData any
}Trigger is a non-solid sensor region that reports bodies entering, staying inside, and exiting its Shape across World.StepTriggers calls.
Layer and Mask follow the same rules as Body: zero values default to LayerAll, and a body interacts with a trigger when both masks accept the other's layer. On the first step a matching body overlaps Shape, OnEnter is called once. On each subsequent step it continues overlapping, OnStay is called. On the first step it no longer overlaps (or has been removed from World.Bodies), OnExit is called once.
type TriggerSnapshot struct {
ID int `json:"id"`
Tag string `json:"tag,omitempty"`
Shape Shape `json:"shape"`
Layer LayerMask `json:"layer"`
Mask LayerMask `json:"mask"`
Area AreaSettings `json:"area"`
}TriggerSnapshot is a JSON-serializable snapshot of one physics.Trigger (excluding callbacks and UserData).
type WeldJoint struct {
A, B *RigidBody
AnchorA core.Point
AnchorB core.Point
ReferenceAngle float32 // target relative angle B.Angle - A.Angle
FrequencyHz float32 // optional spring natural frequency in Hz (> 0 enables soft spring mode)
DampingRatio float32 // damping ratio for FrequencyHz (0 = undamped, 1 = critically damped)
Stiffness float32 // optional direct spring stiffness (used when FrequencyHz <= 0)
Damping float32 // optional direct damping (used when FrequencyHz <= 0)
BreakForce float32 // max reaction force before breaking (<= 0 disables)
BreakTorque float32 // max reaction torque before breaking (<= 0 disables)
CollideConnected bool
// contains filtered or unexported fields
}WeldJoint locks two bodies' relative position and angle at a shared anchor point. When FrequencyHz > 0 (with DampingRatio) or Stiffness > 0 (with Damping), it behaves as a soft damped spring holding the relative pose; otherwise it acts as a rigid weld.
func NewWeldJoint(a, b *RigidBody, worldAnchor core.Point) *WeldJointNewWeldJoint creates a WeldJoint welding a and b together at worldAnchor with their current relative orientation.
func (r *WeldJoint) Broken() boolBroken reports whether the joint has exceeded its break threshold and been removed.
func (r *WeldJoint) ReactionForce() (fx, fy float32)ReactionForce returns the world-space constraint force (fx, fy) applied to body B (or the attached body for MouseJoint) during the most recent RigidWorld.Step.
func (r *WeldJoint) ReactionTorque() float32ReactionTorque returns the scalar constraint torque (clockwise positive in screen space) applied to body B during the most recent RigidWorld.Step.
type WheelJoint struct {
A, B *RigidBody
AnchorA core.Point // suspension mount in A's local space
AnchorB core.Point // wheel hub in B's local space
LocalAxisA core.Point // unit suspension axis in A's local space (defaults to {X: 0, Y: 1})
FrequencyHz float32 // optional suspension natural frequency in Hz (> 0 computes spring from effective mass)
DampingRatio float32 // damping ratio for FrequencyHz (e.g. 0.7)
Stiffness float32 // direct linear spring stiffness along suspension axis (used when FrequencyHz <= 0)
Damping float32 // direct linear damping along suspension axis (used when FrequencyHz <= 0)
EnableLimit bool // enables suspension travel limits along LocalAxisA
LowerTranslation float32
UpperTranslation float32
EnableMotor bool
MotorSpeed float32 // target wheel angular velocity relative to chassis (rad/s)
MaxMotorTorque float32 // maximum drive motor torque
BreakForce float32 // max reaction force before breaking (<= 0 disables)
BreakTorque float32 // max reaction torque before breaking (<= 0 disables)
CollideConnected bool
// contains filtered or unexported fields
}WheelJoint connects a chassis (A) and a wheel (B) with a 1-DOF suspension axis (spring + damping + optional translation limits) and a rotational drive motor.
func NewWheelJoint(a, b *RigidBody, worldAnchor, worldAxis core.Point) *WheelJointNewWheelJoint creates a WheelJoint attaching wheel b to chassis a at worldAnchor with suspension travel along worldAxis. If worldAxis is zero, it defaults to {X: 0, Y: 1} (vertical suspension in screen space).
func (r *WheelJoint) Broken() boolBroken reports whether the joint has exceeded its break threshold and been removed.
func (j *WheelJoint) JointSpeed() float32JointSpeed returns the wheel's angular speed relative to the chassis (B.AngularVel - A.AngularVel).
func (j *WheelJoint) JointTranslation() float32JointTranslation returns the current signed wheel displacement along the suspension axis.
func (r *WheelJoint) ReactionForce() (fx, fy float32)ReactionForce returns the world-space constraint force (fx, fy) applied to body B (or the attached body for MouseJoint) during the most recent RigidWorld.Step.
func (r *WheelJoint) ReactionTorque() float32ReactionTorque returns the scalar constraint torque (clockwise positive in screen space) applied to body B during the most recent RigidWorld.Step.
type World struct {
Bodies []*Body
Triggers []*Trigger
Tiles TileGrid
// RigidWorld is an optional RigidWorld whose static RigidBody colliders participate in World.MoveAndSlide.
RigidWorld *RigidWorld
// TileLayer and TileMask optionally filter tile collisions during World.MoveAndSlide (zero defaults to LayerAll).
TileLayer LayerMask
TileMask LayerMask
GravityX float32
GravityY float32
// contains filtered or unexported fields
}World holds bodies, triggers, an optional TileGrid and an optional RigidWorld for spatial queries and MoveAndSlide.
func (w *World) Add(bodies ...*Body)Add appends non-nil bodies to w.Bodies.
func (w *World) AddTrigger(triggers ...*Trigger)AddTrigger appends non-nil triggers to w.Triggers.
func (w *World) AreaEffectAtShape(shape Shape, layer, mask LayerMask) AreaEffectAreaEffectAtShape resolves all active Triggers in w overlapping shape (filtered by layer and mask) using w.GravityX/GravityY as the base gravity.
func (w *World) Checksum() uint64Checksum returns a deterministic 64-bit FNV-1a hash of w's complete state, including private trigger overlap tracking.
func (w *World) GravityAt(x, y float32) (gx, gy float32)GravityAt returns the effective gravity acceleration at world point (x, y) in w, combining w.GravityX/GravityY with any overlapping active Triggers.
func (w *World) MoveAndSlide(body *Body, dt time.Duration) SlideResultMoveAndSlide sweeps body's shape by (body.VX*dt, body.VY*dt) against static and kinematic bodies in w.Bodies, solid and one-way tiles in w.Tiles, and static RigidBody colliders in w.RigidWorld, filtered by Layer and Mask. It slides along each contact normal for up to DefaultMaxSlides iterations, updates body's position, velocity and contact flags (Grounded, OnCeiling, OnLeftWall, OnRightWall), and returns the collisions and surface state.
func (w *World) MoveAndSlideWith(body *Body, dt time.Duration, opts MoveOptions) SlideResultMoveAndSlideWith is like MoveAndSlide with configurable motion mode, up direction, floor angle, slide iteration limit, query mask, extra static rigid bodies and exclusions.
func (w *World) QueryOverlap(shape Shape) []OverlapHitQueryOverlap returns all bodies and tiles overlapping shape in deterministic order: matching bodies in World.Bodies order followed by matching tiles in row-major order.
func (w *World) QueryOverlapLayer(shape Shape, mask QueryMask, layerMask LayerMask) []OverlapHitQueryOverlapLayer returns all bodies and tiles matching mask and layerMask that overlap shape in deterministic order. A zero layerMask defaults to LayerAll; bodies match when their effective Layer shares at least one bit with layerMask.
func (w *World) QueryOverlapMask(shape Shape, mask QueryMask) []OverlapHitQueryOverlapMask returns all bodies and tiles matching mask that overlap shape in deterministic order.
func (w *World) QueryPoint(x, y float32) []*BodyQueryPoint returns all bodies in World.Bodies whose shape contains (x, y), in World.Bodies order.
func (w *World) QueryPointLayer(x, y float32, layerMask LayerMask) []*BodyQueryPointLayer returns all bodies in World.Bodies matching layerMask whose shape contains (x, y), in World.Bodies order.
func (w *World) Raycast(from, to core.Point, mask QueryMask) []RaycastHitRaycast casts a segment from from to to against targets selected by mask and returns every hit sorted by ascending distance T in [0, 1]. Equal distances keep bodies (in World.Bodies order) before tiles (in traversal order).
func (w *World) RaycastFirst(from, to core.Point, mask QueryMask) (RaycastHit, bool)RaycastFirst returns the closest hit along the segment from from to to matching mask.
func (w *World) RaycastFirstLayer(from, to core.Point, mask QueryMask, layerMask LayerMask) (RaycastHit, bool)RaycastFirstLayer returns the closest hit along the segment from from to to matching mask and layerMask.
func (w *World) RaycastLayer(from, to core.Point, mask QueryMask, layerMask LayerMask) []RaycastHitRaycastLayer casts a segment from from to to against targets selected by mask and layerMask and returns every hit sorted by ascending distance T in [0, 1].
func (w *World) Remove(b *Body) boolRemove deletes the first occurrence of b from w.Bodies, preserving the order of remaining bodies.
func (w *World) RemoveTrigger(tr *Trigger) boolRemoveTrigger deletes the first occurrence of tr from w.Triggers, preserving the order of remaining triggers, and clears its tracked overlap state.
func (w *World) Restore(snap WorldSnapshot) errorRestore replaces w's state from snap. Existing *Body and *Trigger pointers are reused in place (matching by non-zero ID first, then by slot index) so caller references, UserData, and Trigger callbacks remain intact.
func (w *World) Save() WorldSnapshotSave captures a deep, deterministic, JSON-serializable snapshot of w.
func (w *World) ShapeCast(shape Shape, dx, dy float32, mask QueryMask) (ShapeCastHit, bool)ShapeCast sweeps shape by (dx, dy) against targets in w selected by mask and returns the earliest hit. Equal fractions break ties deterministically: bodies in World.Bodies order before tiles in row-major (Row, Col) order.
func (w *World) ShapeCastAll(shape Shape, dx, dy float32, mask QueryMask) []ShapeCastHitShapeCastAll sweeps shape by (dx, dy) against targets in w selected by mask and returns every hit sorted by ascending Fraction in [0, 1]. Equal fractions keep bodies (in World.Bodies order) before tiles (in row-major Row, Col order).
func (w *World) ShapeCastAllLayer(shape Shape, dx, dy float32, mask QueryMask, layerMask LayerMask) []ShapeCastHitShapeCastAllLayer sweeps shape by (dx, dy) against targets in w matching mask and layerMask and returns every hit sorted by ascending Fraction in [0, 1]. A zero layerMask defaults to LayerAll.
func (w *World) ShapeCastAllWith(shape Shape, dx, dy float32, opts ShapeCastOptions) []ShapeCastHitShapeCastAllWith sweeps shape by (dx, dy) against targets in w matching opts and returns every hit sorted by ascending Fraction in [0, 1]. Equal fractions keep bodies (in World.Bodies order) before tiles (in row-major Row, Col order).
func (w *World) ShapeCastLayer(shape Shape, dx, dy float32, mask QueryMask, layerMask LayerMask) (ShapeCastHit, bool)ShapeCastLayer sweeps shape by (dx, dy) against targets in w matching mask and layerMask and returns the earliest hit. A zero layerMask defaults to LayerAll.
func (w *World) ShapeCastWith(shape Shape, dx, dy float32, opts ShapeCastOptions) (ShapeCastHit, bool)ShapeCastWith sweeps shape by (dx, dy) against targets in w matching opts and returns the earliest hit with deterministic tie-breaking.
func (w *World) StepTriggers()StepTriggers evaluates every trigger in w.Triggers against w.Bodies in deterministic order and dispatches OnEnter, OnStay, and OnExit callbacks for changed or continuing overlaps. Removing a body from w.Bodies causes OnExit to fire on the next StepTriggers call.
type WorldSnapshot struct {
Version int `json:"version"`
GravityX float32 `json:"gravityX"`
GravityY float32 `json:"gravityY"`
Bodies []BodySnapshot `json:"bodies,omitempty"`
Triggers []TriggerSnapshot `json:"triggers,omitempty"`
TriggerActive []WorldTriggerActiveSnapshot `json:"triggerActive,omitempty"`
Grid *GridSnapshot `json:"grid,omitempty"`
}WorldSnapshot captures the complete deterministic state of a physics.World, including all bodies, triggers, private trigger enter/stay/exit tracking, gravity, and any *Grid tilemap. It marshals cleanly with encoding/json.
type WorldTriggerActiveSnapshot struct {
TriggerIndex int `json:"triggerIndex"`
BodyIndices []int `json:"bodyIndices,omitempty"`
Detached []BodySnapshot `json:"detached,omitempty"`
}WorldTriggerActiveSnapshot records the active overlapping bodies tracked for one trigger in World. Non-negative BodyIndices index into WorldSnapshot.Bodies; negative values (-1 - k) index Detached[k].