b2

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 15 Imported by: 0

README

Box2D V3 Physics Engine for Go

CI Go Reference Latest tag License Go version

dbox2d is an idiomatic, pure Go port of the Box2D v3.2.0 physics engine.

It offers two scalar modes from the same solver: float32 is the default, and -tags dbox2d_fixed selects Q32.32 fixed-point arithmetic. Both modes are deterministic; the difference in their reproducibility contracts is described in Scalar modes and determinism.

Try the browser samples

Open the live demo · fixed mode

The browser demo requires WebGPU and run on a single thread due to limitations in Go's WebAssembly implementation. To use multithreading, try the native version. see the samples.

Highlights

  • Box2D v3.2.0's public API, expressed in Go style.
  • Deterministic results and a checksum over the complete world state.
  • Bodies, shapes, sensors, chains, contacts, seven joint types, queries, casts, continuous collision, events, and debug drawing.
  • Native and WebAssembly samples rendered with WebGPU.
  • Optional SIMD contact solving with scalar-parity checks.

Install

Requires Go 1.26.8 or newer.

go get github.com/dhannyell/dbox2d

The package is named b2, so the import needs no alias and a call reads like the reference: b2Body_GetPosition(bodyId) becomes bodyId.GetPosition(), and b2MakeBox(1, 1) becomes b2.MakeBox(...). Constructors, defaults, and geometry helpers remain package functions.

First world

package main

import "github.com/dhannyell/dbox2d"

func main() {
	def := b2.DefaultWorldDef()
	def.Gravity = b2.V2(0, -10)
	world := b2.CreateWorld(&def)
	defer b2.DestroyWorld(world)

	world.Step(b2.QFromRatio(1, 60), 4)
}

Every scalar of the API is a Q, the scalar of the selected mode. F converts an integer or a float, V2 builds a vector, and Degrees gives an angle in the turns the API uses; see Scalar modes and determinism for the long forms and the rounding contract.

Run the samples

The samples module includes the Box2D scenes in native and WebAssembly hosts. Native runs need cgo, a C toolchain, and a Vulkan, Metal, or D3D12 driver. The browser host needs WebGPU.

SIMD
cd samples
GOTOOLCHAIN=go1.27.0 GOEXPERIMENT=simd go run -tags dbox2d_simd ./cmd/native

To build the browser host:

cd samples
GOTOOLCHAIN=go1.27.0 GOEXPERIMENT=simd CGO_ENABLED=0 GOOS=js GOARCH=wasm go build -tags dbox2d_simd -o web/app.wasm ./cmd/web
go run ./cmd/serve
Scalar
cd samples
go run ./cmd/native
cd samples
CGO_ENABLED=0 GOOS=js GOARCH=wasm go build -o web/app.wasm ./cmd/web
go run ./cmd/serve

Then open http://localhost:8080. The full list of controls, platform requirements, and instructions for adding a scene are in samples/README.md.

Scalar modes and determinism

Both modes are deterministic, but they are different numeric systems and can follow different trajectories. ScalarMode reports the active mode.

Build Arithmetic Best for
default float32 General use, multiplayer, rollback, and authoritative simulation with a controlled build matrix
-tags dbox2d_fixed Signed Q32.32 fixed point A stronger cross-platform reproducibility contract

-tags dbox2d_double is the large-world mode of Box2D v3.2.0 (BOX2D_DOUBLE_PRECISION). Body positions and world transforms are float64 (Pos, WorldTransform) while the solver stays float32, so a world far from the origin keeps its precision. It builds on the float mode, matches the upstream double traces bit for bit, and cannot be combined with dbox2d_fixed. IsDoublePrecision reports it. Its checksum is not comparable to the default one.

Float is deterministic for a specific supported build and target. A silently introduced fused multiply-add (FMA), compiler change, or other floating-point variation can make two peers take different paths while each continues to produce internally valid results. For float rollback, lockstep, or authoritative simulation, pin the toolchain and flags, validate every supported target, keep update order and random state stable, and compare checksums regularly.

Fixed point provides a stronger and easier-to-audit contract across toolchains and architectures, but does not make the complete application deterministic by itself.

Use these constructors to create simulation values:

b2.F(3)          // an int, exact
b2.F(0.35)       // a float, rounded once to the mode
b2.F(q)          // a Q, unchanged
b2.V2(1, -2)     // a vector; both arguments share one type
b2.Degrees(90)   // a quarter turn
b2.QZero()
b2.QOne()
b2.QHalf()
b2.QFromInt(3)
b2.QFromRatio(1, 8)
b2.QFromFloat64(0.35)
b2.QMustParse("0.35")

F and V2 are generic over int, float32, float64, and Q, so an untyped literal needs no conversion; F(3) is QFromInt(3) and F(0.35) is QFromFloat64(0.35). Mixed arguments need one type: V2(1, 0.5) does not compile, V2(1.0, 0.5) does.

QFromFloat64 rounds to the nearest scalar of the mode, the same way on every architecture, and QToFloat64 converts back. A constant converts to the same bits everywhere. A float64 computed at run time is only as deterministic as its computation: Go fuses a multiply and an add into one rounding on arm64, and on amd64 with GOAMD64=v3, so the same expression can give different bits in different builds. QMustParse rounds a decimal once, while a literal passed to QFromFloat64 rounds to float64 first, so a long literal can differ in the last bit.

Angles in the API are turns in both modes: one quarter turn is QFromRatio(1, 4), and an angular velocity is in turns per second. Inside, the body state keeps radians per second, and a joint keeps its angles in radians in float mode, as Box2D does, and in turns in fixed mode (D-004).

Build and test fixed mode with:

go build -tags dbox2d_fixed ./...
go test -tags dbox2d_fixed ./...
cd samples
go test -tags dbox2d_fixed ./...
go run -tags dbox2d_fixed ./cmd/native

The published sample page serves the float build by default. Add ?mode=fixed to load the fixed build instead.

The port is checked against traces of the reference compiled without SIMD and without FMA; the collision functions match the reference bit for bit in float mode except at three documented sites, and the fixed mode stays within measured budgets. See DIVERGENCES.md D-018.

Reproducing Box2D bit for bit

Box2D v3.2 sorts the new broadphase pairs by shape pair key, and the port follows that order, so the world does not depend on the tree topology and no build tag is needed. Up to v1.0.0 the reference followed the walk of the tree and the dbox2d_upstream_pairs tag reproduced it (DIVERGENCES.md D-013). The frozen scene traces are being regenerated against v3.2.

SIMD

Use dbox2d_simd to enable the SIMD contact solver. It is optional and produces the same result bits as the scalar solver.

Target Native path
amd64 AVX2, with scalar fallback when AVX2 is unavailable
arm64 NEON
wasm and other targets generic path

Native vector paths require Go 1.27.0 and GOEXPERIMENT=simd:

GOTOOLCHAIN=go1.27.0 GOEXPERIMENT=simd go build -tags dbox2d_simd ./...
GOTOOLCHAIN=go1.27.0 GOEXPERIMENT=simd go build -tags dbox2d_simd,dbox2d_fixed ./...

The generic path is useful for compatibility and conformance; benchmark it before enabling it for production.

Workers, callbacks, and drawing

WorldDef.WorkerCount controls native workers without changing result bits. WebAssembly always steps on one worker. Go callbacks use closures rather than the C API's void* context.

DefaultDebugDraw provides no-op callbacks. Implement the operations your host needs and call worldId.Draw(&draw); the library walks the world and the host decides how to render it.

Recording, snapshots and replay

WorldId.StartRecording writes every API call and a state hash per step in the Box2D v3.2.0 recording format. GetSnapshot, RestoreFromSnapshot and CreateWorldFromSnapshot save and roll back a world, and CreateReplay plays a recording with seek, frame queries and divergence detection. Float and double builds read and write the upstream bytes (checked against files made by tools/recordgolden); the fixed build uses an 8 byte scalar and its own layout hash, see D-022. Recording costs one nil check per call when off.

Compatibility with Box2D

This is a port, not a new physics design. It preserves the upstream file structure, names without the b2 prefix, and order of operations so code can be compared with its Box2D counterpart.

It does not promise the same output bits as Box2D. Both scalar modes share one source, and the fixed-point mode forbids some float-oriented operations, so those operations change in both modes. Each intentional change is documented with its rationale and test coverage in DIVERGENCES.md.

dbox2d is not affiliated with, endorsed by, or supported by the Box2D project. Please report dbox2d issues here rather than upstream.

Performance

Performance depends on the workload and target. Native SIMD improves contact-heavy scenes on supported CPUs, while the generic path may be slower than scalar. Measure both scalar modes and the target that matters to you:

go test -run "^$" -bench . -benchmem
go test -tags dbox2d_fixed -run "^$" -bench . -benchmem

The repository's benchmark results are historical measurements, not a promise for another machine or scene. The saturation counter used by some tests is diagnostic only and never changes simulation results.

Against Box2D

The seven benchmark scenes of the reference run on both sides under one protocol: the same step counts, the same AVX2 lane path at width 8, fused multiply-add disabled in the C build because the port never emits it, and validation off in both. Solver milliseconds are the sum of the per-step minima, and each figure is a geometric mean over the seven scenes.

Workers Port over reference Reference speedup Port speedup Reference efficiency Port efficiency
1 1.85x 1.00x 1.00x 100% 100%
2 1.68x 1.72x 1.88x 86% 94%
4 1.70x 2.87x 3.12x 72% 78%
8 1.88x 4.13x 4.05x 52% 51%

The per-scene ratios at one worker run 1.52x to 2.12x; at eight they run 1.74x to 2.04x. The contact stages are close to the reference: in large_pyramid at one worker the relax stage takes 187 ms against 167 ms. Most of the remaining gap is contact preparation, impulse storage, the broad phase and the narrow phase.

Box2D v3.2 is itself about twice as fast as v3.1.1 on these scenes, so the ratio above is wider than the 1.35x the v3.1.1 port held against its own reference, even though this port is faster than that one. Five scenes are unchanged between the two versions: joint_grid, large_pyramid, rain, smash and tumbler. Over those five, solver time against the v3.1.1 port (v1.0.0) is:

Workers v3.2 port over v3.1.1 port
1 0.70x
2 0.68x
4 0.68x
8 0.71x

Over the same five scenes Box2D v3.2 takes 0.51x of the solver time of v3.1.1 at one worker and 0.48x at eight.

spinner and many_pyramids changed in v3.2 (twice the bodies in spinner, a new ground and offsets in many_pyramids), so they are left out of that comparison.

Both sides land on the same result bits at every worker count, in all seven scenes.

On amd64 the warm start, push and relax stages run AVX2 kernels generated by tools/asmgen from the Go stages, one operation at a time and in the same order, so they round as the Go code does. A test runs each kernel against its Go counterpart on random input and requires the same bits.

Measured on an AMD Ryzen 7 5800X3D, Windows/amd64, sixteen logical cores, GCC 13.2.0, Go 1.27.0, three repeats.

Running the comparison

The harness is in the tree, so the numbers above can be checked rather than taken. The reference is not vendored: clone Box2D v3.2.0 beside this repository, or pass -DBOX2D_SOURCE_DIR=<path>.

git clone --branch v3.2.0 --depth 1 https://github.com/erincatto/box2d ../box2d
cmake -S tools/cbench -B build/cbench -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build/cbench

Run one arm at a time and write a JSON file per worker count:

mkdir -p testdata/bench
./build/cbench/cbench --want-lane=avx2 --repeats=3 --workers=8 --arm=c-avx2 --out=testdata/bench/c-avx2-w8.json
GOTOOLCHAIN=go1.27.0 GOEXPERIMENT=simd go test -tags dbox2d_simd -run TestSceneBench -timeout 7200s . -bench.arm=go-avx2 -bench.want-lane=avx2 -bench.repeats=3 -bench.workers=8 -bench.out=testdata/bench/go-avx2-w8.json

benchcmp compares one worker count and benchscale a whole sweep. Both refuse to compare runs that did not share a lane path, a lane width, a clock or an observed worker count, so a mismatched pair is an error rather than a misleading ratio:

go run ./tools/benchcmp testdata/bench/c-avx2-w8.json testdata/bench/go-avx2-w8.json
go run ./tools/benchscale -base=c-avx2 testdata/bench/c-avx2-w*.json testdata/bench/go-avx2-w*.json

The protocol, the worker-pool contract, the lane and clock guards, and the per-scene tables are documented in tools/cbench/README.md. Results are not tracked in the repository: one is a single machine on a single day.

Profile-guided optimization

Measured on the v3.1.1 port, a profile takes 3 to 6 percent off the solver: 2.7 percent on one worker and 5 to 6 percent from two workers up, in all seven scenes. It changes no result bits. The checksum witnesses, the conformance traces, the no-FMA gate and the per-scene hashes all hold with a profile applied, because every float product already sits inside an explicit rounding conversion, and a fused multiply-add cannot cross that barrier.

Go reads default.pgo from the directory of the main package, so a library cannot ship one for you. Collect a profile of your own workload, which is the one whose hot paths matter:

go test -run "^$" -bench . -cpuprofile=cpu.pprof
cp cpu.pprof ./cmd/your_app/default.pgo
go build ./cmd/your_app

A profile kept elsewhere works through the flag, and -pgo=off builds without one:

go build -pgo=cpu.pprof ./cmd/game
go build -pgo=off ./cmd/game

The sample hosts carry a profile of the benchmark scenes, so go run ./cmd/native and the WebAssembly build use it with no flag.

License

MIT. This is a derivative work of Box2D, which is also MIT. See LICENSE.

Documentation

Overview

Package b2 implements a deterministic 2D rigid body solver.

Equal inputs produce the same result bits on every supported architecture, on every run. A world therefore survives a snapshot, a replay and a rollback without drift.

The package builds in two scalar modes. The default is float32. The build tag dbox2d_fixed selects the Q32.32 fixed-point arithmetic of github.com/dhannyell/fixed, with the same determinism promise; see the README for the mode details and commands. ScalarMode reports the mode of a build.

The optional dbox2d_simd tag opts in to a SIMD contact solver in either mode. It produces the same result bits as the scalar solver.

Fidelity

The package is a port of Box2D v3.1.1. It keeps the upstream file decomposition, the upstream names without the b2 prefix, and the upstream order of operations. The port preserves the upstream formulation, not its output bits. Box2D computes in floating point, so the two libraries produce different trajectories.

Fixed-point arithmetic forbids some upstream lines, such as an epsilon tuned for float or a stopping criterion that depends on it. Each such place is a recorded divergence with a reason and a test.

Angles

Every angle of the API is a turn, not a radian, in both modes: one quarter turn is QFromRatio(1, 4), and an angular velocity is in turns per second. Inside, the body state keeps radians per second, the unit of the reference. A joint keeps its angles in radians in float mode, as the reference does, and in turns in fixed mode, because a turn reduces without pi (D-004). The solver stores an orientation as a Rot sine and cosine pair, never as an angle.

IDs

WorldId, BodyId, ShapeId, ChainId and JointId are opaque handles. Their zero values are null, and IDs of the same type can be compared with ==. Pass them by value and obtain them from package functions; constructing a packed value by hand may make it refer to whatever occupies that slot.

Accumulation

Saturated addition is not associative near the range limits. The solver keeps a fixed accumulation order for that reason. The worker count never changes that order: TestStepIsWorkerCountIndependent pins the same checksum for one and for several workers.

Index

Examples

Constants

View Source
const (
	DefaultCategoryBits uint64 = 1
	DefaultMaskBits     uint64 = math.MaxUint64
)

Default filter bits. upstream B2_DEFAULT_CATEGORY_BITS, B2_DEFAULT_MASK_BITS

View Source
const MaxPolygonVertices = 8

MaxPolygonVertices is the vertex limit of a convex polygon. Raising it costs performance even for shapes that use fewer vertices.

View Source
const ScalarMode = "float"

ScalarMode names the scalar mode of this build: "float" or "fixed".

Variables

View Source
var (

	// Huge is the largest coordinate the world accepts and the rigid push
	// limit of a collision plane. It corresponds to B2_HUGE in
	// include/box2d/math_functions.h. It bounds a length that an
	// application supplies, so a wild input fails early.
	Huge = QFromInt(hugeMeters)
)

A length is a meter. The reference lets an application rescale its tolerances; this package does not, because a world that rescales them stops matching a world that does not. See DIVERGENCES.md.

Functions

func AABBContains

func AABBContains(a, b AABB) bool

AABBContains reports whether a fully contains b.

func AABBOverlaps

func AABBOverlaps(a, b AABB) bool

AABBOverlaps reports whether a and b overlap.

func Checksum

func Checksum(worldId WorldId) uint64

Checksum folds the complete deterministic state of a world into one integer. Application data and internal ids are excluded because they do not affect simulation. Bodies, shapes, contacts and joints use commutative folds, so equivalent worlds do not depend on creation order.

func ClampInt

func ClampInt(a, lower, upper int) int

ClampInt returns a limited to the range [lower, upper].

func DestroyBody

func DestroyBody(bodyId BodyId)

DestroyBody destroys a body. Every shape attached to it goes away too.

func DestroyChain added in v0.4.0

func DestroyChain(chainId ChainId)

DestroyChain ports b2DestroyChain.

func DestroyJoint added in v0.3.0

func DestroyJoint(jointId JointId)

DestroyJoint destroys a joint and wakes the two bodies.

func DestroyShape

func DestroyShape(shapeId ShapeId, updateBodyMass bool)

DestroyShape destroys a shape. Pass updateBodyMass true to recompute the mass of the body from the remaining shapes.

func DestroyWorld

func DestroyWorld(worldId WorldId)

DestroyWorld destroys a world and every body and shape in it.

func GetLengthAndNormalize

func GetLengthAndNormalize(v Vec2) (Q, Vec2)

GetLengthAndNormalize returns the length of v and the unit vector with the same direction. A vector Normalize sends to zero returns a zero length and the zero vector.

func IsDoublePrecision added in v1.1.0

func IsDoublePrecision() bool

IsDoublePrecision reports whether the library was built with the dbox2d_double tag. It corresponds to b2IsDoublePrecision.

func IsNormalized

func IsNormalized(a Vec2) bool

IsNormalized reports whether a has unit length.

func IsNormalizedRot

func IsNormalizedRot(q Rot) bool

IsNormalizedRot reports whether q has unit length.

func IsValidAABB

func IsValidAABB(a AABB) bool

IsValidAABB reports whether a is usable and not inverted.

func IsValidPlane

func IsValidPlane(a Plane) bool

IsValidPlane reports whether a has a unit normal and a usable offset.

func IsValidPos added in v1.1.0

func IsValidPos(p Pos) bool

IsValidPos reports whether p is a usable position. It corresponds to b2IsValidPos.

func IsValidQ

func IsValidQ(a Q) bool

IsValidQ reports whether a is finite in the float32 format.

func IsValidRay

func IsValidRay(input *RayCastInput) bool

IsValidRay reports whether a ray cast input is usable.

func IsValidRot added in v1.1.0

func IsValidRot(q Rot) bool

IsValidRot reports whether q is a usable and normalized rotation. It corresponds to b2IsValidRot.

func IsValidTransform added in v1.1.0

func IsValidTransform(t Transform) bool

IsValidTransform reports whether t has a usable position and a valid rotation. It corresponds to b2IsValidTransform.

func IsValidVec2

func IsValidVec2(v Vec2) bool

IsValidVec2 reports whether v is a usable vector.

func IsValidWorldTransform added in v1.1.0

func IsValidWorldTransform(t WorldTransform) bool

IsValidWorldTransform reports whether t has a usable position and a valid rotation. It corresponds to b2IsValidWorldTransform.

func LanePath added in v1.0.0

func LanePath() string

LanePath reports the contact-solver lane path of this build. It is "scalar" whenever the wide family is absent, so a caller can record the path it actually got rather than the path its build tags asked for.

func LaneWidth added in v1.0.0

func LaneWidth() int

LaneWidth reports the number of contacts one solver unit carries. The scalar family carries one.

func PointInCapsule

func PointInCapsule(shape *Capsule, point Vec2) bool

PointInCapsule reports whether a point overlaps a capsule in local space.

func PointInCircle

func PointInCircle(shape *Circle, point Vec2) bool

PointInCircle reports whether a point overlaps a circle in local space.

func QToFloat64 added in v0.6.0

func QToFloat64(q Q) float64

QToFloat64 returns q as a float64. The conversion is exact.

func StoreBodyId

func StoreBodyId(id BodyId) uint64

StoreBodyId packs a body id into a uint64.

func StoreChainId

func StoreChainId(id ChainId) uint64

StoreChainId packs a chain id into a uint64.

func StoreContactId added in v1.1.0

func StoreContactId(id ContactId) [3]uint32

StoreContactId packs a contact id into three uint32 values. It corresponds to b2StoreContactId.

func StoreJointId

func StoreJointId(id JointId) uint64

StoreJointId packs a joint id into a uint64.

func StoreShapeId

func StoreShapeId(id ShapeId) uint64

StoreShapeId packs a shape id into a uint64.

func StoreWorldId

func StoreWorldId(id WorldId) uint32

StoreWorldId packs a world id into a uint32.

func ValidateHull

func ValidateHull(hull *Hull) bool

ValidateHull reports whether a hull is convex and free of collinear points. It is expensive, so it does not belong in a running simulation.

func ValidateRecording added in v1.1.0

func ValidateRecording(data []byte, workerCount int) bool

ValidateRecording replays a whole recording and reports whether every state hash and query reproduced. It corresponds to b2ValidateRecording.

Types

type AABB

type AABB struct {
	LowerBound Vec2
	UpperBound Vec2
}

AABB is an axis-aligned bounding box.

func AABBUnion

func AABBUnion(a, b AABB) AABB

AABBUnion returns the smallest box that contains a and b.

func ComputeCapsuleBounds added in v1.1.0

func ComputeCapsuleBounds(shape *Capsule, xf WorldTransform) AABB

ComputeCapsuleBounds returns the bounding box of a transformed capsule. It corresponds to b2ComputeCapsuleBounds.

func ComputeCircleBounds added in v1.1.0

func ComputeCircleBounds(shape *Circle, xf WorldTransform) AABB

ComputeCircleBounds returns the bounding box of a transformed circle. It corresponds to b2ComputeCircleBounds.

func ComputePolygonBounds added in v1.1.0

func ComputePolygonBounds(shape *Polygon, xf WorldTransform) AABB

ComputePolygonBounds returns the bounding box of a transformed polygon. It corresponds to b2ComputePolygonBounds.

func ComputeSegmentBounds added in v1.1.0

func ComputeSegmentBounds(shape *Segment, xf WorldTransform) AABB

ComputeSegmentBounds returns the bounding box of a transformed segment. It corresponds to b2ComputeSegmentBounds.

func MakeAABB

func MakeAABB(points []Vec2, radius Q) AABB

MakeAABB returns the box that bounds a set of circles of the given radius. It panics when points is empty.

type BodyDef

type BodyDef struct {
	// The body type: static, kinematic or dynamic.
	Type BodyType

	// The initial world position. Create a body at its final position:
	// creating it at the origin and moving it costs nearly twice as much.
	Position Pos

	// The initial world rotation. Use MakeRot for an angle in turns.
	Rotation Rot

	// The initial linear velocity of the body origin, usually in meters per
	// second.
	LinearVelocity Vec2

	// The initial angular velocity, in turns per second. The reference uses
	// radians per second; an angle is a turn in this package.
	AngularVelocity Q

	// Linear damping reduces the linear velocity. A value larger than 1 is
	// valid but grows sensitive to the time step. Usually undesirable,
	// because it makes bodies move as if they float.
	LinearDamping Q

	// Angular damping reduces the angular velocity. A value larger than 1 is
	// valid but grows sensitive to the time step.
	AngularDamping Q

	// Scale of the gravity on this body, non-dimensional.
	GravityScale Q

	// Sleep speed threshold, default 0.05 meters per second.
	SleepThreshold Q

	// Continuous collision safety factor. The solver only uses continuous
	// collision when the body risks tunneling. If moving N meters risks
	// tunneling, the body is fast once it moves more than SafetyFactor times
	// N meters in one full time step. Non-dimensional. The recommended range
	// is [0.01, 0.5]; the default 0.5 favors performance with a low
	// tunneling risk.
	SafetyFactor Q

	// Optional body name for debugging, up to 10 bytes.
	Name string

	// Application data attached to the body.
	UserData any

	// Set this to false if the body must never fall asleep.
	EnableSleep bool

	// Whether the body starts awake.
	IsAwake bool

	// Motion locks to restrict linear and angular movement.
	MotionLocks MotionLocks

	// Treat the body as a high speed object that performs continuous
	// collision against dynamic and kinematic bodies, but not against other
	// bullets. Use sparingly: bullets solve no general dynamic-versus-dynamic
	// case and may interfere with joints.
	IsBullet bool

	// A disabled body does not move and does not collide.
	IsEnabled bool

	// Let the body bypass the rotational speed limit. Only for circular
	// bodies, like wheels.
	AllowFastRotation bool

	// Let the contacts of the body keep their manifold while the bodies
	// barely move. A contact recycles only when both bodies enable it.
	EnableContactRecycling bool
	// contains filtered or unexported fields
}

BodyDef holds the data to construct a rigid body. It is a temporary bundle of creation parameters; shapes come after construction. Initialize it with DefaultBodyDef.

func DefaultBodyDef

func DefaultBodyDef() BodyDef

DefaultBodyDef returns the default body definition.

type BodyEvents added in v0.3.0

type BodyEvents struct {
	MoveEvents []BodyMoveEvent
}

BodyEvents holds the body events of the last step. The slice stays valid until the next step; a body destroy makes its entry stale.

type BodyId

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

BodyId identifies a body. Its zero value is null.

func CreateBody

func CreateBody(worldId WorldId, def *BodyDef) BodyId

CreateBody creates a rigid body from a definition. The definition must come from DefaultBodyDef and is not retained.

func LoadBodyId

func LoadBodyId(x uint64) BodyId

LoadBodyId unpacks a body id from a uint64.

func (BodyId) ApplyAngularImpulse added in v0.4.0

func (bodyId BodyId) ApplyAngularImpulse(impulse Q, wake bool)

ApplyAngularImpulse applies an angular impulse and receives the impulse in the reference's angular units. It corresponds to b2Body_ApplyAngularImpulse.

func (BodyId) ApplyForce added in v0.4.0

func (bodyId BodyId) ApplyForce(force Vec2, point Pos, wake bool)

ApplyForce applies a force at a world point. It corresponds to b2Body_ApplyForce.

func (BodyId) ApplyForceToCenter added in v0.4.0

func (bodyId BodyId) ApplyForceToCenter(force Vec2, wake bool)

ApplyForceToCenter applies a force at the center of mass. It corresponds to b2Body_ApplyForceToCenter.

func (BodyId) ApplyLinearImpulse added in v0.4.0

func (bodyId BodyId) ApplyLinearImpulse(impulse Vec2, point Pos, wake bool)

ApplyLinearImpulse applies a linear impulse at a world point. It corresponds to b2Body_ApplyLinearImpulse.

func (BodyId) ApplyLinearImpulseToCenter added in v0.4.0

func (bodyId BodyId) ApplyLinearImpulseToCenter(impulse Vec2, wake bool)

ApplyLinearImpulseToCenter applies a linear impulse at the center of mass. It corresponds to b2Body_ApplyLinearImpulseToCenter.

func (BodyId) ApplyTorque added in v0.4.0

func (bodyId BodyId) ApplyTorque(torque Q, wake bool)

ApplyTorque applies a torque. It corresponds to b2Body_ApplyTorque.

func (BodyId) ClearForces added in v1.1.0

func (bodyId BodyId) ClearForces()

ClearForces clears the force and torque accumulated on the body. The world step clears them anyway; call this only to drop forces applied before the next step. It corresponds to b2Body_ClearForces.

func (BodyId) ComputeBounds added in v1.1.0

func (bodyId BodyId) ComputeBounds() AABB

ComputeBounds returns the union of the body's shape bounds. It corresponds to b2Body_ComputeBounds.

func (BodyId) Disable added in v0.4.0

func (bodyId BodyId) Disable()

Disable removes the body from simulation. It corresponds to b2Body_Disable.

Example
worldId, _, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

boxId.Disable()
fmt.Println(boxId.IsEnabled())

boxId.Enable()
fmt.Println(boxId.IsEnabled())
Output:
false
true

func (BodyId) Enable added in v0.4.0

func (bodyId BodyId) Enable()

Enable returns the body to simulation. It corresponds to b2Body_Enable.

func (BodyId) EnableContactEvents added in v0.4.0

func (bodyId BodyId) EnableContactEvents(flag bool)

EnableContactEvents enables contact events on every body shape. It corresponds to b2Body_EnableContactEvents.

func (BodyId) EnableContactRecycling added in v1.1.0

func (bodyId BodyId) EnableContactRecycling(flag bool)

EnableContactRecycling lets the contacts of the body keep their manifold while the bodies barely move. A contact recycles only when both bodies enable it, and only contacts created after this call see the change. It corresponds to b2Body_EnableContactRecycling.

func (BodyId) EnableHitEvents added in v0.4.0

func (bodyId BodyId) EnableHitEvents(flag bool)

EnableHitEvents enables hit events on every body shape. It corresponds to b2Body_EnableHitEvents.

func (BodyId) EnableSleeping added in v1.1.0

func (bodyId BodyId) EnableSleeping(enableSleep bool)

EnableSleeping enables or disables sleeping. It corresponds to b2Body_EnableSleeping.

func (BodyId) GetAngularDamping added in v0.4.0

func (bodyId BodyId) GetAngularDamping() Q

GetAngularDamping returns angular damping. It corresponds to b2Body_GetAngularDamping.

func (BodyId) GetAngularVelocity added in v0.4.0

func (bodyId BodyId) GetAngularVelocity() Q

GetAngularVelocity returns the body's angular velocity in turns per second. It corresponds to b2Body_GetAngularVelocity.

func (BodyId) GetContactCapacity added in v0.4.0

func (bodyId BodyId) GetContactCapacity() int

GetContactCapacity returns the body's conservative contact capacity. It corresponds to b2Body_GetContactCapacity.

func (BodyId) GetContactData added in v0.4.0

func (bodyId BodyId) GetContactData(data []ContactData) int

GetContactData fills touching contact data in body-list order. It corresponds to b2Body_GetContactData.

Example
worldDef := b2.DefaultWorldDef()
worldId := b2.CreateWorld(&worldDef)
defer b2.DestroyWorld(worldId)

groundDef := b2.DefaultBodyDef()
groundId := b2.CreateBody(worldId, &groundDef)
groundShapeDef := b2.DefaultShapeDef()
groundBox := b2.MakeBox(b2.QFromInt(5), b2.QHalf())
b2.CreatePolygonShape(groundId, &groundShapeDef, &groundBox)

boxDef := b2.DefaultBodyDef()
boxDef.Type = b2.DynamicBody
boxDef.Position = b2.ToPos(b2.Vec2{Y: b2.QOne()})
boxId := b2.CreateBody(worldId, &boxDef)
boxShapeDef := b2.DefaultShapeDef()
box := b2.MakeSquare(b2.QHalf())
b2.CreatePolygonShape(boxId, &boxShapeDef, &box)

dt := b2.QOne().Div(b2.QFromInt(60))
for range 60 {
	worldId.Step(dt, 4)
}

data := make([]b2.ContactData, boxId.GetContactCapacity())
count := boxId.GetContactData(data)

fmt.Println(count)
fmt.Println(data[0].ShapeIdA.GetBody() == groundId || data[0].ShapeIdB.GetBody() == groundId)
Output:
1
true

func (BodyId) GetGravityScale added in v0.4.0

func (bodyId BodyId) GetGravityScale() Q

GetGravityScale returns the body's gravity scale. It corresponds to b2Body_GetGravityScale.

func (BodyId) GetJointCount added in v0.4.0

func (bodyId BodyId) GetJointCount() int

GetJointCount returns the number of joints on the body. It corresponds to b2Body_GetJointCount.

func (BodyId) GetJoints added in v0.4.0

func (bodyId BodyId) GetJoints(joints []JointId) int

GetJoints fills joints in body-list order. It corresponds to b2Body_GetJoints.

func (BodyId) GetLinearDamping added in v0.4.0

func (bodyId BodyId) GetLinearDamping() Q

GetLinearDamping returns linear damping. It corresponds to b2Body_GetLinearDamping.

func (BodyId) GetLinearVelocity added in v0.4.0

func (bodyId BodyId) GetLinearVelocity() Vec2

GetLinearVelocity returns the body's linear velocity. It corresponds to b2Body_GetLinearVelocity.

func (BodyId) GetLocalCenter added in v1.1.0

func (bodyId BodyId) GetLocalCenter() Vec2

GetLocalCenter returns the center of mass in local coordinates. It corresponds to b2Body_GetLocalCenter.

func (BodyId) GetLocalPoint added in v0.4.0

func (bodyId BodyId) GetLocalPoint(worldPoint Pos) Vec2

GetLocalPoint converts a world point to the body's local frame. It corresponds to b2Body_GetLocalPoint.

func (BodyId) GetLocalPointVelocity added in v0.4.0

func (bodyId BodyId) GetLocalPointVelocity(localPoint Vec2) Vec2

GetLocalPointVelocity returns the velocity at a local point. It corresponds to b2Body_GetLocalPointVelocity.

func (BodyId) GetLocalVector added in v0.4.0

func (bodyId BodyId) GetLocalVector(worldVector Vec2) Vec2

GetLocalVector converts a world vector to the body's local frame. It corresponds to b2Body_GetLocalVector.

func (BodyId) GetMass added in v0.4.0

func (bodyId BodyId) GetMass() Q

GetMass returns the mass of the body, usually in kilograms. It corresponds to b2Body_GetMass.

func (BodyId) GetMassData added in v0.4.0

func (bodyId BodyId) GetMassData() MassData

GetMassData returns the body's mass, local center and rotational inertia. It corresponds to b2Body_GetMassData.

func (BodyId) GetMaxExtent added in v1.1.0

func (bodyId BodyId) GetMaxExtent() Q

GetMaxExtent returns the maximum distance from any point on the body shapes to the center of mass. It corresponds to b2Body_GetMaxExtent.

func (BodyId) GetMaxExtentFromOrigin added in v1.1.0

func (bodyId BodyId) GetMaxExtentFromOrigin() Q

GetMaxExtentFromOrigin returns a conservative maximum distance from any point on the body shapes to the body origin. It corresponds to b2Body_GetMaxExtentFromOrigin.

func (BodyId) GetMinExtent added in v1.1.0

func (bodyId BodyId) GetMinExtent() Q

GetMinExtent returns the minimum distance from any point on the body shapes to the center of mass. It corresponds to b2Body_GetMinExtent.

func (BodyId) GetMotionLocks added in v1.1.0

func (bodyId BodyId) GetMotionLocks() MotionLocks

GetMotionLocks returns the motion locks. It corresponds to b2Body_GetMotionLocks.

func (BodyId) GetName added in v0.4.0

func (bodyId BodyId) GetName() string

GetName returns the stored body name. It corresponds to b2Body_GetName.

func (BodyId) GetPosition added in v0.4.0

func (bodyId BodyId) GetPosition() Pos

GetPosition returns the world position of the body origin. It corresponds to b2Body_GetPosition.

func (BodyId) GetRotation added in v0.4.0

func (bodyId BodyId) GetRotation() Rot

GetRotation returns the world rotation of the body. It corresponds to b2Body_GetRotation.

func (BodyId) GetRotationalInertia added in v0.4.0

func (bodyId BodyId) GetRotationalInertia() Q

GetRotationalInertia returns the inertia about the center of mass. It corresponds to b2Body_GetRotationalInertia.

func (BodyId) GetSafetyFactor added in v1.1.0

func (bodyId BodyId) GetSafetyFactor() Q

GetSafetyFactor returns the continuous collision safety factor. It corresponds to b2Body_GetSafetyFactor.

func (BodyId) GetShapeCount added in v0.4.0

func (bodyId BodyId) GetShapeCount() int

GetShapeCount returns the number of shapes on the body. It corresponds to b2Body_GetShapeCount.

func (BodyId) GetShapes added in v0.4.0

func (bodyId BodyId) GetShapes(shapes []ShapeId) int

GetShapes fills shapes in body-list order. It corresponds to b2Body_GetShapes.

func (BodyId) GetSleepThreshold added in v0.4.0

func (bodyId BodyId) GetSleepThreshold() Q

GetSleepThreshold returns the body's sleep threshold. It corresponds to b2Body_GetSleepThreshold.

func (BodyId) GetTransform added in v0.4.0

func (bodyId BodyId) GetTransform() WorldTransform

GetTransform returns the world transform of the body. It corresponds to b2Body_GetTransform.

func (BodyId) GetType added in v0.4.0

func (bodyId BodyId) GetType() BodyType

GetType returns the body type. It corresponds to b2Body_GetType.

func (BodyId) GetUserData added in v0.4.0

func (bodyId BodyId) GetUserData() any

GetUserData returns the data attached to the body. It corresponds to b2Body_GetUserData.

func (BodyId) GetWorld added in v0.4.0

func (bodyId BodyId) GetWorld() WorldId

GetWorld returns the world containing the body. It corresponds to b2Body_GetWorld.

func (BodyId) GetWorldCenter added in v1.1.0

func (bodyId BodyId) GetWorldCenter() Pos

GetWorldCenter returns the center of mass in world coordinates. It corresponds to b2Body_GetWorldCenter.

func (BodyId) GetWorldPoint added in v0.4.0

func (bodyId BodyId) GetWorldPoint(localPoint Vec2) Pos

GetWorldPoint converts a local point to the world frame. It corresponds to b2Body_GetWorldPoint.

func (BodyId) GetWorldPointVelocity added in v0.4.0

func (bodyId BodyId) GetWorldPointVelocity(worldPoint Pos) Vec2

GetWorldPointVelocity returns the velocity at a world point. It corresponds to b2Body_GetWorldPointVelocity.

func (BodyId) GetWorldVector added in v0.4.0

func (bodyId BodyId) GetWorldVector(localVector Vec2) Vec2

GetWorldVector converts a local vector to the world frame. It corresponds to b2Body_GetWorldVector.

func (BodyId) IsAwake added in v0.4.0

func (bodyId BodyId) IsAwake() bool

IsAwake reports whether the body is in the awake set. It corresponds to b2Body_IsAwake.

func (BodyId) IsBullet added in v0.4.0

func (bodyId BodyId) IsBullet() bool

IsBullet reports whether the body is treated as a bullet. It corresponds to b2Body_IsBullet.

func (BodyId) IsContactRecyclingEnabled added in v1.1.0

func (bodyId BodyId) IsContactRecyclingEnabled() bool

IsContactRecyclingEnabled reports whether the contacts of the body may recycle. It corresponds to b2Body_IsContactRecyclingEnabled.

func (BodyId) IsEnabled added in v0.4.0

func (bodyId BodyId) IsEnabled() bool

IsEnabled reports whether the body is enabled. It corresponds to b2Body_IsEnabled.

func (BodyId) IsNull

func (id BodyId) IsNull() bool

IsNull reports whether the id references nothing.

func (BodyId) IsSleepingEnabled added in v1.1.0

func (bodyId BodyId) IsSleepingEnabled() bool

IsSleepingEnabled reports whether the body may sleep. It corresponds to b2Body_IsSleepingEnabled.

func (BodyId) IsValid

func (id BodyId) IsValid() bool

IsValid reports whether the id references a live body.

func (BodyId) SetAngularDamping added in v0.4.0

func (bodyId BodyId) SetAngularDamping(angularDamping Q)

SetAngularDamping changes angular damping. It corresponds to b2Body_SetAngularDamping.

func (BodyId) SetAngularVelocity added in v0.4.0

func (bodyId BodyId) SetAngularVelocity(angularVelocity Q)

SetAngularVelocity changes the body's angular velocity in turns per second. It corresponds to b2Body_SetAngularVelocity.

func (BodyId) SetAwake added in v0.4.0

func (bodyId BodyId) SetAwake(awake bool)

SetAwake wakes or sleeps the body's island. It corresponds to b2Body_SetAwake.

func (BodyId) SetBullet added in v0.4.0

func (bodyId BodyId) SetBullet(flag bool)

SetBullet changes whether the body is treated as a bullet. It corresponds to b2Body_SetBullet.

func (BodyId) SetGravityScale added in v0.4.0

func (bodyId BodyId) SetGravityScale(gravityScale Q)

SetGravityScale changes the body's gravity scale. It corresponds to b2Body_SetGravityScale.

func (BodyId) SetLinearDamping added in v0.4.0

func (bodyId BodyId) SetLinearDamping(linearDamping Q)

SetLinearDamping changes linear damping. It corresponds to b2Body_SetLinearDamping.

func (BodyId) SetLinearVelocity added in v0.4.0

func (bodyId BodyId) SetLinearVelocity(linearVelocity Vec2)

SetLinearVelocity changes the body's linear velocity. It corresponds to b2Body_SetLinearVelocity.

func (BodyId) SetMassData added in v0.4.0

func (bodyId BodyId) SetMassData(massData MassData)

SetMassData overrides the body's mass, center and rotational inertia. It corresponds to b2Body_SetMassData.

func (BodyId) SetMotionLocks added in v1.1.0

func (bodyId BodyId) SetMotionLocks(locks MotionLocks)

SetMotionLocks restricts the body movement. A lock zeroes the matching velocity at the end of each sub-step; the angular lock also zeroes the rotational inertia. It corresponds to b2Body_SetMotionLocks.

func (BodyId) SetName added in v0.4.0

func (bodyId BodyId) SetName(name string)

SetName stores up to 10 bytes of the body name. It corresponds to b2Body_SetName.

func (BodyId) SetSafetyFactor added in v1.1.0

func (bodyId BodyId) SetSafetyFactor(safetyFactor Q)

SetSafetyFactor changes the continuous collision safety factor. Smaller is safer but can lead to hitching. It corresponds to b2Body_SetSafetyFactor.

func (BodyId) SetSleepThreshold added in v0.4.0

func (bodyId BodyId) SetSleepThreshold(sleepThreshold Q)

SetSleepThreshold changes the body's sleep threshold. It corresponds to b2Body_SetSleepThreshold.

func (BodyId) SetTargetTransform added in v0.4.0

func (bodyId BodyId) SetTargetTransform(target WorldTransform, timeStep Q, wake bool)

SetTargetTransform sets the velocity needed to reach a target transform in timeStep. A sleeping body is left alone unless wake is true, and it stays asleep when the motion would be below its sleep threshold. It corresponds to b2Body_SetTargetTransform.

func (BodyId) SetTransform added in v0.4.0

func (bodyId BodyId) SetTransform(position Pos, rotation Rot)

SetTransform changes the body's world transform. It corresponds to b2Body_SetTransform.

Example
worldId, _, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

boxId.SetTransform(b2.ToPos(b2.Vec2{X: b2.QOne(), Y: b2.QFromInt(3)}), b2.RotIdentity())

fmt.Println(boxId.GetPosition())
Output:
{1 3}

func (BodyId) SetType added in v0.4.0

func (bodyId BodyId) SetType(bodyType BodyType)

SetType changes the body type. It corresponds to b2Body_SetType.

Example
worldId, _, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

// A dynamic box turned static stops falling.
boxId.SetType(b2.StaticBody)

fmt.Println(boxId.GetType() == b2.StaticBody)
Output:
true

func (BodyId) SetUserData added in v0.4.0

func (bodyId BodyId) SetUserData(userData any)

SetUserData attaches application data to the body. It corresponds to b2Body_SetUserData.

func (BodyId) UpdateMassFromShapes added in v1.1.0

func (bodyId BodyId) UpdateMassFromShapes()

UpdateMassFromShapes recomputes mass data from the body's shapes. It corresponds to b2Body_UpdateMassFromShapes.

func (BodyId) WakeTouching added in v1.1.0

func (bodyId BodyId) WakeTouching()

WakeTouching wakes the bodies touching this body. It works for static bodies. It corresponds to b2Body_WakeTouching.

type BodyMoveEvent added in v0.3.0

type BodyMoveEvent struct {
	Transform  WorldTransform
	BodyId     BodyId
	UserData   any
	FellAsleep bool
}

BodyMoveEvent reports a body that the simulation moved. A body that the user moves does not report one. FellAsleep tells the application that it can sleep the object of the body. With sleep disabled, every dynamic and kinematic body reports on every step.

type BodyType

type BodyType int

BodyType selects how the solver treats a body.

const (
	// StaticBody has zero mass and zero velocity. An application may move it
	// manually.
	StaticBody BodyType = 0

	// KinematicBody has zero mass. The application sets the velocity and the
	// solver moves it.
	KinematicBody BodyType = 1

	// DynamicBody has positive mass. Forces determine the velocity and the
	// solver moves it.
	DynamicBody BodyType = 2

	// BodyTypeCount is the number of body types.
	BodyTypeCount = 3
)

type BoxCastInput added in v1.1.0

type BoxCastInput struct {
	// Box is the box to cast, in the tree's frame.
	Box AABB

	// Translation is the sweep translation.
	Translation Vec2

	// MaxFraction limits the translation to consider. It is usually one.
	MaxFraction Q
}

BoxCastInput is the input of a swept box cast through a tree. It corresponds to b2BoxCastInput in include/box2d/collision.h.

type Capsule

type Capsule struct {
	// Center1 is the local center of the first semicircle.
	Center1 Vec2

	// Center2 is the local center of the second semicircle.
	Center2 Vec2

	// Radius is the radius of both semicircles.
	Radius Q
}

Capsule is a solid capsule: two semicircles joined by a rectangle.

type CastOutput

type CastOutput struct {
	// Normal is the surface normal at the hit point.
	Normal Vec2

	// Point is the surface hit point.
	Point Vec2

	// Fraction is the part of the input translation at the collision.
	Fraction Q

	// Iterations is the number of iterations the cast used.
	Iterations int

	// Hit reports whether the cast hit.
	Hit bool
}

CastOutput is the output of a ray cast or of a shape cast. An initial overlap returns a zero fraction and a zero normal.

func CastRayCapsule added in v1.1.0

func CastRayCapsule(shape *Capsule, input *RayCastInput) CastOutput

RayCastCapsule casts a ray against a capsule in local space. An initial overlap reports a hit at the ray origin with a zero fraction.

func CastRayCircle added in v1.1.0

func CastRayCircle(shape *Circle, input *RayCastInput) CastOutput

RayCastCircle casts a ray against a circle in local space. An initial overlap reports a hit at the ray origin with a zero fraction.

func CastRayPolygon added in v1.1.0

func CastRayPolygon(shape *Polygon, input *RayCastInput) CastOutput

RayCastPolygon casts a ray against a convex polygon in local space. An initial overlap reports a hit at the ray origin with a zero fraction.

A rounded polygon needs the shape cast, which arrives with the distance stage, so this function accepts only a polygon with a zero radius.

func CastRaySegment added in v1.1.0

func CastRaySegment(shape *Segment, input *RayCastInput, oneSided bool) CastOutput

RayCastSegment casts a ray against a segment in local space. A one-sided segment reports a miss for a ray that arrives from the left.

func CastShape added in v0.3.0

func CastShape(input *ShapeCastPairInput) CastOutput

ShapeCast casts shape B against a fixed shape A by conservative advancement and reports the hit point, the normal and the fraction of the translation. Shapes that start in contact report a hit at a zero fraction unless the input allows an encroach. It corresponds to b2CastShape in src/distance.c. The cast runs in frame A, so the point and the normal of the output are in frame A.

func CastShapeCapsule added in v1.1.0

func CastShapeCapsule(shape *Capsule, input *ShapeCastInput) CastOutput

ShapeCastCapsule casts a proxy against a capsule in the local frame of the capsule. It corresponds to b2ShapeCastCapsule in src/geometry.c.

func CastShapeCircle added in v1.1.0

func CastShapeCircle(shape *Circle, input *ShapeCastInput) CastOutput

ShapeCastCircle casts a proxy against a circle in the local frame of the circle. It corresponds to b2ShapeCastCircle in src/geometry.c.

func CastShapePolygon added in v1.1.0

func CastShapePolygon(shape *Polygon, input *ShapeCastInput) CastOutput

ShapeCastPolygon casts a proxy against a polygon in the local frame of the polygon. It corresponds to b2ShapeCastPolygon in src/geometry.c.

func CastShapeSegment added in v1.1.0

func CastShapeSegment(shape *Segment, input *ShapeCastInput) CastOutput

ShapeCastSegment casts a proxy against a segment in the local frame of the segment. It corresponds to b2ShapeCastSegment in src/geometry.c.

type CastResultFcn added in v0.3.0

type CastResultFcn func(shapeId ShapeId, point Pos, normal Vec2, fraction Q) Q

CastResultFcn receives each hit of a ray cast. Return -1 to skip the shape, 0 to stop, the fraction to clip the ray for the closest hit, or 1 to continue. It corresponds to b2CastResultFcn in include/box2d/types.h; the closure carries the context.

type ChainDef added in v0.4.0

type ChainDef struct {
	// Application data attached to the chain's segments.
	UserData any

	// An array of at least 2 points (open chain) or 3 points (loop). The
	// points are copied during creation.
	Points []Vec2

	// The ghost point before the first point of an open chain. It must be
	// set: the default is an infinity sentinel that CreateChain rejects.
	// Ignored for loops.
	Ghost1 Vec2

	// The ghost point after the last point of an open chain. It must be
	// set like Ghost1. Ignored for loops.
	Ghost2 Vec2

	// One material for every segment, or one material shared by all segments.
	Materials []SurfaceMaterial

	// Collision filtering data.
	Filter Filter

	// Enable sensors to detect this chain.
	EnableSensorEvents bool

	// Connect the last point back to the first point.
	IsLoop bool
	// contains filtered or unexported fields
}

ChainDef configures a chain shape. It corresponds to b2ChainDef.

func DefaultChainDef added in v0.4.0

func DefaultChainDef() ChainDef

DefaultChainDef returns the default chain definition. It corresponds to b2DefaultChainDef.

type ChainId

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

ChainId identifies a chain. Its zero value is null.

func CreateChain added in v0.4.0

func CreateChain(bodyId BodyId, def *ChainDef) ChainId

CreateChain creates a chain of segment shapes on a body. An open chain needs at least two points and both ghost points; a loop needs at least three points. It corresponds to b2CreateChain.

Example
worldId, groundId, _ := exampleWorld()
defer b2.DestroyWorld(worldId)

// An open chain of three points builds two segments; the ghost points
// past each end give smooth rolling contact at the ends.
def := b2.DefaultChainDef()
def.Points = []b2.Vec2{
	{X: b2.QFromInt(1)},
	{X: b2.QFromInt(2)},
	{X: b2.QFromInt(3)},
}
def.Ghost1 = b2.Vec2{X: b2.QFromInt(0)}
def.Ghost2 = b2.Vec2{X: b2.QFromInt(4)}
chainId := b2.CreateChain(groundId, &def)

fmt.Println(chainId.GetSegmentCount())
Output:
2

func LoadChainId

func LoadChainId(x uint64) ChainId

LoadChainId unpacks a chain id from a uint64.

func (ChainId) GetSegmentCount added in v0.4.0

func (chainId ChainId) GetSegmentCount() int

GetSegmentCount returns the number of segments in the chain. It corresponds to b2Chain_GetSegmentCount.

func (ChainId) GetSegments added in v0.4.0

func (chainId ChainId) GetSegments(segments []ShapeId) int

GetSegments fills segments with the chain's segment shapes. It corresponds to b2Chain_GetSegments.

func (ChainId) GetSurfaceMaterial added in v1.1.0

func (chainId ChainId) GetSurfaceMaterial(segmentIndex int) SurfaceMaterial

GetSurfaceMaterial returns the material of one chain segment. It corresponds to b2Chain_GetSurfaceMaterial.

func (ChainId) GetWorld added in v0.4.0

func (chainId ChainId) GetWorld() WorldId

GetWorld returns the world containing the chain. It corresponds to b2Chain_GetWorld.

func (ChainId) IsNull

func (id ChainId) IsNull() bool

IsNull reports whether the id references nothing.

func (ChainId) IsValid added in v0.4.0

func (chainId ChainId) IsValid() bool

IsValid reports whether the id references a live chain.

func (ChainId) SetAllSurfaceMaterials added in v1.1.0

func (chainId ChainId) SetAllSurfaceMaterials(material SurfaceMaterial)

SetAllSurfaceMaterials changes the material of every chain segment. It corresponds to b2Chain_SetAllSurfaceMaterials.

func (ChainId) SetSurfaceMaterial added in v1.1.0

func (chainId ChainId) SetSurfaceMaterial(material SurfaceMaterial, segmentIndex int)

SetSurfaceMaterial changes the material of one chain segment. It corresponds to b2Chain_SetSurfaceMaterial.

type ChainSegment

type ChainSegment struct {
	// Ghost1 is the tail ghost vertex.
	Ghost1 Vec2

	// Segment is the colliding part.
	Segment Segment

	// Ghost2 is the head ghost vertex.
	Ghost2 Vec2

	// ChainId is the owning chain shape. It is internal bookkeeping.
	ChainId int
}

ChainSegment is a line segment with one-sided collision. It collides only on the right side. A chain shape generates several of them, in the order ghost1, point1, point2, ghost2.

type Circle

type Circle struct {
	Center Vec2
	Radius Q
}

Circle is a solid circle.

type CollisionPlane added in v0.4.0

type CollisionPlane struct {
	Plane        Plane
	PushLimit    Q
	Push         Q
	ClipVelocity bool
}

CollisionPlane is a plane constraint for the mover plane solver.

type ContactBeginTouchEvent added in v0.3.0

type ContactBeginTouchEvent struct {
	// ShapeIdA is the first shape.
	ShapeIdA ShapeId

	// ShapeIdB is the second shape.
	ShapeIdB ShapeId

	// ContactId is the transient contact id. The world may destroy the
	// contact when it is modified or simulated; check ContactId.IsValid
	// before using it. ContactId.GetData returns the manifold.
	ContactId ContactId
}

ContactBeginTouchEvent reports that two shapes started to touch.

type ContactData added in v0.4.0

type ContactData struct {
	// ContactId identifies the contact. It may be held across steps but
	// can become stale; check ContactId.IsValid before using it.
	ContactId ContactId

	// ShapeIdA is the first shape in the contact.
	ShapeIdA ShapeId

	// ShapeIdB is the second shape in the contact.
	ShapeIdB ShapeId

	// Manifold is the current contact manifold.
	Manifold Manifold
}

ContactData reports the manifold of a touching contact on a body. It corresponds to b2ContactData in include/box2d/types.h.

type ContactEndTouchEvent added in v0.3.0

type ContactEndTouchEvent struct {
	// ShapeIdA is the first shape. It may be destroyed; see IsValid.
	ShapeIdA ShapeId

	// ShapeIdB is the second shape. It may be destroyed; see IsValid.
	ShapeIdB ShapeId

	// ContactId is the contact. It may be destroyed; see IsValid.
	ContactId ContactId
}

ContactEndTouchEvent reports that two shapes stopped touching. Any action that destroys a contact between steps also reports one, such as a transform change, a body or shape destroy, or a body type change.

type ContactEvents added in v0.3.0

type ContactEvents struct {
	BeginEvents []ContactBeginTouchEvent
	EndEvents   []ContactEndTouchEvent
	HitEvents   []ContactHitEvent
}

ContactEvents holds the contact events of the last step. The slices stay valid until the next step; a body or shape destroy may make an id in them stale.

type ContactHitEvent added in v0.3.0

type ContactHitEvent struct {
	// ShapeIdA is the first shape.
	ShapeIdA ShapeId

	// ShapeIdB is the second shape.
	ShapeIdB ShapeId

	// ContactId is the contact. It may be destroyed; see IsValid.
	ContactId ContactId

	// Point is where the shapes hit at the start of the step. It is the
	// mid-point between the two surfaces.
	Point Pos

	// Normal points from shape A to shape B.
	Normal Vec2

	// ApproachSpeed is the closing speed of the shapes. It is positive.
	ApproachSpeed Q
}

ContactHitEvent reports that two shapes collided faster than the hit event threshold. A speculative contact with a confirmed impulse also reports one.

type ContactId added in v1.1.0

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

ContactId identifies a contact. Its zero value is null. The generation advances each time a contact takes the slot, so a held id goes stale once the contact is destroyed. It corresponds to b2ContactId.

func LoadContactId added in v1.1.0

func LoadContactId(values [3]uint32) ContactId

LoadContactId unpacks a contact id from three uint32 values. It corresponds to b2LoadContactId.

func (ContactId) GetData added in v1.1.0

func (contactId ContactId) GetData() ContactData

GetData returns the shapes and the manifold of a contact. The manifold may have no points if the contact is not touching. It corresponds to b2Contact_GetData.

func (ContactId) IsNull added in v1.1.0

func (id ContactId) IsNull() bool

IsNull reports whether the id references nothing.

func (ContactId) IsValid added in v1.1.0

func (contactId ContactId) IsValid() bool

IsValid reports whether the id references a live contact. It provides validation for up to 2^32 allocations per slot. It corresponds to b2Contact_IsValid.

type Counters added in v0.4.0

type Counters struct {
	BodyCount, ShapeCount, ContactCount, JointCount, IslandCount, StackUsed, StaticTreeHeight, TreeHeight int
	TaskCount                                                                                             int
	ColorCounts                                                                                           [graphColorCount]int

	// AwakeContactCount is the number of contacts the collide pass
	// touches: the graph contacts and the awake non-touching contacts.
	AwakeContactCount int

	// RecycledContactCount is the number of contacts recycled in the last
	// step.
	RecycledContactCount int
}

Counters reports world sizes and solver storage usage for diagnostics.

type CustomFilterFcn added in v0.4.0

type CustomFilterFcn func(shapeIdA, shapeIdB ShapeId) bool

CustomFilterFcn decides whether two shapes may collide. It corresponds to b2CustomFilterFcn; return false to reject the pair. With several workers it runs on worker goroutines while the step mutates the world: it must not call the world API or query it, must not panic, and must be safe to call concurrently.

type DebugDraw added in v0.4.0

type DebugDraw struct {
	// DrawPolygonFcn draws a closed polygon provided in CCW order.
	DrawPolygonFcn DrawPolygonFcn
	// DrawSolidPolygonFcn draws a solid closed polygon provided in CCW order.
	DrawSolidPolygonFcn DrawSolidPolygonFcn
	// DrawCircleFcn draws a circle.
	DrawCircleFcn DrawCircleFcn
	// DrawSolidCircleFcn draws a solid circle.
	DrawSolidCircleFcn DrawSolidCircleFcn
	// DrawSolidCapsuleFcn draws a solid capsule.
	DrawSolidCapsuleFcn DrawSolidCapsuleFcn
	// DrawLineFcn draws a line segment.
	DrawLineFcn DrawLineFcn
	// DrawTransformFcn draws a transform at a host-chosen length scale.
	DrawTransformFcn DrawTransformFcn
	// DrawPointFcn draws a point.
	DrawPointFcn DrawPointFcn
	// DrawStringFcn draws a string in world space.
	DrawStringFcn DrawStringFcn
	// DrawBoundsFcn draws a bounding box.
	DrawBoundsFcn DrawBoundsFcn

	// DrawingBounds is the world region to draw. An empty box draws nothing.
	DrawingBounds AABB
	// ForceScale scales the drawn contact and friction forces.
	ForceScale Q
	// JointScale scales every joint drawing.
	JointScale Q

	// DrawContacts draws contact points.
	DrawContacts bool
	// DrawAnchorA draws contact points at anchor A instead of anchor B.
	DrawAnchorA bool
	// DrawShapes draws shapes.
	DrawShapes bool
	// DrawChainNormals draws chain segment normals.
	DrawChainNormals bool
	// DrawJoints draws joints.
	DrawJoints bool
	// DrawJointExtras draws additional information for joints.
	DrawJointExtras bool
	// DrawBounds draws the bounding boxes for shapes.
	DrawBounds bool
	// DrawMass draws the mass and center of mass of dynamic bodies.
	DrawMass bool
	// DrawBodyNames draws body names.
	DrawBodyNames bool
	// DrawGraphColors visualizes the graph coloring used for contacts and joints.
	DrawGraphColors bool
	// DrawContactFeatures draws contact feature ids.
	DrawContactFeatures bool
	// DrawContactNormals draws contact normals.
	DrawContactNormals bool
	// DrawContactForces draws contact normal forces.
	DrawContactForces bool
	// DrawFrictionForces draws contact friction forces.
	DrawFrictionForces bool
	// DrawIslands draws islands as bounding boxes.
	DrawIslands bool
}

DebugDraw holds the callbacks and options used by WorldId.Draw. Callbacks receive world coordinates. Start from DefaultDebugDraw, which fills every callback with a no-op and opens the drawing bounds to the whole world. It corresponds to b2DebugDraw in include/box2d/types.h.

func DefaultDebugDraw added in v0.4.0

func DefaultDebugDraw() DebugDraw

DefaultDebugDraw returns a debug drawer whose callbacks are safe no-ops, whose drawing bounds cover the world and which draws shapes. It corresponds to b2DefaultDebugDraw in src/types.c.

type DistanceInput added in v0.3.0

type DistanceInput struct {
	// ProxyA is the proxy of shape A.
	ProxyA ShapeProxy

	// ProxyB is the proxy of shape B.
	ProxyB ShapeProxy

	// Transform is the transform of shape B in the frame of shape A,
	// InvMulTransforms(worldA, worldB). The query runs in frame A.
	Transform Transform

	// UseRadii asks the solver to subtract the proxy radii.
	UseRadii bool
}

DistanceInput is the input of ComputeShapeDistance. It corresponds to b2DistanceInput in include/box2d/collision.h.

type DistanceJointDef added in v0.3.0

type DistanceJointDef struct {
	// Base joint definition.
	Base JointDef

	// The rest length of the joint. Clamped to a stable minimum value.
	Length Q

	// Enable the distance constraint to behave like a spring. If false the
	// distance joint is rigid, overriding the limit and the motor.
	EnableSpring bool

	// The lower spring force controls how much tension it can sustain.
	LowerSpringForce Q

	// The upper spring force controls how much compression it can sustain.
	UpperSpringForce Q

	// The spring linear stiffness in cycles per second.
	Hertz Q

	// The spring linear damping ratio, non-dimensional.
	DampingRatio Q

	// Enable and disable the joint limit.
	EnableLimit bool

	// The minimum length. Clamped to a stable minimum value.
	MinLength Q

	// The maximum length. Must be greater than or equal to the minimum
	// length.
	MaxLength Q

	// Enable and disable the joint motor.
	EnableMotor bool

	// The maximum motor force, usually in newtons.
	MaxMotorForce Q

	// The desired motor speed, usually in meters per second.
	MotorSpeed Q
	// contains filtered or unexported fields
}

DistanceJointDef configures a distance joint: the origin of local frame A and the origin of local frame B kept at a fixed length, or within a length range. Useful for ropes and springs. Initialize it with DefaultDistanceJointDef.

func DefaultDistanceJointDef added in v0.3.0

func DefaultDistanceJointDef() DistanceJointDef

DefaultDistanceJointDef returns the default distance joint definition.

type DistanceOutput added in v0.3.0

type DistanceOutput struct {
	// PointA is the closest point on shape A.
	PointA Vec2

	// PointB is the closest point on shape B.
	PointB Vec2

	// Normal points from A to B. It is invalid when the distance is zero.
	Normal Vec2

	// Distance is the final distance, zero when the shapes overlap.
	Distance Q

	// Iterations counts the GJK iterations used.
	Iterations int

	// SimplexCount is the number of simplexes stored in the debug slice.
	SimplexCount int
}

DistanceOutput is the output of ComputeShapeDistance, in frame A. It corresponds to b2DistanceOutput in include/box2d/collision.h.

func ComputeShapeDistance added in v1.1.0

func ComputeShapeDistance(input *DistanceInput, cache *SimplexCache, simplexes []Simplex) DistanceOutput

ShapeDistance computes the closest points between two convex proxies with GJK. The cache is input and output; start with the zero value. The simplexes slice receives the simplex of each iteration for debugging; pass nil to skip it. It corresponds to b2ShapeDistance in src/distance.c, https://box2d.org/files/ErinCatto_GJK_GDC2010.pdf.

The query runs in frame A, so the points and the normal of the output are in frame A. The reference stops on a squared search direction below 1000 * FLT_MIN; the fixed port stops on exactly zero (D-012).

type DrawBoundsFcn added in v1.1.0

type DrawBoundsFcn func(aabb AABB, color HexColor)

DrawBoundsFcn draws a bounding box.

type DrawCircleFcn added in v0.4.0

type DrawCircleFcn func(center Pos, radius Q, color HexColor)

DrawCircleFcn draws a circle outline.

type DrawLineFcn added in v1.1.0

type DrawLineFcn func(p1, p2 Pos, color HexColor)

DrawLineFcn draws a line segment.

type DrawPointFcn added in v0.4.0

type DrawPointFcn func(p Pos, size Q, color HexColor)

DrawPointFcn draws a point of the requested size.

type DrawPolygonFcn added in v0.4.0

type DrawPolygonFcn func(transform WorldTransform, vertices []Vec2, color HexColor)

DrawPolygonFcn draws a closed polygon, given in counter-clockwise order in the local frame of transform.

type DrawSolidCapsuleFcn added in v0.4.0

type DrawSolidCapsuleFcn func(p1, p2 Pos, radius Q, color HexColor)

DrawSolidCapsuleFcn draws a solid capsule.

type DrawSolidCircleFcn added in v0.4.0

type DrawSolidCircleFcn func(transform WorldTransform, center Vec2, radius Q, color HexColor)

DrawSolidCircleFcn draws a solid circle whose center is given in the local frame of transform.

type DrawSolidPolygonFcn added in v0.4.0

type DrawSolidPolygonFcn func(transform WorldTransform, vertices []Vec2, radius Q, color HexColor)

DrawSolidPolygonFcn draws a solid polygon with a rounded radius, given in the local frame of transform.

type DrawStringFcn added in v0.4.0

type DrawStringFcn func(p Pos, s string, color HexColor)

DrawStringFcn draws a world-space string.

type DrawTransformFcn added in v0.4.0

type DrawTransformFcn func(transform WorldTransform)

DrawTransformFcn draws a transform with a host-selected scale.

type DynamicTree added in v0.7.0

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

DynamicTree is a standalone bounding volume hierarchy over proxies. The world keeps its own trees; this type serves user code that wants the tree as a spatial structure. It corresponds to b2DynamicTree and the b2DynamicTree_* functions of include/box2d/collision.h.

func NewDynamicTree added in v0.7.0

func NewDynamicTree(proxyCapacity int) *DynamicTree

NewDynamicTree returns an empty tree with room for proxyCapacity proxies. It corresponds to b2CreateDynamicTree.

func (*DynamicTree) CastBox added in v1.1.0

func (t *DynamicTree) CastBox(input *BoxCastInput, maskBits uint64, fcn TreeBoxCastCallbackFcn) TreeStats

CastBox calls back every proxy the swept box may reach. The box sweeps from its origin to origin + MaxFraction * Translation. It corresponds to b2DynamicTree_CastBox.

func (*DynamicTree) CastRay added in v1.1.0

func (t *DynamicTree) CastRay(input *RayCastInput, maskBits uint64, fcn TreeRayCastCallbackFcn) TreeStats

CastRay calls back every proxy whose box the ray reaches. It corresponds to b2DynamicTree_CastRay.

func (*DynamicTree) CreateProxy added in v0.7.0

func (t *DynamicTree) CreateProxy(aabb AABB, categoryBits uint64, userData uint64) int

CreateProxy inserts a proxy with a fat box and returns its id. It corresponds to b2CreateTreeProxy.

func (*DynamicTree) Destroy added in v0.7.0

func (t *DynamicTree) Destroy()

Destroy releases the tree. It corresponds to b2DestroyDynamicTree.

func (*DynamicTree) DestroyProxy added in v0.7.0

func (t *DynamicTree) DestroyProxy(proxyId int)

DestroyProxy removes a proxy. It corresponds to b2DestroyTreeProxy.

func (*DynamicTree) GetAreaRatio added in v0.7.0

func (t *DynamicTree) GetAreaRatio() Q

GetAreaRatio returns the summed perimeter of the internal nodes over the perimeter of the root. It corresponds to b2DynamicTree_GetAreaRatio.

func (*DynamicTree) GetByteCount added in v1.1.0

func (t *DynamicTree) GetByteCount() int

GetByteCount returns the memory the tree holds. It corresponds to b2DynamicTree_GetByteCount.

func (*DynamicTree) GetCategoryBits added in v0.7.0

func (t *DynamicTree) GetCategoryBits(proxyId int) uint64

GetCategoryBits returns the category bits of a proxy. It corresponds to b2DynamicTree_GetCategoryBits.

func (*DynamicTree) GetHeight added in v0.7.0

func (t *DynamicTree) GetHeight() int

GetHeight returns the height of the tree. It corresponds to b2DynamicTree_GetHeight.

func (*DynamicTree) GetProxyBounds added in v1.1.0

func (t *DynamicTree) GetProxyBounds(proxyId int) AABB

GetProxyBounds returns the box of a proxy. It corresponds to b2DynamicTree_GetProxyBounds.

func (*DynamicTree) GetProxyCount added in v0.7.0

func (t *DynamicTree) GetProxyCount() int

GetProxyCount returns the number of proxies. It corresponds to b2DynamicTree_GetProxyCount.

func (*DynamicTree) GetRootBounds added in v0.7.0

func (t *DynamicTree) GetRootBounds() AABB

GetRootBounds returns the box of the root, or the empty box for an empty tree. It corresponds to b2DynamicTree_GetRootBounds.

func (*DynamicTree) GetUserData added in v0.7.0

func (t *DynamicTree) GetUserData(proxyId int) uint64

GetUserData returns the user data of a proxy. It corresponds to b2DynamicTree_GetUserData.

func (*DynamicTree) MoveProxy added in v0.7.0

func (t *DynamicTree) MoveProxy(proxyId int, aabb AABB)

MoveProxy reinserts a proxy with a new box. It corresponds to b2DynamicTree_MoveProxy.

func (*DynamicTree) OverlapAABB added in v1.1.0

func (t *DynamicTree) OverlapAABB(aabb AABB, maskBits uint64, fcn TreeQueryCallbackFcn) TreeStats

OverlapAABB calls back every proxy that overlaps the box and passes the mask. It corresponds to b2DynamicTree_OverlapAABB.

func (*DynamicTree) OverlapAABBAll added in v1.1.0

func (t *DynamicTree) OverlapAABBAll(aabb AABB, fcn TreeQueryCallbackFcn) TreeStats

OverlapAABBAll calls back every proxy that overlaps the box, ignoring the category bits. It corresponds to b2DynamicTree_OverlapAABBAll.

func (*DynamicTree) SetCategoryBits added in v0.7.0

func (t *DynamicTree) SetCategoryBits(proxyId int, categoryBits uint64)

SetCategoryBits changes the category bits of a proxy. It corresponds to b2DynamicTree_SetCategoryBits.

func (*DynamicTree) Validate added in v0.7.0

func (t *DynamicTree) Validate()

Validate checks the tree. Like the reference, it does nothing unless the build enables validation (-tags dbox2d_validate). It corresponds to b2DynamicTree_Validate.

type ExplosionDef added in v0.4.0

type ExplosionDef struct {
	// MaskBits filters the shapes the explosion reaches.
	MaskBits uint64

	// Position is the center of the explosion in world space.
	Position Pos

	// Radius is the full-impulse radius of the explosion.
	Radius Q

	// Falloff is the distance beyond Radius where the impulse fades to zero.
	Falloff Q

	// ImpulsePerLength scales the impulse by the perimeter facing the
	// explosion. It may be negative for an implosion.
	ImpulsePerLength Q
}

ExplosionDef configures an explosion. It corresponds to b2ExplosionDef in include/box2d/types.h.

func DefaultExplosionDef added in v0.4.0

func DefaultExplosionDef() ExplosionDef

DefaultExplosionDef returns an explosion definition with every mask bit set and every other field zero. It corresponds to b2DefaultExplosionDef.

type Filter

type Filter struct {
	// The collision category bits of this shape. Normally one bit per
	// application object type.
	CategoryBits uint64

	// The categories that this shape accepts for collision.
	MaskBits uint64

	// Shapes in the same negative group never collide; in the same positive
	// group they always collide. Zero has no effect. A non-zero group wins
	// against the mask bits.
	GroupIndex int
}

Filter controls collision between shapes, and between queries and shapes.

func DefaultFilter

func DefaultFilter() Filter

DefaultFilter returns the default filter: category 1, every mask bit set, no group.

type FilterJointDef added in v0.3.0

type FilterJointDef struct {
	// Base joint definition.
	Base JointDef
	// contains filtered or unexported fields
}

FilterJointDef configures a filter joint: it only disables collision between two specific bodies. Initialize it with DefaultFilterJointDef.

func DefaultFilterJointDef added in v0.3.0

func DefaultFilterJointDef() FilterJointDef

DefaultFilterJointDef returns the default filter joint definition.

type FrictionCallback added in v0.4.0

type FrictionCallback func(frictionA Q, userMaterialIdA uint64, frictionB Q, userMaterialIdB uint64) Q

FrictionCallback mixes the friction values of two shapes.

type HexColor added in v0.4.0

type HexColor uint32

HexColor is an RGB color encoded as 0xRRGGBB.

const (
	// ColorAliceBlue is RGB 0xF0F8FF.
	ColorAliceBlue HexColor = 0xF0F8FF
	// ColorAntiqueWhite is RGB 0xFAEBD7.
	ColorAntiqueWhite HexColor = 0xFAEBD7
	// ColorAqua is RGB 0x00FFFF.
	ColorAqua HexColor = 0x00FFFF
	// ColorAquamarine is RGB 0x7FFFD4.
	ColorAquamarine HexColor = 0x7FFFD4
	// ColorAzure is RGB 0xF0FFFF.
	ColorAzure HexColor = 0xF0FFFF
	// ColorBeige is RGB 0xF5F5DC.
	ColorBeige HexColor = 0xF5F5DC
	// ColorBisque is RGB 0xFFE4C4.
	ColorBisque HexColor = 0xFFE4C4
	// ColorBlack is RGB 0x000000.
	ColorBlack HexColor = 0x000000
	// ColorBlanchedAlmond is RGB 0xFFEBCD.
	ColorBlanchedAlmond HexColor = 0xFFEBCD
	// ColorBlue is RGB 0x0000FF.
	ColorBlue HexColor = 0x0000FF
	// ColorBlueViolet is RGB 0x8A2BE2.
	ColorBlueViolet HexColor = 0x8A2BE2
	// ColorBrown is RGB 0xA52A2A.
	ColorBrown HexColor = 0xA52A2A
	// ColorBurlywood is RGB 0xDEB887.
	ColorBurlywood HexColor = 0xDEB887
	// ColorCadetBlue is RGB 0x5F9EA0.
	ColorCadetBlue HexColor = 0x5F9EA0
	// ColorChartreuse is RGB 0x7FFF00.
	ColorChartreuse HexColor = 0x7FFF00
	// ColorChocolate is RGB 0xD2691E.
	ColorChocolate HexColor = 0xD2691E
	// ColorCoral is RGB 0xFF7F50.
	ColorCoral HexColor = 0xFF7F50
	// ColorCornflowerBlue is RGB 0x6495ED.
	ColorCornflowerBlue HexColor = 0x6495ED
	// ColorCornsilk is RGB 0xFFF8DC.
	ColorCornsilk HexColor = 0xFFF8DC
	// ColorCrimson is RGB 0xDC143C.
	ColorCrimson HexColor = 0xDC143C
	// ColorCyan is RGB 0x00FFFF.
	ColorCyan HexColor = 0x00FFFF
	// ColorDarkBlue is RGB 0x00008B.
	ColorDarkBlue HexColor = 0x00008B
	// ColorDarkCyan is RGB 0x008B8B.
	ColorDarkCyan HexColor = 0x008B8B
	// ColorDarkGoldenRod is RGB 0xB8860B.
	ColorDarkGoldenRod HexColor = 0xB8860B
	// ColorDarkGray is RGB 0xA9A9A9.
	ColorDarkGray HexColor = 0xA9A9A9
	// ColorDarkGreen is RGB 0x006400.
	ColorDarkGreen HexColor = 0x006400
	// ColorDarkKhaki is RGB 0xBDB76B.
	ColorDarkKhaki HexColor = 0xBDB76B
	// ColorDarkMagenta is RGB 0x8B008B.
	ColorDarkMagenta HexColor = 0x8B008B
	// ColorDarkOliveGreen is RGB 0x556B2F.
	ColorDarkOliveGreen HexColor = 0x556B2F
	// ColorDarkOrange is RGB 0xFF8C00.
	ColorDarkOrange HexColor = 0xFF8C00
	// ColorDarkOrchid is RGB 0x9932CC.
	ColorDarkOrchid HexColor = 0x9932CC
	// ColorDarkRed is RGB 0x8B0000.
	ColorDarkRed HexColor = 0x8B0000
	// ColorDarkSalmon is RGB 0xE9967A.
	ColorDarkSalmon HexColor = 0xE9967A
	// ColorDarkSeaGreen is RGB 0x8FBC8F.
	ColorDarkSeaGreen HexColor = 0x8FBC8F
	// ColorDarkSlateBlue is RGB 0x483D8B.
	ColorDarkSlateBlue HexColor = 0x483D8B
	// ColorDarkSlateGray is RGB 0x2F4F4F.
	ColorDarkSlateGray HexColor = 0x2F4F4F
	// ColorDarkTurquoise is RGB 0x00CED1.
	ColorDarkTurquoise HexColor = 0x00CED1
	// ColorDarkViolet is RGB 0x9400D3.
	ColorDarkViolet HexColor = 0x9400D3
	// ColorDeepPink is RGB 0xFF1493.
	ColorDeepPink HexColor = 0xFF1493
	// ColorDeepSkyBlue is RGB 0x00BFFF.
	ColorDeepSkyBlue HexColor = 0x00BFFF
	// ColorDimGray is RGB 0x696969.
	ColorDimGray HexColor = 0x696969
	// ColorDodgerBlue is RGB 0x1E90FF.
	ColorDodgerBlue HexColor = 0x1E90FF
	// ColorFireBrick is RGB 0xB22222.
	ColorFireBrick HexColor = 0xB22222
	// ColorFloralWhite is RGB 0xFFFAF0.
	ColorFloralWhite HexColor = 0xFFFAF0
	// ColorForestGreen is RGB 0x228B22.
	ColorForestGreen HexColor = 0x228B22
	// ColorFuchsia is RGB 0xFF00FF.
	ColorFuchsia HexColor = 0xFF00FF
	// ColorGainsboro is RGB 0xDCDCDC.
	ColorGainsboro HexColor = 0xDCDCDC
	// ColorGhostWhite is RGB 0xF8F8FF.
	ColorGhostWhite HexColor = 0xF8F8FF
	// ColorGold is RGB 0xFFD700.
	ColorGold HexColor = 0xFFD700
	// ColorGoldenRod is RGB 0xDAA520.
	ColorGoldenRod HexColor = 0xDAA520
	// ColorGray is RGB 0x808080.
	ColorGray HexColor = 0x808080
	// ColorGreen is RGB 0x008000.
	ColorGreen HexColor = 0x008000
	// ColorGreenYellow is RGB 0xADFF2F.
	ColorGreenYellow HexColor = 0xADFF2F
	// ColorHoneyDew is RGB 0xF0FFF0.
	ColorHoneyDew HexColor = 0xF0FFF0
	// ColorHotPink is RGB 0xFF69B4.
	ColorHotPink HexColor = 0xFF69B4
	// ColorIndianRed is RGB 0xCD5C5C.
	ColorIndianRed HexColor = 0xCD5C5C
	// ColorIndigo is RGB 0x4B0082.
	ColorIndigo HexColor = 0x4B0082
	// ColorIvory is RGB 0xFFFFF0.
	ColorIvory HexColor = 0xFFFFF0
	// ColorKhaki is RGB 0xF0E68C.
	ColorKhaki HexColor = 0xF0E68C
	// ColorLavender is RGB 0xE6E6FA.
	ColorLavender HexColor = 0xE6E6FA
	// ColorLavenderBlush is RGB 0xFFF0F5.
	ColorLavenderBlush HexColor = 0xFFF0F5
	// ColorLawnGreen is RGB 0x7CFC00.
	ColorLawnGreen HexColor = 0x7CFC00
	// ColorLemonChiffon is RGB 0xFFFACD.
	ColorLemonChiffon HexColor = 0xFFFACD
	// ColorLightBlue is RGB 0xADD8E6.
	ColorLightBlue HexColor = 0xADD8E6
	// ColorLightCoral is RGB 0xF08080.
	ColorLightCoral HexColor = 0xF08080
	// ColorLightCyan is RGB 0xE0FFFF.
	ColorLightCyan HexColor = 0xE0FFFF
	// ColorLightGoldenRodYellow is RGB 0xFAFAD2.
	ColorLightGoldenRodYellow HexColor = 0xFAFAD2
	// ColorLightGray is RGB 0xD3D3D3.
	ColorLightGray HexColor = 0xD3D3D3
	// ColorLightGreen is RGB 0x90EE90.
	ColorLightGreen HexColor = 0x90EE90
	// ColorLightPink is RGB 0xFFB6C1.
	ColorLightPink HexColor = 0xFFB6C1
	// ColorLightSalmon is RGB 0xFFA07A.
	ColorLightSalmon HexColor = 0xFFA07A
	// ColorLightSeaGreen is RGB 0x20B2AA.
	ColorLightSeaGreen HexColor = 0x20B2AA
	// ColorLightSkyBlue is RGB 0x87CEFA.
	ColorLightSkyBlue HexColor = 0x87CEFA
	// ColorLightSlateGray is RGB 0x778899.
	ColorLightSlateGray HexColor = 0x778899
	// ColorLightSteelBlue is RGB 0xB0C4DE.
	ColorLightSteelBlue HexColor = 0xB0C4DE
	// ColorLightYellow is RGB 0xFFFFE0.
	ColorLightYellow HexColor = 0xFFFFE0
	// ColorLime is RGB 0x00FF00.
	ColorLime HexColor = 0x00FF00
	// ColorLimeGreen is RGB 0x32CD32.
	ColorLimeGreen HexColor = 0x32CD32
	// ColorLinen is RGB 0xFAF0E6.
	ColorLinen HexColor = 0xFAF0E6
	// ColorMagenta is RGB 0xFF00FF.
	ColorMagenta HexColor = 0xFF00FF
	// ColorMaroon is RGB 0x800000.
	ColorMaroon HexColor = 0x800000
	// ColorMediumAquaMarine is RGB 0x66CDAA.
	ColorMediumAquaMarine HexColor = 0x66CDAA
	// ColorMediumBlue is RGB 0x0000CD.
	ColorMediumBlue HexColor = 0x0000CD
	// ColorMediumOrchid is RGB 0xBA55D3.
	ColorMediumOrchid HexColor = 0xBA55D3
	// ColorMediumPurple is RGB 0x9370DB.
	ColorMediumPurple HexColor = 0x9370DB
	// ColorMediumSeaGreen is RGB 0x3CB371.
	ColorMediumSeaGreen HexColor = 0x3CB371
	// ColorMediumSlateBlue is RGB 0x7B68EE.
	ColorMediumSlateBlue HexColor = 0x7B68EE
	// ColorMediumSpringGreen is RGB 0x00FA9A.
	ColorMediumSpringGreen HexColor = 0x00FA9A
	// ColorMediumTurquoise is RGB 0x48D1CC.
	ColorMediumTurquoise HexColor = 0x48D1CC
	// ColorMediumVioletRed is RGB 0xC71585.
	ColorMediumVioletRed HexColor = 0xC71585
	// ColorMidnightBlue is RGB 0x191970.
	ColorMidnightBlue HexColor = 0x191970
	// ColorMintCream is RGB 0xF5FFFA.
	ColorMintCream HexColor = 0xF5FFFA
	// ColorMistyRose is RGB 0xFFE4E1.
	ColorMistyRose HexColor = 0xFFE4E1
	// ColorMoccasin is RGB 0xFFE4B5.
	ColorMoccasin HexColor = 0xFFE4B5
	// ColorNavajoWhite is RGB 0xFFDEAD.
	ColorNavajoWhite HexColor = 0xFFDEAD
	// ColorNavy is RGB 0x000080.
	ColorNavy HexColor = 0x000080
	// ColorOldLace is RGB 0xFDF5E6.
	ColorOldLace HexColor = 0xFDF5E6
	// ColorOlive is RGB 0x808000.
	ColorOlive HexColor = 0x808000
	// ColorOliveDrab is RGB 0x6B8E23.
	ColorOliveDrab HexColor = 0x6B8E23
	// ColorOrange is RGB 0xFFA500.
	ColorOrange HexColor = 0xFFA500
	// ColorOrangeRed is RGB 0xFF4500.
	ColorOrangeRed HexColor = 0xFF4500
	// ColorOrchid is RGB 0xDA70D6.
	ColorOrchid HexColor = 0xDA70D6
	// ColorPaleGoldenRod is RGB 0xEEE8AA.
	ColorPaleGoldenRod HexColor = 0xEEE8AA
	// ColorPaleGreen is RGB 0x98FB98.
	ColorPaleGreen HexColor = 0x98FB98
	// ColorPaleTurquoise is RGB 0xAFEEEE.
	ColorPaleTurquoise HexColor = 0xAFEEEE
	// ColorPaleVioletRed is RGB 0xDB7093.
	ColorPaleVioletRed HexColor = 0xDB7093
	// ColorPapayaWhip is RGB 0xFFEFD5.
	ColorPapayaWhip HexColor = 0xFFEFD5
	// ColorPeachPuff is RGB 0xFFDAB9.
	ColorPeachPuff HexColor = 0xFFDAB9
	// ColorPeru is RGB 0xCD853F.
	ColorPeru HexColor = 0xCD853F
	// ColorPink is RGB 0xFFC0CB.
	ColorPink HexColor = 0xFFC0CB
	// ColorPlum is RGB 0xDDA0DD.
	ColorPlum HexColor = 0xDDA0DD
	// ColorPowderBlue is RGB 0xB0E0E6.
	ColorPowderBlue HexColor = 0xB0E0E6
	// ColorPurple is RGB 0x800080.
	ColorPurple HexColor = 0x800080
	// ColorRebeccaPurple is RGB 0x663399.
	ColorRebeccaPurple HexColor = 0x663399
	// ColorRed is RGB 0xFF0000.
	ColorRed HexColor = 0xFF0000
	// ColorRosyBrown is RGB 0xBC8F8F.
	ColorRosyBrown HexColor = 0xBC8F8F
	// ColorRoyalBlue is RGB 0x4169E1.
	ColorRoyalBlue HexColor = 0x4169E1
	// ColorSaddleBrown is RGB 0x8B4513.
	ColorSaddleBrown HexColor = 0x8B4513
	// ColorSalmon is RGB 0xFA8072.
	ColorSalmon HexColor = 0xFA8072
	// ColorSandyBrown is RGB 0xF4A460.
	ColorSandyBrown HexColor = 0xF4A460
	// ColorSeaGreen is RGB 0x2E8B57.
	ColorSeaGreen HexColor = 0x2E8B57
	// ColorSeaShell is RGB 0xFFF5EE.
	ColorSeaShell HexColor = 0xFFF5EE
	// ColorSienna is RGB 0xA0522D.
	ColorSienna HexColor = 0xA0522D
	// ColorSilver is RGB 0xC0C0C0.
	ColorSilver HexColor = 0xC0C0C0
	// ColorSkyBlue is RGB 0x87CEEB.
	ColorSkyBlue HexColor = 0x87CEEB
	// ColorSlateBlue is RGB 0x6A5ACD.
	ColorSlateBlue HexColor = 0x6A5ACD
	// ColorSlateGray is RGB 0x708090.
	ColorSlateGray HexColor = 0x708090
	// ColorSnow is RGB 0xFFFAFA.
	ColorSnow HexColor = 0xFFFAFA
	// ColorSpringGreen is RGB 0x00FF7F.
	ColorSpringGreen HexColor = 0x00FF7F
	// ColorSteelBlue is RGB 0x4682B4.
	ColorSteelBlue HexColor = 0x4682B4
	// ColorTan is RGB 0xD2B48C.
	ColorTan HexColor = 0xD2B48C
	// ColorTeal is RGB 0x008080.
	ColorTeal HexColor = 0x008080
	// ColorThistle is RGB 0xD8BFD8.
	ColorThistle HexColor = 0xD8BFD8
	// ColorTomato is RGB 0xFF6347.
	ColorTomato HexColor = 0xFF6347
	// ColorTurquoise is RGB 0x40E0D0.
	ColorTurquoise HexColor = 0x40E0D0
	// ColorViolet is RGB 0xEE82EE.
	ColorViolet HexColor = 0xEE82EE
	// ColorWheat is RGB 0xF5DEB3.
	ColorWheat HexColor = 0xF5DEB3
	// ColorWhite is RGB 0xFFFFFF.
	ColorWhite HexColor = 0xFFFFFF
	// ColorWhiteSmoke is RGB 0xF5F5F5.
	ColorWhiteSmoke HexColor = 0xF5F5F5
	// ColorYellow is RGB 0xFFFF00.
	ColorYellow HexColor = 0xFFFF00
	// ColorYellowGreen is RGB 0x9ACD32.
	ColorYellowGreen HexColor = 0x9ACD32

	// ColorBox2DRed is RGB 0xDC3132.
	ColorBox2DRed HexColor = 0xDC3132
	// ColorBox2DBlue is RGB 0x30AEBF.
	ColorBox2DBlue HexColor = 0x30AEBF
	// ColorBox2DGreen is RGB 0x8CC924.
	ColorBox2DGreen HexColor = 0x8CC924
	// ColorBox2DYellow is RGB 0xFFEE8C.
	ColorBox2DYellow HexColor = 0xFFEE8C
)

type Hull

type Hull struct {
	// Points holds the hull corners. Only the first Count entries are valid.
	Points [MaxPolygonVertices]Vec2

	// Count is the number of points.
	Count int
}

Hull is a convex hull. It feeds the polygon constructors. Build one with ComputeHull and do not modify it afterwards.

func ComputeHull

func ComputeHull(points []Vec2) Hull

ComputeHull returns the convex hull of a set of points. It welds points that are closer than four linear slops and it drops collinear points. It returns an empty hull on failure: fewer than three points, more than MaxPolygonVertices points, points all very close, or points all on a line.

type JointDef added in v1.1.0

type JointDef struct {
	// Application data attached to the joint.
	UserData any

	// The first attached body.
	BodyIdA BodyId

	// The second attached body.
	BodyIdB BodyId

	// The first local joint frame.
	LocalFrameA Transform

	// The second local joint frame.
	LocalFrameB Transform

	// Force threshold for joint events.
	ForceThreshold Q

	// Torque threshold for joint events.
	TorqueThreshold Q

	// Constraint stiffness in cycles per second (advanced).
	ConstraintHertz Q

	// Constraint damping ratio (advanced).
	ConstraintDampingRatio Q

	// Debug draw scale.
	DrawScale Q

	// Set this flag to true if the attached bodies should collide.
	CollideConnected bool
}

JointDef is the base definition of every joint type. The local frames are measured from the body origin rather than the center of mass because the center of mass may be unknown when the joint is made, and because adding or removing shapes would otherwise break the joint. It corresponds to b2JointDef.

type JointEvent added in v1.1.0

type JointEvent struct {
	// JointId is the joint.
	JointId JointId

	// UserData is the joint user data, for convenience.
	UserData any
}

JointEvent reports an awake joint whose force or torque exceeded its threshold. The observed force and torque are not returned. It corresponds to b2JointEvent.

type JointId

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

JointId identifies a joint. Its zero value is null.

func CreateDistanceJoint added in v0.3.0

func CreateDistanceJoint(worldId WorldId, def *DistanceJointDef) JointId

CreateDistanceJoint creates a distance joint. The definition must come from DefaultDistanceJointDef.

Example
worldId, groundId, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

// A rope of length two from the ground origin to the box center.
def := b2.DefaultDistanceJointDef()
def.Base.BodyIdA = groundId
def.Base.BodyIdB = boxId
def.Length = b2.QFromInt(2)
jointId := b2.CreateDistanceJoint(worldId, &def)

fmt.Println(jointId.IsNull())
Output:
false

func CreateFilterJoint added in v0.3.0

func CreateFilterJoint(worldId WorldId, def *FilterJointDef) JointId

CreateFilterJoint creates a filter joint. The joint only disables collision between the two bodies. The definition must come from DefaultFilterJointDef.

Example
worldId, groundId, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

// The box falls through the ground; the filter joint disables the
// collision between the two bodies.
def := b2.DefaultFilterJointDef()
def.Base.BodyIdA = groundId
def.Base.BodyIdB = boxId
jointId := b2.CreateFilterJoint(worldId, &def)

fmt.Println(jointId.IsNull())
Output:
false

func CreateMotorJoint added in v0.3.0

func CreateMotorJoint(worldId WorldId, def *MotorJointDef) JointId

CreateMotorJoint creates a motor joint. The definition must come from DefaultMotorJointDef. The angular velocity is in turns per second.

Example
worldId, groundId, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

// A linear spring pulls the box toward the point (1, 2) of the
// ground; the motor joint also replaces the removed mouse joint.
def := b2.DefaultMotorJointDef()
def.Base.BodyIdA = groundId
def.Base.BodyIdB = boxId
def.Base.LocalFrameA.P = b2.Vec2{X: b2.QOne(), Y: b2.QFromInt(2)}
def.LinearHertz = b2.QFromInt(5)
def.LinearDampingRatio = b2.QOne()
def.MaxSpringForce = b2.QFromInt(100)
jointId := b2.CreateMotorJoint(worldId, &def)

fmt.Println(jointId.IsNull())
Output:
false

func CreateMoverJoint added in v1.1.0

func CreateMoverJoint(worldId WorldId, def *MoverJointDef) JointId

CreateMoverJoint creates a mover joint. The definition must come from DefaultMoverJointDef.

func CreatePogoJoint added in v1.1.0

func CreatePogoJoint(worldId WorldId, def *PogoJointDef) JointId

CreatePogoJoint creates a pogo joint. The definition must come from DefaultPogoJointDef.

func CreatePrismaticJoint added in v0.3.0

func CreatePrismaticJoint(worldId WorldId, def *PrismaticJointDef) JointId

CreatePrismaticJoint creates a prismatic joint. The definition must come from DefaultPrismaticJointDef. The joint slides along the x-axis of LocalFrameA.

Example
worldId, groundId, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

// The box slides along the vertical axis of the ground, between
// zero and three units.
def := b2.DefaultPrismaticJointDef()
def.Base.BodyIdA = groundId
def.Base.BodyIdB = boxId
def.Base.LocalFrameA.Q = b2.MakeRot(b2.QMustParse("0.25"))
def.Base.LocalFrameB.Q = def.Base.LocalFrameA.Q
def.EnableLimit = true
def.LowerTranslation = b2.QZero()
def.UpperTranslation = b2.QFromInt(3)
jointId := b2.CreatePrismaticJoint(worldId, &def)

fmt.Println(jointId.IsNull())
Output:
false

func CreateRevoluteJoint added in v0.3.0

func CreateRevoluteJoint(worldId WorldId, def *RevoluteJointDef) JointId

CreateRevoluteJoint creates a revolute joint. The definition must come from DefaultRevoluteJointDef. The angles are in turns.

Example
worldId, groundId, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

// A pendulum: the pivot is the ground origin, two units below the
// box center. The angles are in turns; a quarter turn is 0.25.
def := b2.DefaultRevoluteJointDef()
def.Base.BodyIdA = groundId
def.Base.BodyIdB = boxId
def.Base.LocalFrameB.P = b2.Vec2{Y: b2.QFromInt(-2)}
def.EnableLimit = true
def.LowerAngle = b2.QMustParse("-0.25")
def.UpperAngle = b2.QMustParse("0.25")
jointId := b2.CreateRevoluteJoint(worldId, &def)

fmt.Println(jointId.IsNull())
Output:
false

func CreateWeldJoint added in v0.3.0

func CreateWeldJoint(worldId WorldId, def *WeldJointDef) JointId

CreateWeldJoint creates a weld joint. The definition must come from DefaultWeldJointDef.

Example
worldId, groundId, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

// A weld with a soft angular spring holds the box in place.
def := b2.DefaultWeldJointDef()
def.Base.BodyIdA = groundId
def.Base.BodyIdB = boxId
def.Base.LocalFrameB.P = b2.Vec2{Y: b2.QFromInt(-2)}
def.AngularHertz = b2.QFromInt(2)
def.AngularDampingRatio = b2.QHalf()
jointId := b2.CreateWeldJoint(worldId, &def)

fmt.Println(jointId.IsNull())
Output:
false

func CreateWheelJoint added in v0.3.0

func CreateWheelJoint(worldId WorldId, def *WheelJointDef) JointId

CreateWheelJoint creates a wheel joint. The definition must come from DefaultWheelJointDef. The wheel axis is the x-axis of LocalFrameA.

Example
worldId, groundId, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

// A suspension: the box rides the vertical axis on a spring and its
// motor spins it at one turn per second.
// The axis is the x-axis of frame A, turned a quarter turn up.
def := b2.DefaultWheelJointDef()
def.Base.BodyIdA = groundId
def.Base.BodyIdB = boxId
def.Base.LocalFrameA.Q = b2.MakeRot(b2.QMustParse("0.25"))
def.EnableMotor = true
def.MotorSpeed = b2.QOne()
def.MaxMotorTorque = b2.QFromInt(10)
jointId := b2.CreateWheelJoint(worldId, &def)

fmt.Println(jointId.IsNull())
Output:
false

func LoadJointId

func LoadJointId(x uint64) JointId

LoadJointId unpacks a joint id from a uint64.

func (JointId) EnableLimit added in v0.4.0

func (jointId JointId) EnableLimit(enableLimit bool)

EnableLimit enables or disables the limit on a distance, prismatic, revolute or wheel joint.

func (JointId) EnableMotor added in v0.4.0

func (jointId JointId) EnableMotor(enableMotor bool)

EnableMotor enables or disables the motor on a distance, prismatic, revolute or wheel joint.

func (JointId) EnableSpring added in v0.4.0

func (jointId JointId) EnableSpring(enableSpring bool)

EnableSpring enables or disables the spring on a distance, prismatic, revolute or wheel joint.

func (JointId) GetAngularDampingRatio added in v0.4.0

func (jointId JointId) GetAngularDampingRatio() Q

GetAngularDampingRatio reports the angular spring damping ratio.

func (JointId) GetAngularHertz added in v0.4.0

func (jointId JointId) GetAngularHertz() Q

GetAngularHertz reports the angular spring stiffness.

func (JointId) GetAngularSeparation added in v0.4.0

func (jointId JointId) GetAngularSeparation() Q

GetAngularSeparation reports angular separation in turns (b2Joint_GetAngularSeparation). As in the reference, the angle is the relative body rotation; the joint frames do not enter.

func (JointId) GetAngularVelocity added in v1.1.0

func (jointId JointId) GetAngularVelocity() Q

GetAngularVelocity reports the target angular velocity of a motor joint in turns per second.

func (JointId) GetBodyA added in v0.4.0

func (jointId JointId) GetBodyA() BodyId

GetBodyA reports the first attached body (b2Joint_GetBodyA).

func (JointId) GetBodyB added in v0.4.0

func (jointId JointId) GetBodyB() BodyId

GetBodyB reports the second attached body (b2Joint_GetBodyB).

func (JointId) GetCollideConnected added in v0.4.0

func (jointId JointId) GetCollideConnected() bool

GetCollideConnected reports whether the attached bodies collide (b2Joint_GetCollideConnected).

func (JointId) GetConstraintForce added in v0.4.0

func (jointId JointId) GetConstraintForce() Vec2

GetConstraintForce reports the constraint force from the last step (b2Joint_GetConstraintForce).

func (JointId) GetConstraintTorque added in v0.4.0

func (jointId JointId) GetConstraintTorque() Q

GetConstraintTorque reports the constraint torque from the last step (b2Joint_GetConstraintTorque).

func (JointId) GetConstraintTuning added in v0.4.0

func (jointId JointId) GetConstraintTuning() (hertz, dampingRatio Q)

GetConstraintTuning reports the joint constraint tuning (b2Joint_GetConstraintTuning).

func (JointId) GetCurrentAngle added in v1.1.0

func (jointId JointId) GetCurrentAngle() Q

GetCurrentAngle reports the angle of a revolute joint in turns: frame B relative to frame A.

func (JointId) GetCurrentLength added in v0.4.0

func (jointId JointId) GetCurrentLength() Q

GetCurrentLength reports the current length of a distance joint, or the length along the pogo axis of a pogo joint.

func (JointId) GetCurrentMotorForce added in v1.1.0

func (jointId JointId) GetCurrentMotorForce() Q

GetCurrentMotorForce reports the motor force of the last step on a distance or prismatic joint.

func (JointId) GetCurrentMotorTorque added in v1.1.0

func (jointId JointId) GetCurrentMotorTorque() Q

GetCurrentMotorTorque reports the motor torque of the last step on a revolute or wheel joint.

func (JointId) GetCurrentSpeed added in v1.1.0

func (jointId JointId) GetCurrentSpeed() Q

GetCurrentSpeed reports the joint speed: the angular speed in turns per second of a revolute joint, the translation speed of a prismatic joint or the spring velocity of a pogo joint.

func (JointId) GetCurrentTranslation added in v1.1.0

func (jointId JointId) GetCurrentTranslation() Q

GetCurrentTranslation reports the translation of a prismatic joint along the x-axis of its frame A.

func (JointId) GetForceThreshold added in v1.1.0

func (jointId JointId) GetForceThreshold() Q

GetForceThreshold reports the force that triggers a joint event (b2Joint_GetForceThreshold).

func (JointId) GetImpulse added in v1.1.0

func (jointId JointId) GetImpulse() Q

GetImpulse reports the spring impulse of a pogo joint in the last step.

func (JointId) GetLinearDampingRatio added in v0.4.0

func (jointId JointId) GetLinearDampingRatio() Q

GetLinearDampingRatio reports the linear spring damping ratio.

func (JointId) GetLinearHertz added in v0.4.0

func (jointId JointId) GetLinearHertz() Q

GetLinearHertz reports the linear spring stiffness.

func (JointId) GetLinearSeparation added in v0.4.0

func (jointId JointId) GetLinearSeparation() Q

GetLinearSeparation reports the joint's linear separation (b2Joint_GetLinearSeparation).

func (JointId) GetLinearVelocity added in v1.1.0

func (jointId JointId) GetLinearVelocity() Vec2

GetLinearVelocity reports the target linear velocity of a motor or mover joint.

func (JointId) GetLocalFrameA added in v1.1.0

func (jointId JointId) GetLocalFrameA() Transform

GetLocalFrameA reports the joint frame on body A (b2Joint_GetLocalFrameA).

func (JointId) GetLocalFrameB added in v1.1.0

func (jointId JointId) GetLocalFrameB() Transform

GetLocalFrameB reports the joint frame on body B (b2Joint_GetLocalFrameB).

func (JointId) GetLowerLimit added in v0.4.0

func (jointId JointId) GetLowerLimit() Q

GetLowerLimit reports the lower limit: a length, a translation or an angle in turns.

func (JointId) GetMaxMotorForce added in v0.4.0

func (jointId JointId) GetMaxMotorForce() Q

GetMaxMotorForce reports the maximum motor force.

func (JointId) GetMaxMotorTorque added in v0.4.0

func (jointId JointId) GetMaxMotorTorque() Q

GetMaxMotorTorque reports the maximum motor torque.

func (JointId) GetMaxSpringForce added in v1.1.0

func (jointId JointId) GetMaxSpringForce() Q

GetMaxSpringForce reports the maximum force of the motor joint linear spring.

func (JointId) GetMaxSpringTorque added in v1.1.0

func (jointId JointId) GetMaxSpringTorque() Q

GetMaxSpringTorque reports the maximum torque of the motor joint angular spring.

func (JointId) GetMaxVelocityForce added in v1.1.0

func (jointId JointId) GetMaxVelocityForce() Q

GetMaxVelocityForce reports the maximum force of the motor joint velocity constraint.

func (JointId) GetMaxVelocityTorque added in v1.1.0

func (jointId JointId) GetMaxVelocityTorque() Q

GetMaxVelocityTorque reports the maximum torque of the motor joint velocity constraint.

func (JointId) GetMoverMaxVelocityForce added in v1.1.0

func (jointId JointId) GetMoverMaxVelocityForce() Vec2

GetMoverMaxVelocityForce reports the per-axis maximum force of a mover joint (b2MoverJoint_GetMaxVelocityForce).

func (JointId) GetRestLength added in v1.1.0

func (jointId JointId) GetRestLength() Q

GetRestLength reports the rest length of a distance or pogo joint.

func (JointId) GetSpringDampingRatio added in v0.4.0

func (jointId JointId) GetSpringDampingRatio() Q

GetSpringDampingRatio reports the spring damping ratio.

func (JointId) GetSpringForce added in v1.1.0

func (jointId JointId) GetSpringForce() Q

GetSpringForce reports the spring force of a distance joint in the last step, or zero without a spring.

func (JointId) GetSpringForceRange added in v1.1.0

func (jointId JointId) GetSpringForceRange() (lowerForce, upperForce Q)

GetSpringForceRange reports the force range of a distance joint spring.

func (JointId) GetSpringHertz added in v0.4.0

func (jointId JointId) GetSpringHertz() Q

GetSpringHertz reports the spring stiffness in hertz.

func (JointId) GetTargetAngle added in v0.4.0

func (jointId JointId) GetTargetAngle() Q

GetTargetAngle reports the spring target of a revolute joint in turns.

func (JointId) GetTargetMotorSpeed added in v1.1.0

func (jointId JointId) GetTargetMotorSpeed() Q

GetTargetMotorSpeed reports the motor speed.

func (JointId) GetTargetTranslation added in v0.4.0

func (jointId JointId) GetTargetTranslation() Q

GetTargetTranslation reports the spring target of a prismatic joint.

func (JointId) GetTorqueThreshold added in v1.1.0

func (jointId JointId) GetTorqueThreshold() Q

GetTorqueThreshold reports the torque that triggers a joint event (b2Joint_GetTorqueThreshold).

func (JointId) GetType added in v0.4.0

func (jointId JointId) GetType() JointType

GetType reports the joint type (b2Joint_GetType).

func (JointId) GetUpperLimit added in v0.4.0

func (jointId JointId) GetUpperLimit() Q

GetUpperLimit reports the upper limit: a length, a translation or an angle in turns.

func (JointId) GetUserData added in v0.4.0

func (jointId JointId) GetUserData() any

GetUserData reports the data attached to the joint (b2Joint_GetUserData).

func (JointId) GetWorld added in v0.4.0

func (jointId JointId) GetWorld() WorldId

GetWorld reports the world containing the joint (b2Joint_GetWorld).

func (JointId) IsLimitEnabled added in v0.4.0

func (jointId JointId) IsLimitEnabled() bool

IsLimitEnabled reports whether the limit is enabled.

func (JointId) IsMotorEnabled added in v0.4.0

func (jointId JointId) IsMotorEnabled() bool

IsMotorEnabled reports whether the motor is enabled.

func (JointId) IsNull

func (id JointId) IsNull() bool

IsNull reports whether the id references nothing.

func (JointId) IsSpringEnabled added in v0.4.0

func (jointId JointId) IsSpringEnabled() bool

IsSpringEnabled reports whether the spring is enabled.

func (JointId) IsValid added in v0.4.0

func (jointId JointId) IsValid() bool

IsValid reports whether the id references a live joint (b2Joint_IsValid).

func (JointId) SetAngularDampingRatio added in v0.4.0

func (jointId JointId) SetAngularDampingRatio(dampingRatio Q)

SetAngularDampingRatio changes the angular spring damping ratio of a motor or weld joint.

func (JointId) SetAngularHertz added in v0.4.0

func (jointId JointId) SetAngularHertz(hertz Q)

SetAngularHertz changes the angular spring stiffness of a motor or weld joint.

func (JointId) SetAngularVelocity added in v1.1.0

func (jointId JointId) SetAngularVelocity(velocity Q)

SetAngularVelocity changes the target angular velocity of a motor joint in turns per second.

func (JointId) SetCollideConnected added in v0.4.0

func (jointId JointId) SetCollideConnected(shouldCollide bool)

SetCollideConnected changes whether the attached bodies collide (b2Joint_SetCollideConnected).

Example
worldId, groundId, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

def := b2.DefaultDistanceJointDef()
def.Base.BodyIdA = groundId
def.Base.BodyIdB = boxId
def.Length = b2.QFromInt(2)
jointId := b2.CreateDistanceJoint(worldId, &def)

jointId.SetCollideConnected(true)

fmt.Println(jointId.GetCollideConnected())
Output:
true

func (JointId) SetConstraintTuning added in v0.4.0

func (jointId JointId) SetConstraintTuning(hertz, dampingRatio Q)

SetConstraintTuning changes the joint constraint tuning (b2Joint_SetConstraintTuning).

func (JointId) SetForceThreshold added in v1.1.0

func (jointId JointId) SetForceThreshold(threshold Q)

SetForceThreshold changes the force that triggers a joint event (b2Joint_SetForceThreshold).

func (JointId) SetLimits added in v0.4.0

func (jointId JointId) SetLimits(lower, upper Q)

SetLimits changes the limits of a distance joint (the length range), a prismatic or wheel joint (the translation range) or a revolute joint (the angle range in turns, bounded to 0.495 turns).

func (JointId) SetLinearDampingRatio added in v0.4.0

func (jointId JointId) SetLinearDampingRatio(dampingRatio Q)

SetLinearDampingRatio changes the linear spring damping ratio of a motor or weld joint.

func (JointId) SetLinearHertz added in v0.4.0

func (jointId JointId) SetLinearHertz(hertz Q)

SetLinearHertz changes the linear spring stiffness of a motor or weld joint.

func (JointId) SetLinearVelocity added in v1.1.0

func (jointId JointId) SetLinearVelocity(velocity Vec2)

SetLinearVelocity changes the target linear velocity of a motor or mover joint.

func (JointId) SetLocalFrameA added in v1.1.0

func (jointId JointId) SetLocalFrameA(localFrame Transform)

SetLocalFrameA changes the joint frame on body A (b2Joint_SetLocalFrameA).

func (JointId) SetLocalFrameB added in v1.1.0

func (jointId JointId) SetLocalFrameB(localFrame Transform)

SetLocalFrameB changes the joint frame on body B (b2Joint_SetLocalFrameB).

func (JointId) SetMaxMotorForce added in v0.4.0

func (jointId JointId) SetMaxMotorForce(force Q)

SetMaxMotorForce changes the maximum motor force of a distance or prismatic joint.

func (JointId) SetMaxMotorTorque added in v0.4.0

func (jointId JointId) SetMaxMotorTorque(torque Q)

SetMaxMotorTorque changes the maximum motor torque of a revolute or wheel joint.

func (JointId) SetMaxSpringForce added in v1.1.0

func (jointId JointId) SetMaxSpringForce(maxForce Q)

SetMaxSpringForce changes the maximum force of the motor joint linear spring. A negative value counts as zero.

func (JointId) SetMaxSpringTorque added in v1.1.0

func (jointId JointId) SetMaxSpringTorque(maxTorque Q)

SetMaxSpringTorque changes the maximum torque of the motor joint angular spring. A negative value counts as zero.

func (JointId) SetMaxVelocityForce added in v1.1.0

func (jointId JointId) SetMaxVelocityForce(maxForce Q)

SetMaxVelocityForce changes the maximum force of the motor joint velocity constraint. The mover joint takes a per-axis vector: see SetMoverMaxVelocityForce.

func (JointId) SetMaxVelocityTorque added in v1.1.0

func (jointId JointId) SetMaxVelocityTorque(maxTorque Q)

SetMaxVelocityTorque changes the maximum torque of the motor joint velocity constraint.

func (JointId) SetMoverMaxVelocityForce added in v1.1.0

func (jointId JointId) SetMoverMaxVelocityForce(maxForce Vec2)

SetMoverMaxVelocityForce changes the per-axis maximum force of a mover joint (b2MoverJoint_SetMaxVelocityForce).

func (JointId) SetRestLength added in v1.1.0

func (jointId JointId) SetRestLength(length Q)

SetRestLength changes the rest length of a distance or pogo joint. The distance joint clamps it to [linearSlop, Huge] and restarts its impulses.

func (JointId) SetSpringDampingRatio added in v0.4.0

func (jointId JointId) SetSpringDampingRatio(dampingRatio Q)

SetSpringDampingRatio changes the spring damping ratio on a distance, pogo, prismatic, revolute or wheel joint.

func (JointId) SetSpringForceRange added in v1.1.0

func (jointId JointId) SetSpringForceRange(lowerForce, upperForce Q)

SetSpringForceRange changes the force range of a distance joint spring.

func (JointId) SetSpringHertz added in v0.4.0

func (jointId JointId) SetSpringHertz(hertz Q)

SetSpringHertz changes the spring stiffness in hertz on a distance, pogo, prismatic, revolute or wheel joint.

func (JointId) SetTargetAngle added in v0.4.0

func (jointId JointId) SetTargetAngle(angle Q)

SetTargetAngle changes the spring target of a revolute joint in turns. The create clamps it to half a turn; this setter does not, as in the reference.

func (JointId) SetTargetMotorSpeed added in v1.1.0

func (jointId JointId) SetTargetMotorSpeed(motorSpeed Q)

SetTargetMotorSpeed changes the motor speed: meters per second on a distance or prismatic joint, turns per second on a revolute or wheel joint.

func (JointId) SetTargetTranslation added in v0.4.0

func (jointId JointId) SetTargetTranslation(translation Q)

SetTargetTranslation changes the spring target of a prismatic joint.

func (JointId) SetTorqueThreshold added in v1.1.0

func (jointId JointId) SetTorqueThreshold(threshold Q)

SetTorqueThreshold changes the torque that triggers a joint event (b2Joint_SetTorqueThreshold).

func (JointId) SetUserData added in v0.4.0

func (jointId JointId) SetUserData(userData any)

SetUserData attaches application data to the joint (b2Joint_SetUserData).

func (JointId) WakeBodies added in v0.4.0

func (jointId JointId) WakeBodies()

WakeBodies wakes both bodies attached to the joint (b2Joint_WakeBodies).

type JointType added in v0.3.0

type JointType int

JointType selects the joint of a joint definition.

const (
	// DistanceJoint constrains the distance between two points.
	DistanceJoint JointType = iota
	// FilterJoint filters collision between two bodies.
	FilterJoint
	// MotorJoint fully controls the movement of a body.
	MotorJoint
	// MoverJoint controls the movement of the dynamic character mover.
	MoverJoint
	// PogoJoint is the ground interaction of the dynamic character mover.
	PogoJoint
	// PrismaticJoint slides along an axis.
	PrismaticJoint
	// RevoluteJoint rotates around a pivot.
	RevoluteJoint
	// WeldJoint brings two bodies together with some flex.
	WeldJoint
	// WheelJoint spins a wheel with a shock absorber.
	WheelJoint
)

Joint types. upstream b2JointType

type LocalManifold added in v1.1.0

type LocalManifold struct {
	// Normal is the unit normal in frame A. It points from A to B.
	Normal Vec2

	// Points holds the contact points. Two are possible in 2D.
	Points [2]LocalManifoldPoint

	// PointCount is zero, one or two.
	PointCount int
}

LocalManifold is the output of the collide functions, in the frame of shape A. It corresponds to b2LocalManifold in include/box2d/collision.h.

func CollideCapsuleAndCircle added in v0.2.0

func CollideCapsuleAndCircle(capsuleA *Capsule, circleB *Circle, xf Transform) LocalManifold

CollideCapsuleAndCircle computes the contact manifold of a capsule and a circle. It corresponds to b2CollideCapsuleAndCircle in src/manifold.c.

func CollideCapsules added in v0.2.0

func CollideCapsules(capsuleA *Capsule, capsuleB *Capsule, xf Transform) LocalManifold

CollideCapsules computes the contact manifold of two capsules. It follows Ericson 5.1.9 with clipping for a second contact point and corresponds to b2CollideCapsules in src/manifold.c.

func CollideChainSegmentAndCapsule added in v0.3.0

func CollideChainSegmentAndCapsule(segmentA *ChainSegment, capsuleB *Capsule, xf Transform, cache *SimplexCache) LocalManifold

CollideChainSegmentAndCapsule treats the capsule as a rounded polygon and defers to the polygon routine. It corresponds to b2CollideChainSegmentAndCapsule in src/manifold.c.

func CollideChainSegmentAndCircle added in v0.2.0

func CollideChainSegmentAndCircle(segmentA *ChainSegment, circleB *Circle, xf Transform) LocalManifold

CollideChainSegmentAndCircle computes the contact manifold of a one-sided chain segment and a circle. It corresponds to b2CollideChainSegmentAndCircle in src/manifold.c.

func CollideChainSegmentAndPolygon added in v0.3.0

func CollideChainSegmentAndPolygon(segmentA *ChainSegment, polygonB *Polygon, xf Transform, cache *SimplexCache) LocalManifold

CollideChainSegmentAndPolygon computes the manifold between a chain segment and a polygon. The cache warm starts the distance solver between calls. It corresponds to b2CollideChainSegmentAndPolygon in src/manifold.c.

func CollideCircles added in v0.2.0

func CollideCircles(circleA *Circle, circleB *Circle, xf Transform) LocalManifold

CollideCircles computes the contact manifold of two circles. It corresponds to b2CollideCircles in src/manifold.c.

func CollidePolygonAndCapsule added in v0.2.0

func CollidePolygonAndCapsule(polygonA *Polygon, capsuleB *Capsule, xf Transform) LocalManifold

CollidePolygonAndCapsule computes the contact manifold of a polygon and a capsule. It corresponds to b2CollidePolygonAndCapsule in src/manifold.c.

func CollidePolygonAndCircle added in v0.2.0

func CollidePolygonAndCircle(polygonA *Polygon, circleB *Circle, xf Transform) LocalManifold

CollidePolygonAndCircle computes the contact manifold of a polygon and a circle. It corresponds to b2CollidePolygonAndCircle in src/manifold.c.

func CollidePolygons added in v0.2.0

func CollidePolygons(polygonA *Polygon, polygonB *Polygon, xf Transform) LocalManifold

CollidePolygons computes the contact manifold of two rounded polygons with the separating axis test and edge clipping. It corresponds to b2CollidePolygons in src/manifold.c.

func CollideSegmentAndCapsule added in v0.2.0

func CollideSegmentAndCapsule(segmentA *Segment, capsuleB *Capsule, xf Transform) LocalManifold

CollideSegmentAndCapsule computes the contact manifold of a segment and a capsule. It corresponds to b2CollideSegmentAndCapsule in src/manifold.c.

func CollideSegmentAndCircle added in v0.2.0

func CollideSegmentAndCircle(segmentA *Segment, circleB *Circle, xf Transform) LocalManifold

CollideSegmentAndCircle computes the contact manifold of a segment and a circle. It corresponds to b2CollideSegmentAndCircle in src/manifold.c.

func CollideSegmentAndPolygon added in v0.2.0

func CollideSegmentAndPolygon(segmentA *Segment, polygonB *Polygon, xf Transform) LocalManifold

CollideSegmentAndPolygon computes the contact manifold of a segment and a polygon. It corresponds to b2CollideSegmentAndPolygon in src/manifold.c.

type LocalManifoldPoint added in v1.1.0

type LocalManifoldPoint struct {
	// Point is the contact point in frame A.
	Point Vec2

	// Separation is negative when the shapes penetrate.
	Separation Q

	// Id identifies the contact point between the two shapes.
	Id uint16
}

LocalManifoldPoint is one contact point of a LocalManifold. It corresponds to b2LocalManifoldPoint in include/box2d/collision.h.

type Manifold

type Manifold struct {
	// Normal is the unit normal in world space. It points from A to B.
	Normal Vec2

	// RollingImpulse is the angular impulse of the rolling resistance.
	RollingImpulse Q

	// Points holds the contact points. Two are possible in 2D.
	Points [2]ManifoldPoint

	// PointCount is zero, one or two.
	PointCount int
}

Manifold describes the contact points between two colliding shapes. The solver uses speculative collision, so a point may still be separated.

type ManifoldPoint

type ManifoldPoint struct {
	// AnchorA is the contact point relative to the center of mass of body A,
	// in world space.
	AnchorA Vec2

	// AnchorB is the contact point relative to the center of mass of body B,
	// in world space.
	AnchorB Vec2

	// Separation is negative when the shapes penetrate.
	Separation Q

	// NormalImpulse is the impulse along the manifold normal.
	NormalImpulse Q

	// TangentImpulse is the friction impulse.
	TangentImpulse Q

	// TotalNormalImpulse accumulates over the substeps and the restitution
	// pass. It tells a speculative point that acted from one that did not.
	TotalNormalImpulse Q

	// NormalVelocity is the relative normal velocity before the solve. It
	// feeds the hit events. A negative value means the shapes approach. It
	// is only computed for contacts with hit events or restitution.
	NormalVelocity Q

	// BaseSeparation is the separation cached for contact recycling.
	BaseSeparation Q

	// Id identifies the contact point between the two shapes.
	Id uint16

	// Persisted reports whether the point existed in the previous step.
	Persisted bool
}

ManifoldPoint is one contact point of a contact manifold. The solver uses speculative collision, so a point may still be separated.

type MassData

type MassData struct {
	// Mass is the mass of the shape, usually in kilograms.
	Mass Q

	// Center is the centroid of the shape, relative to the shape origin.
	Center Vec2

	// RotationalInertia is measured about the center of mass.
	RotationalInertia Q
}

MassData holds the mass properties of a shape.

func ComputeCapsuleMass

func ComputeCapsuleMass(shape *Capsule, density Q) MassData

ComputeCapsuleMass returns the mass properties of a capsule.

func ComputeCircleMass

func ComputeCircleMass(shape *Circle, density Q) MassData

ComputeCircleMass returns the mass properties of a circle.

func ComputePolygonMass

func ComputePolygonMass(shape *Polygon, density Q) MassData

ComputePolygonMass returns the mass properties of a convex polygon. It approximates a rounded polygon by pushing the vertices outward.

type Mat22

type Mat22 struct {
	Cx, Cy Vec2
}

Mat22 is a 2-by-2 matrix, stored as its columns.

func GetInverse22

func GetInverse22(m Mat22) Mat22

GetInverse22 returns the inverse of m. A singular matrix returns the zero matrix.

Each entry scales by the reciprocal of the determinant: a division in fixed mode and a product in float mode (D-006).

func Mat22Zero

func Mat22Zero() Mat22

Mat22Zero returns the zero matrix.

type MotionLocks added in v1.1.0

type MotionLocks struct {
	// Prevent translation along the x-axis.
	LinearX bool

	// Prevent translation along the y-axis.
	LinearY bool

	// Prevent rotation around the z-axis.
	AngularZ bool
}

MotionLocks restrict the body movement. It corresponds to b2MotionLocks.

type MotorJointDef added in v0.3.0

type MotorJointDef struct {
	// Base joint definition.
	Base JointDef

	// The desired linear velocity.
	LinearVelocity Vec2

	// The maximum velocity force in newtons.
	MaxVelocityForce Q

	// The desired angular velocity in turns per second.
	AngularVelocity Q

	// The maximum velocity torque in newton-meters.
	MaxVelocityTorque Q

	// Linear spring stiffness in cycles per second, for position control.
	LinearHertz Q

	// Linear spring damping ratio.
	LinearDampingRatio Q

	// Maximum spring force in newtons.
	MaxSpringForce Q

	// Angular spring stiffness in cycles per second, for position control.
	AngularHertz Q

	// Angular spring damping ratio.
	AngularDampingRatio Q

	// Maximum spring torque in newton-meters.
	MaxSpringTorque Q
	// contains filtered or unexported fields
}

MotorJointDef configures a motor joint: it controls the relative velocity and the relative transform of two bodies. With a velocity of zero it acts like top-down friction. Move local frame A to change the target transform. Initialize it with DefaultMotorJointDef.

func DefaultMotorJointDef added in v0.3.0

func DefaultMotorJointDef() MotorJointDef

DefaultMotorJointDef returns the default motor joint definition. Every setting starts at zero.

type MoverJointDef added in v1.1.0

type MoverJointDef struct {
	// Base joint definition.
	Base JointDef

	// The desired linear velocity.
	LinearVelocity Vec2

	// The maximum velocity force in newtons, per axis.
	MaxVelocityForce Vec2
	// contains filtered or unexported fields
}

MoverJointDef configures a mover joint: it moves a dynamic character mover through velocity commands. The x and y directions are handled separately. It does not affect rotation. Initialize it with DefaultMoverJointDef.

func DefaultMoverJointDef added in v1.1.0

func DefaultMoverJointDef() MoverJointDef

DefaultMoverJointDef returns the default mover joint definition.

type OverlapResultFcn added in v0.3.0

type OverlapResultFcn func(shapeId ShapeId) bool

OverlapResultFcn receives each shape that an overlap query finds. Return false to stop the walk of the current tree; the query goes on with the next body type, as the reference does. It corresponds to b2OverlapResultFcn in include/box2d/types.h; the closure carries the context.

type Plane

type Plane struct {
	Normal Vec2
	Offset Q
}

Plane separates space. The separation of a point is dot(normal, point) - offset.

type PlaneResult added in v0.4.0

type PlaneResult struct {
	Plane Plane
	Point Vec2
	Hit   bool
}

PlaneResult is the collision plane and contact point for a mover collision.

func CollideMoverAndCapsule added in v0.4.0

func CollideMoverAndCapsule(mover *Capsule, shape *Capsule) PlaneResult

CollideMoverAndCapsule ports b2CollideMoverAndCapsule.

func CollideMoverAndCircle added in v0.4.0

func CollideMoverAndCircle(mover *Capsule, shape *Circle) PlaneResult

CollideMoverAndCircle ports b2CollideMoverAndCircle.

func CollideMoverAndPolygon added in v0.4.0

func CollideMoverAndPolygon(mover *Capsule, shape *Polygon) PlaneResult

CollideMoverAndPolygon ports b2CollideMoverAndPolygon.

func CollideMoverAndSegment added in v0.4.0

func CollideMoverAndSegment(mover *Capsule, shape *Segment) PlaneResult

CollideMoverAndSegment ports b2CollideMoverAndSegment.

type PlaneResultFcn added in v0.4.0

type PlaneResultFcn func(shapeId ShapeId, result *PlaneResult) bool

PlaneResultFcn receives each collision plane a mover query finds. Return true to keep gathering planes. It corresponds to b2PlaneResultFcn in include/box2d/types.h; the closure carries the context.

type PlaneSolverResult added in v0.4.0

type PlaneSolverResult struct {
	Translation    Vec2
	IterationCount int
}

PlaneSolverResult is the translation and iteration count from SolvePlanes.

func SolvePlanes added in v0.4.0

func SolvePlanes(targetDelta Vec2, planes []CollisionPlane) PlaneSolverResult

SolvePlanes ports b2SolvePlanes. Pass Huge as PushLimit for a rigid plane.

Example
// A push limit of b2.Huge (the engine's rigid-contact bound) makes
// the plane act as an unyielding wall: the tangential component of the
// move survives untouched, and the normal component is pushed back
// to just outside the plane, leaving a linear-slop margin.
planes := []b2.CollisionPlane{{
	Plane:     b2.Plane{Normal: b2.Vec2{Y: b2.QOne()}},
	PushLimit: b2.Huge,
}}

result := b2.SolvePlanes(b2.Vec2{X: b2.QOne(), Y: b2.QOne().Neg()}, planes)

fmt.Println(result.Translation.X)
fmt.Println(result.Translation.Y.Less(b2.LinearSlop().Neg().Sub(b2.LinearSlop())))
Output:
1
false

type PogoJointDef added in v1.1.0

type PogoJointDef struct {
	// Base joint definition.
	Base JointDef

	// Normal vector at the contact.
	Normal Vec2

	// The spring stiffness in cycles per second.
	Hertz Q

	// The spring damping ratio, non-dimensional.
	DampingRatio Q

	// Spring length.
	RestLength Q

	// Maximum tension force. Controls how sticky the mover is to the
	// ground.
	MaxTensionForce Q

	// Maximum compression force. How hard the pogo pushes the mover up
	// from the ground.
	MaxCompressionForce Q

	// The initial internal impulse. The pogo is typically recreated every
	// frame; this moves the internal state forward for a smoother spring.
	Impulse Q

	// The initial internal velocity. The pogo is typically recreated every
	// frame; this moves the internal state forward for a smoother spring.
	Velocity Q
	// contains filtered or unexported fields
}

PogoJointDef configures a pogo joint: the ground spring of the dynamic character mover. Initialize it with DefaultPogoJointDef.

func DefaultPogoJointDef added in v1.1.0

func DefaultPogoJointDef() PogoJointDef

DefaultPogoJointDef returns the default pogo joint definition.

type Polygon

type Polygon struct {
	// Vertices holds the corners. Only the first Count entries are valid.
	Vertices [MaxPolygonVertices]Vec2

	// Normals holds the outward normal of each side.
	Normals [MaxPolygonVertices]Vec2

	// Centroid is the area centroid of the polygon.
	Centroid Vec2

	// Radius is the external radius of a rounded polygon.
	Radius Q

	// Count is the number of vertices.
	Count int
}

Polygon is a solid convex polygon. The interior lies to the left of every edge. Build one with MakePolygon or MakeBox; never fill the fields by hand.

func MakeBox

func MakeBox(halfWidth, halfHeight Q) Polygon

MakeBox returns a rectangle polygon of the given half-extents, without a hull. It panics on a half-extent that is not positive.

func MakeOffsetBox

func MakeOffsetBox(halfWidth, halfHeight Q, center Vec2, rotation Rot) Polygon

MakeOffsetBox returns a rectangle polygon placed at a center and a rotation, without a hull.

func MakeOffsetPolygon

func MakeOffsetPolygon(hull *Hull, position Vec2, rotation Rot) Polygon

MakeOffsetPolygon returns a convex polygon built from a hull and placed at a position and a rotation.

func MakeOffsetRoundedBox

func MakeOffsetRoundedBox(halfWidth, halfHeight Q, center Vec2, rotation Rot, radius Q) Polygon

MakeOffsetRoundedBox returns a rectangle polygon with rounded corners, placed at a center and a rotation, without a hull.

func MakeOffsetRoundedPolygon

func MakeOffsetRoundedPolygon(hull *Hull, position Vec2, rotation Rot, radius Q) Polygon

MakeOffsetRoundedPolygon returns a convex polygon built from a hull, placed at a position and a rotation, with rounded corners of the given radius.

func MakePolygon

func MakePolygon(hull *Hull, radius Q) Polygon

MakePolygon returns a convex polygon built from a hull. The radius rounds the corners. It panics on a hull that ValidateHull rejects.

func MakeRoundedBox

func MakeRoundedBox(halfWidth, halfHeight, radius Q) Polygon

MakeRoundedBox returns a rectangle polygon with rounded corners, without a hull.

func MakeSquare

func MakeSquare(halfWidth Q) Polygon

MakeSquare returns a square polygon of the given half-width, without a hull.

func TransformPolygon

func TransformPolygon(transform Transform, polygon *Polygon) Polygon

TransformPolygon returns the polygon moved by a transform. It moves a shape from one body to another.

type Pos added in v1.1.0

type Pos = Vec2

Pos is a world position. Box2D v3.2 keeps world positions in double precision under its large world option and in float otherwise; without the dbox2d_double tag a position is a Vec2 (decision M-06). It corresponds to b2Pos in include/box2d/math_types.h.

func LerpPos added in v1.1.0

func LerpPos(a, b Pos, t Q) Pos

LerpPos interpolates two world positions. It corresponds to b2LerpPos.

func OffsetPos added in v1.1.0

func OffsetPos(p Pos, d Vec2) Pos

OffsetPos returns p + d. It corresponds to b2OffsetPos.

func PosZero added in v1.1.0

func PosZero() Pos

PosZero returns the origin. It corresponds to b2Pos_zero.

func ToPos added in v1.1.0

func ToPos(v Vec2) Pos

ToPos converts a vector to a world position. It corresponds to b2ToPos.

func TransformWorldPoint added in v1.1.0

func TransformWorldPoint(t WorldTransform, p Vec2) Pos

TransformWorldPoint moves a local point into the world. It corresponds to b2TransformWorldPoint.

type PreContinuousFcn added in v1.1.0

type PreContinuousFcn func(shapeIdA, shapeIdB ShapeId, point Pos, normal Vec2) bool

PreContinuousFcn inspects a time of impact event of the continuous stage, with the world hit point and normal; return false to skip the event. It runs only for shapes with pre-solve events enabled. It corresponds to b2PreContinuousCallbackFcn and has the threading rules of PreSolveFcn.

type PreSolveFcn added in v0.4.0

type PreSolveFcn func(shapeIdA, shapeIdB ShapeId, manifold *Manifold)

PreSolveFcn inspects a contact manifold before the solver runs. It may edit the manifold; a point count of zero disables the contact this step. It corresponds to b2PreSolveCallbackFcn. With several workers it runs on worker goroutines while the step mutates the world: it must not call the world API or query it, must not panic, and must be safe to call concurrently.

type PrismaticJointDef added in v0.3.0

type PrismaticJointDef struct {
	// Base joint definition.
	Base JointDef

	// Enable a linear spring along the prismatic joint axis.
	EnableSpring bool

	// The spring stiffness in cycles per second.
	Hertz Q

	// The spring damping ratio, non-dimensional.
	DampingRatio Q

	// The target translation for the joint in meters. The spring-damper
	// drives toward this translation.
	TargetTranslation Q

	// Enable and disable the joint limit.
	EnableLimit bool

	// The lower translation limit.
	LowerTranslation Q

	// The upper translation limit.
	UpperTranslation Q

	// Enable and disable the joint motor.
	EnableMotor bool

	// The maximum motor force, usually in newtons.
	MaxMotorForce Q

	// The desired motor speed, usually in meters per second.
	MotorSpeed Q
	// contains filtered or unexported fields
}

PrismaticJointDef configures a prismatic joint: body B slides along the x-axis of local frame A and cannot rotate relative to body A. The translation is zero when the local frame origins coincide in world space. Initialize it with DefaultPrismaticJointDef.

func DefaultPrismaticJointDef added in v0.3.0

func DefaultPrismaticJointDef() PrismaticJointDef

DefaultPrismaticJointDef returns the default prismatic joint definition.

type Profile added in v0.5.0

type Profile struct {
	Step                float64
	Pairs               float64
	Collide             float64
	Solve               float64
	SolverSetup         float64
	Constraints         float64
	PrepareConstraints  float64
	IntegrateVelocities float64
	WarmStart           float64
	SolveImpulses       float64
	IntegratePositions  float64
	RelaxImpulses       float64
	Restitution         float64
	StoreImpulses       float64
	SplitIslands        float64
	Transforms          float64
	JointEvents         float64
	HitEvents           float64
	Refit               float64
	Bullets             float64
	SensorHits          float64
	SleepIslands        float64
	Sensors             float64
}

Profile holds the wall-clock cost of the last Step, in milliseconds.

type Q

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

Q is a float32 scalar. Only the constructors make one.

func AABBMargin

func AABBMargin() Q

AABBMargin is the largest margin that fattens the bounds in the dynamic tree, in meters. Each shape uses an eighth of its extent, up to this cap. A proxy that moves less than its margin triggers no tree adjustment.

Changing it has a significant effect on performance.

func ComputeAngularVelocity

func ComputeAngularVelocity(q1, q2 Rot, invH Q) Q

ComputeAngularVelocity returns the angular velocity, in turns per second, that rotates q1 into q2 over one step. invH is the inverse time step.

func Cross

func Cross(a, b Vec2) Q

Cross returns the 2D cross product, which is a scalar.

func Degrees added in v1.0.0

func Degrees[T Scalar](v T) Q

Degrees returns an angle given in degrees as the turns the API uses. An integer converts as the exact ratio over 360; a float divides in float64 first, which is one rounding for a constant.

func F added in v1.0.0

func F[T Scalar](v T) Q

F returns v as a scalar of the build mode. An integer converts exactly and a float rounds once, as QFromInt and QFromFloat64 do, so a constant gives the same bits on every architecture. A float computed at run time is only as portable as its computation; see QFromFloat64.

func JointConstraintDampingRatio

func JointConstraintDampingRatio() Q

JointConstraintDampingRatio is the default damping of a joint constraint.

func JointConstraintHertz

func JointConstraintHertz() Q

JointConstraintHertz is the default stiffness of a joint constraint.

func LinearSlop

func LinearSlop() Q

LinearSlop is the collision and constraint tolerance in meters. It is numerically significant and visually insignificant.

Changing it has a significant effect on stability.

func MaxRotation

func MaxRotation() Q

MaxRotation is the largest rotation of a body in one time step, in turns. The limit prevents numerical problems.

Raising it to 0.25 turns or more breaks continuous collision.

func Pi

func Pi() Q

Pi is the ratio of a circumference to its diameter. An angle is a turn in this package; Pi serves the formulas that the reference writes in radians.

func PlaneSeparation

func PlaneSeparation(plane Plane, point Vec2) Q

PlaneSeparation returns the signed distance of a point from a plane.

func QFromFloat64 added in v0.6.0

func QFromFloat64(f float64) Q

QFromFloat64 returns f rounded to the nearest float32. The rounding is the same on every architecture, so a constant converts to the same scalar everywhere. A float64 computed at run time is only as portable as its computation: Go fuses a multiply and an add into one rounding on arm64, and on amd64 with GOAMD64=v3. A decimal literal rounds to float64 first, so a long literal can differ from QMustParse in the last bit.

func QFromInt added in v0.5.0

func QFromInt(i int) Q

QFromInt returns the integer i as a scalar.

func QFromRatio added in v0.5.0

func QFromRatio(num, den int) Q

QFromRatio returns num/den, rounded to float32.

func QHalf added in v0.5.0

func QHalf() Q

QHalf returns one half.

func QMaxValue added in v0.5.0

func QMaxValue() Q

QMaxValue returns the largest finite float32 scalar.

func QMinValue added in v0.5.0

func QMinValue() Q

QMinValue returns the smallest finite float32 scalar.

func QMustParse added in v0.5.0

func QMustParse(s string) Q

QMustParse returns the decimal literal s as a scalar. It panics when s is not a decimal number.

func QOne added in v0.5.0

func QOne() Q

QOne returns one.

func QZero added in v0.5.0

func QZero() Q

QZero returns zero.

func RelativeAngle

func RelativeAngle(a, b Rot) Q

RelativeAngle returns the angle of b relative to a, b - a, in turns. The arguments follow b2RelativeAngle(a, b) of v3.2.

func RotGetAngle

func RotGetAngle(q Rot) Q

RotGetAngle returns the angle of q in turns, in the range [-0.5, 0.5].

func SpeculativeDistance

func SpeculativeDistance() Q

SpeculativeDistance is the range of limited speculative collision, in meters. It reduces jitter.

Changing it has a significant effect on performance and stability.

func SpringDamper

func SpringDamper(hertz, dampingRatio, position, velocity, timeStep Q) Q

SpringDamper simulates a one-dimensional mass-spring-damper and returns the new velocity. The caller then computes the new position:

position += timeStep * newVelocity

It drives towards a zero position. Implicit integration makes the solution stable and free of transcendental functions.

func TimeToSleep

func TimeToSleep() Q

TimeToSleep is how long a body must stay still before it sleeps, in seconds.

func UnwindAngle

func UnwindAngle(t Q) Q

UnwindAngle reduces an angle in turns to the range [-0.5, 0.5]. One turn is one unit here, so the reduction is exact and needs no remainder of pi.

func (Q) Abs added in v0.8.0

func (q Q) Abs() Q

Abs returns q with its sign bit cleared.

func (Q) Add added in v0.8.0

func (q Q) Add(o Q) Q

Add returns q+o.

func (Q) Clamp added in v0.8.0

func (q Q) Clamp(lo, hi Q) Q

Clamp returns q limited to [lo, hi].

func (Q) Cmp added in v0.8.0

func (q Q) Cmp(o Q) int

Cmp returns -1 when q < o, 0 when q == o, and 1 when q > o.

func (Q) Div added in v0.8.0

func (q Q) Div(o Q) Q

Div returns q/o. The conversion blocks fusion with a following add.

func (Q) Eq added in v0.8.0

func (q Q) Eq(o Q) bool

Eq reports whether q equals o.

func (Q) Greater added in v0.8.0

func (q Q) Greater(o Q) bool

Greater reports whether q is greater than o.

func (Q) Int added in v0.8.0

func (q Q) Int() int

Int returns q truncated toward zero.

func (Q) Less added in v0.8.0

func (q Q) Less(o Q) bool

Less reports whether q is less than o.

func (Q) Max added in v0.8.0

func (q Q) Max(o Q) Q

Max returns the larger of q and o.

func (Q) Min added in v0.8.0

func (q Q) Min(o Q) Q

Min returns the smaller of q and o.

func (Q) Mul added in v0.8.0

func (q Q) Mul(o Q) Q

Mul returns q*o. The conversion blocks fusion with a following add.

func (Q) Neg added in v0.8.0

func (q Q) Neg() Q

Neg returns -q.

func (Q) Round added in v0.8.0

func (q Q) Round() Q

Round returns the nearest integer, with halves away from zero.

func (Q) Sqrt added in v0.8.0

func (q Q) Sqrt() Q

func (Q) String added in v0.8.0

func (q Q) String() string

String returns q in the shortest float32 decimal form.

func (Q) Sub added in v0.8.0

func (q Q) Sub(o Q) Q

Sub returns q-o.

type QueryFilter

type QueryFilter struct {
	// The collision category bits of this query. Normally one bit.
	CategoryBits uint64

	// The shape categories that this query accepts for collision.
	MaskBits uint64
}

QueryFilter controls collision between a query and the shapes it visits.

func DefaultQueryFilter

func DefaultQueryFilter() QueryFilter

DefaultQueryFilter returns the default query filter: category 1, every mask bit set.

type RayCastInput

type RayCastInput struct {
	// Origin is the start point of the ray.
	Origin Vec2

	// Translation is the displacement of the ray.
	Translation Vec2

	// MaxFraction limits the translation to consider. It is usually one.
	MaxFraction Q
}

RayCastInput is the input of a ray cast in the local frame of a shape.

type RayResult added in v0.3.0

type RayResult struct {
	ShapeId    ShapeId
	Point      Pos
	Normal     Vec2
	Fraction   Q
	NodeVisits int
	LeafVisits int
	Hit        bool
}

RayResult is the answer of CastRayClosest. On an initial overlap the fraction and the normal are zero and the point is an arbitrary point of the overlap region. It corresponds to b2RayResult in include/box2d/types.h.

type Recording added in v1.1.0

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

Recording is a growable byte buffer that holds a recording. It corresponds to b2Recording.

func CreateRecording added in v1.1.0

func CreateRecording(byteCapacity int) *Recording

CreateRecording makes an empty recording buffer. The capacity is a hint. It corresponds to b2CreateRecording.

func CreateRecordingFromFile added in v1.1.0

func CreateRecordingFromFile(path string) *Recording

CreateRecordingFromFile loads a recording file, or returns nil. It corresponds to b2CreateRecordingFromFile.

func (*Recording) Data added in v1.1.0

func (r *Recording) Data() []byte

Data returns the recorded bytes. They stay valid until the next call that records or destroys. It corresponds to b2Recording_GetData.

func (*Recording) Destroy added in v1.1.0

func (r *Recording) Destroy()

Destroy releases the buffer. It corresponds to b2DestroyRecording.

func (*Recording) SaveToFile added in v1.1.0

func (r *Recording) SaveToFile(path string) bool

SaveToFile writes the recording to a file and reports success. It corresponds to b2Recording_SaveToFile.

func (*Recording) Size added in v1.1.0

func (r *Recording) Size() int

Size returns the number of recorded bytes. It corresponds to b2Recording_GetSize.

type Replay added in v1.1.0

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

Replay is an incremental player. It owns a private copy of the recording and drives the replay one step at a time. It corresponds to b2Replay.

func CreateReplay added in v1.1.0

func CreateReplay(data []byte, workerCount int) *Replay

CreateReplay opens a recording and creates the replay world from its seed snapshot. A workerCount of zero or less lets the replay world use the default. The recording bytes are copied. It returns nil when the recording is malformed or comes from another scalar mode. It corresponds to b2CreateReplay.

func (*Replay) Destroy added in v1.1.0

func (p *Replay) Destroy()

Destroy destroys the replay world and releases the player. It corresponds to b2DestroyReplay.

func (*Replay) DrawFrameQueries added in v1.1.0

func (p *Replay) DrawFrameQueries(draw *DebugDraw, queryIndex int)

DrawFrameQueries draws the spatial queries of the current frame through a debug draw. A queryIndex below zero draws every query, otherwise only that one, which is what a viewer does for the selected query. It corresponds to b2Replay_DrawFrameQueries.

func (*Replay) GetBodyCount added in v1.1.0

func (p *Replay) GetBodyCount() int

GetBodyCount returns the number of body slots of the outliner list. A destroyed body leaves a null slot. It corresponds to b2Replay_GetBodyCount.

func (*Replay) GetBodyId added in v1.1.0

func (p *Replay) GetBodyId(index int) BodyId

GetBodyId returns a body of the outliner list, or the null id. It corresponds to b2Replay_GetBodyId.

func (*Replay) GetDivergeFrame added in v1.1.0

func (p *Replay) GetDivergeFrame() int

GetDivergeFrame returns the first frame that diverged, or -1. It corresponds to b2Replay_GetDivergeFrame.

func (*Replay) GetFrame added in v1.1.0

func (p *Replay) GetFrame() int

GetFrame returns the number of steps dispatched so far. It corresponds to b2Replay_GetFrame.

func (*Replay) GetFrameQuery added in v1.1.0

func (p *Replay) GetFrameQuery(index int) ReplayQueryInfo

GetFrameQuery returns the description of a query of the current frame. It corresponds to b2Replay_GetFrameQuery.

func (*Replay) GetFrameQueryCount added in v1.1.0

func (p *Replay) GetFrameQueryCount() int

GetFrameQueryCount returns the number of queries of the current frame. It corresponds to b2Replay_GetFrameQueryCount.

func (*Replay) GetFrameQueryHit added in v1.1.0

func (p *Replay) GetFrameQueryHit(queryIndex, hitIndex int) ReplayQueryHit

GetFrameQueryHit returns one result of a query of the current frame. It corresponds to b2Replay_GetFrameQueryHit.

func (*Replay) GetInfo added in v1.1.0

func (p *Replay) GetInfo() ReplayInfo

GetInfo returns the metadata of the recording. It corresponds to b2Replay_GetInfo.

func (*Replay) GetKeyframeBudget added in v1.1.0

func (p *Replay) GetKeyframeBudget() int

GetKeyframeBudget returns the keyframe memory budget in bytes. It corresponds to b2Replay_GetKeyframeBudget.

func (*Replay) GetKeyframeBytes added in v1.1.0

func (p *Replay) GetKeyframeBytes() int

GetKeyframeBytes returns the bytes that the kept keyframes hold. It corresponds to b2Replay_GetKeyframeBytes.

func (*Replay) GetKeyframeInterval added in v1.1.0

func (p *Replay) GetKeyframeInterval() int

GetKeyframeInterval returns the current keyframe spacing, a power-of-two multiple of the minimum. It corresponds to b2Replay_GetKeyframeInterval.

func (*Replay) GetKeyframeMinInterval added in v1.1.0

func (p *Replay) GetKeyframeMinInterval() int

GetKeyframeMinInterval returns the finest keyframe spacing in frames. It corresponds to b2Replay_GetKeyframeMinInterval.

func (*Replay) GetWorldId added in v1.1.0

func (p *Replay) GetWorldId() WorldId

GetWorldId returns the replay world. It corresponds to b2Replay_GetWorldId.

func (*Replay) HasDiverged added in v1.1.0

func (p *Replay) HasDiverged() bool

HasDiverged reports whether a state hash or a query did not reproduce. It corresponds to b2Replay_HasDiverged.

func (*Replay) IsAtEnd added in v1.1.0

func (p *Replay) IsAtEnd() bool

IsAtEnd reports whether a StepFrame ran out of records. It corresponds to b2Replay_IsAtEnd.

func (*Replay) Restart added in v1.1.0

func (p *Replay) Restart()

Restart rewinds the replay to frame 0 in place. The world id stays stable. It corresponds to b2Replay_Restart.

func (*Replay) SeekFrame added in v1.1.0

func (p *Replay) SeekFrame(targetFrame int)

SeekFrame replays to the target frame, restoring the nearest keyframe first when that beats stepping. It corresponds to b2Replay_SeekFrame.

func (*Replay) SetKeyframePolicy added in v1.1.0

func (p *Replay) SetKeyframePolicy(budgetBytes int, minIntervalFrames int)

SetKeyframePolicy sets the memory budget in bytes and the finest spacing in frames of the keyframes. A value of zero or less keeps the current setting. It drops the captured keyframes. It corresponds to b2Replay_SetKeyframePolicy.

func (*Replay) StepFrame added in v1.1.0

func (p *Replay) StepFrame() bool

StepFrame advances the replay by one recorded step and the records that trail it, and reports whether a step ran. It corresponds to b2Replay_StepFrame.

type ReplayInfo added in v1.1.0

type ReplayInfo struct {
	// FrameCount is the number of recorded steps.
	FrameCount int

	// WorkerCount is the worker count of the replay world.
	WorkerCount int

	// TimeStep is the time step of the first recorded step.
	TimeStep Q

	// SubStepCount is the sub-step count of the first recorded step.
	SubStepCount int

	// LengthScale is the length units per meter in effect when recorded. The
	// port has one length unit, so a replay ignores it, see D-002.
	LengthScale float32

	// Bounds is the accumulated world bounds over the recording, zero-extent
	// if unavailable.
	Bounds AABB
}

ReplayInfo is the static metadata of a recording, resolved once when the player opens it. It corresponds to b2ReplayInfo.

type ReplayQueryHit added in v1.1.0

type ReplayQueryHit struct {
	ShapeId  ShapeId
	Point    Pos
	Normal   Vec2
	Fraction Q
}

ReplayQueryHit is one result of a recorded spatial query. It corresponds to b2ReplayQueryHit.

type ReplayQueryInfo added in v1.1.0

type ReplayQueryInfo struct {
	Type        ReplayQueryType
	Filter      QueryFilter
	AABB        AABB
	Origin      Pos
	Translation Vec2
	HitCount    int
}

ReplayQueryInfo describes a spatial query recorded during a replayed frame. It corresponds to b2ReplayQueryInfo.

type ReplayQueryType added in v1.1.0

type ReplayQueryType int

ReplayQueryType is the kind of a recorded spatial query. It corresponds to b2ReplayQueryType.

const (
	ReplayQueryOverlapAABB ReplayQueryType = iota
	ReplayQueryOverlapShape
	ReplayQueryCastRay
	ReplayQueryCastShape
	ReplayQueryCollideMover
	ReplayQueryCastRayClosest
	ReplayQueryCastMover
)

type RestitutionCallback added in v0.4.0

type RestitutionCallback func(restitutionA Q, userMaterialIdA uint64, restitutionB Q, userMaterialIdB uint64) Q

RestitutionCallback mixes the restitution values of two shapes.

type RevoluteJointDef added in v0.3.0

type RevoluteJointDef struct {
	// Base joint definition.
	Base JointDef

	// The target angle for the joint in turns. The spring-damper drives
	// toward this angle.
	TargetAngle Q

	// Enable a rotational spring on the revolute hinge axis.
	EnableSpring bool

	// The spring stiffness in cycles per second.
	Hertz Q

	// The spring damping ratio, non-dimensional.
	DampingRatio Q

	// Enable and disable the joint limit.
	EnableLimit bool

	// The lower angle for the joint limit in turns. Minimum of -0.495
	// turns.
	LowerAngle Q

	// The upper angle for the joint limit in turns. Maximum of 0.495
	// turns.
	UpperAngle Q

	// Enable and disable the joint motor.
	EnableMotor bool

	// The maximum motor torque, usually in newton-meters.
	MaxMotorTorque Q

	// The desired motor speed in turns per second.
	MotorSpeed Q
	// contains filtered or unexported fields
}

RevoluteJointDef configures a revolute joint: the origin of local frame B is fixed to the origin of local frame A, with free relative rotation. Initialize it with DefaultRevoluteJointDef.

func DefaultRevoluteJointDef added in v0.3.0

func DefaultRevoluteJointDef() RevoluteJointDef

DefaultRevoluteJointDef returns the default revolute joint definition.

type Rot

type Rot struct {
	Sin, Cos Q
}

Rot is a 2D rotation, stored as a sine and cosine pair.

func ComputeRotationBetweenUnitVectors

func ComputeRotationBetweenUnitVectors(v1, v2 Vec2) Rot

ComputeRotationBetweenUnitVectors returns the rotation that carries the unit vector v1 onto the unit vector v2. It panics when either vector is not a unit vector, because the result would be a rotation of the wrong scale.

func IntegrateRotation

func IntegrateRotation(q1 Rot, deltaAngle Q) Rot

IntegrateRotation advances q1 by the angular displacement deltaAngle, in turns, and renormalizes. The first-order step below needs radians, so the displacement scales by one turn.

func InvMulRot

func InvMulRot(q, r Rot) Rot

InvMulRot returns the rotation transpose(q) * r.

[ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc]
[-qs qc]   [rs  rc]   [-qs*rc+qc*rs qs*rs+qc*rc]
s(q - r) = qc * rs - qs * rc
c(q - r) = qc * rc + qs * rs

func InvertRot added in v1.1.0

func InvertRot(a Rot) Rot

InvertRot returns the inverse rotation. It corresponds to b2InvertRot.

func MakeRot

func MakeRot(t Q) Rot

MakeRot returns the rotation by the angle t, in turns.

func MakeRotFromUnitVector added in v1.1.0

func MakeRotFromUnitVector(unitVector Vec2) Rot

MakeRotFromUnitVector returns the rotation whose cosine and sine are the components of a unit vector. It corresponds to b2MakeRotFromUnitVector.

func MulRot

func MulRot(q, r Rot) Rot

MulRot returns the rotation q * r.

[qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc]
[qs  qc]   [rs  rc]   [qs*rc+qc*rs -qs*rs+qc*rc]
s(q + r) = qs * rc + qc * rs
c(q + r) = qc * rc - qs * rs

func NLerp

func NLerp(q1, q2 Rot, t Q) Rot

NLerp interpolates between q1 and q2 by t and renormalizes.

func NormalizeRot

func NormalizeRot(q Rot) Rot

NormalizeRot rescales q to unit length.

A zero q returns a zero rotation, as the reference does. The zero rotation is invalid, so IsValidRotation reports the bad state instead of hiding it behind the identity.

func RotIdentity

func RotIdentity() Rot

RotIdentity returns the rotation by zero turns.

func (Rot) Apply added in v0.8.0

func (r Rot) Apply(v Vec2) Vec2

Apply rotates the vector v by r.

func (Rot) Mul added in v0.8.0

func (r Rot) Mul(o Rot) Rot

Mul composes the rotations: the result rotates by r then by o.

func (Rot) Normalize added in v0.8.0

func (r Rot) Normalize() Rot

Normalize rescales r to unit length. A zero r returns a zero rotation.

type Scalar added in v1.0.0

type Scalar interface {
	int | int32 | int64 | float32 | float64 | Q
}

Scalar is what the short constructors accept: a Go integer or float, for a literal or a value the caller computed, and Q itself, so a value that is already on the scalar grid passes through unchanged.

type Segment

type Segment struct {
	Point1 Vec2
	Point2 Vec2
}

Segment is a line segment with two-sided collision.

type SegmentDistanceResult added in v0.2.0

type SegmentDistanceResult struct {
	// Closest1 is the closest point on the first segment.
	Closest1 Vec2

	// Closest2 is the closest point on the second segment.
	Closest2 Vec2

	// Fraction1 is the barycentric coordinate on the first segment.
	Fraction1 Q

	// Fraction2 is the barycentric coordinate on the second segment.
	Fraction2 Q

	// DistanceSquared is the squared distance between the closest points.
	DistanceSquared Q
}

SegmentDistanceResult is the output of SegmentDistance. It corresponds to b2SegmentDistanceResult in include/box2d/collision.h.

func ComputeSegmentDistance added in v1.1.0

func ComputeSegmentDistance(p1, q1, p2, q2 Vec2) SegmentDistanceResult

SegmentDistance computes the closest points of two line segments, clamping at the end points when needed. It follows Ericson 5.1.9 and corresponds to b2SegmentDistance in src/distance.c.

type SensorBeginTouchEvent added in v0.4.0

type SensorBeginTouchEvent struct {
	SensorShapeId, VisitorShapeId ShapeId
}

SensorBeginTouchEvent reports that a shape started to overlap a sensor. It corresponds to b2SensorBeginTouchEvent in include/box2d/types.h.

type SensorEndTouchEvent added in v0.4.0

type SensorEndTouchEvent struct {
	SensorShapeId, VisitorShapeId ShapeId
}

SensorEndTouchEvent reports that a shape stopped overlapping a sensor. It corresponds to b2SensorEndTouchEvent in include/box2d/types.h.

type SensorEvents added in v0.4.0

type SensorEvents struct {
	BeginEvents []SensorBeginTouchEvent
	EndEvents   []SensorEndTouchEvent
}

SensorEvents holds the sensor events of the last step. The slices stay valid until the next step. It corresponds to b2SensorEvents in include/box2d/types.h.

type ShapeCastInput

type ShapeCastInput struct {
	Proxy       ShapeProxy
	Translation Vec2

	// MaxFraction limits the translation to consider. It is usually one.
	MaxFraction Q

	// CanEncroach lets a cast that starts in contact advance. It applies
	// only when the radius is greater than zero.
	CanEncroach bool
}

ShapeCastInput is the input of a shape cast in generic form.

type ShapeCastPairInput added in v0.3.0

type ShapeCastPairInput struct {
	// ProxyA is the proxy of shape A.
	ProxyA ShapeProxy

	// ProxyB is the proxy of shape B.
	ProxyB ShapeProxy

	// Transform is the transform of shape B in the frame of shape A.
	Transform Transform

	// TranslationB is the translation of shape B, in frame A.
	TranslationB Vec2

	// MaxFraction is the fraction of the translation to consider. It is
	// usually one.
	MaxFraction Q

	// CanEncroach lets shapes with a radius move a little closer when
	// they already touch.
	CanEncroach bool
}

ShapeCastPairInput is the input of CastShape. It corresponds to b2ShapeCastPairInput in include/box2d/collision.h.

type ShapeDef

type ShapeDef struct {
	// Application data attached to the shape.
	UserData any

	// The surface material of this shape.
	Material SurfaceMaterial

	// The density, usually in kg/m^2. It stays out of the material because
	// it describes the interior, which may be hollow.
	Density Q

	// Collision filtering data.
	Filter Filter

	// Enable custom filtering. Only one of the two shapes needs to enable
	// it. See WorldId.SetCustomFilterCallback.
	EnableCustomFiltering bool

	// A sensor generates overlap events and never a collision response.
	IsSensor bool

	// Enable sensor events for this shape. False by default, even for
	// sensors.
	EnableSensorEvents bool

	// Enable contact events. Only for kinematic and dynamic bodies. Ignored
	// for sensors.
	EnableContactEvents bool

	// Enable hit events. Only for kinematic and dynamic bodies. Ignored for
	// sensors.
	EnableHitEvents bool

	// Enable pre-solve contact events. Only for dynamic bodies. Ignored for
	// sensors.
	EnablePreSolveEvents bool

	// A new shape scans the environment for collision on the next step. This
	// flag skips the scan on a static body, where the scan is the dominant
	// creation cost. Dynamic and kinematic shapes ignore the flag.
	InvokeContactCreation bool

	// Update the mass of the body when this shape is created. Default true.
	UpdateBodyMass bool
	// contains filtered or unexported fields
}

ShapeDef holds the data to create a shape. It is a temporary bundle of creation parameters; one definition may create many shapes. Initialize it with DefaultShapeDef.

func DefaultShapeDef

func DefaultShapeDef() ShapeDef

DefaultShapeDef returns the default shape definition.

type ShapeId

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

ShapeId identifies a shape. Its zero value is null.

func CreateCapsuleShape

func CreateCapsuleShape(bodyId BodyId, def *ShapeDef, capsule *Capsule) ShapeId

CreateCapsuleShape creates a capsule shape on a body. A capsule shorter than the linear slop is not created and the null ShapeId is returned.

func CreateChainSegmentShape added in v1.1.0

func CreateChainSegmentShape(bodyId BodyId, def *ShapeDef, chainSegment *ChainSegment) ShapeId

CreateChainSegmentShape creates a chain segment that has no parent chain. It panics on a degenerate segment. It corresponds to b2CreateChainSegmentShape.

func CreateCircleShape

func CreateCircleShape(bodyId BodyId, def *ShapeDef, circle *Circle) ShapeId

CreateCircleShape creates a circle shape on a body. The definition must come from DefaultShapeDef and is not retained.

func CreatePolygonShape

func CreatePolygonShape(bodyId BodyId, def *ShapeDef, polygon *Polygon) ShapeId

CreatePolygonShape creates a polygon shape on a body. Build the polygon with MakePolygon or MakeBox.

func CreateSegmentShape

func CreateSegmentShape(bodyId BodyId, def *ShapeDef, segment *Segment) ShapeId

CreateSegmentShape creates a segment shape on a body. It panics on a segment shorter than the linear slop.

func LoadShapeId

func LoadShapeId(x uint64) ShapeId

LoadShapeId unpacks a shape id from a uint64.

func (ShapeId) ApplyWind added in v1.1.0

func (shapeId ShapeId) ApplyWind(wind Vec2, drag, lift Q, wake bool)

ApplyWind applies a wind force to the body of the shape, using the density of air. It considers the projected area of the shape in the wind direction and the relative velocity of the shape. drag scales the force that opposes the relative velocity, lift the force perpendicular to it. Only circles, capsules and polygons on dynamic bodies feel the wind; a sleeping body feels it only when wake is set. It corresponds to b2Shape_ApplyWind.

func (ShapeId) AreContactEventsEnabled added in v0.4.0

func (shapeId ShapeId) AreContactEventsEnabled() bool

AreContactEventsEnabled reports whether contact events are enabled. It corresponds to b2Shape_AreContactEventsEnabled.

func (ShapeId) AreHitEventsEnabled added in v0.4.0

func (shapeId ShapeId) AreHitEventsEnabled() bool

AreHitEventsEnabled reports whether hit events are enabled. It corresponds to b2Shape_AreHitEventsEnabled.

func (ShapeId) ArePreSolveEventsEnabled added in v0.4.0

func (shapeId ShapeId) ArePreSolveEventsEnabled() bool

ArePreSolveEventsEnabled reports whether pre-solve events are enabled. It corresponds to b2Shape_ArePreSolveEventsEnabled.

func (ShapeId) AreSensorEventsEnabled added in v0.4.0

func (shapeId ShapeId) AreSensorEventsEnabled() bool

AreSensorEventsEnabled reports whether sensor events are enabled. It corresponds to b2Shape_AreSensorEventsEnabled.

func (ShapeId) CastRay added in v1.1.0

func (shapeId ShapeId) CastRay(origin Pos, translation Vec2) WorldCastOutput

CastRay casts a ray against the shape. The ray starts at origin and the translation is relative to it. The cast runs in the frame of the origin and the hit point is lifted back to a world position. It corresponds to b2Shape_CastRay.

func (ShapeId) ComputeMassData added in v1.1.0

func (shapeId ShapeId) ComputeMassData() MassData

ComputeMassData returns the shape mass, centroid and rotational inertia. It corresponds to b2Shape_ComputeMassData.

func (ShapeId) EnableContactEvents added in v0.4.0

func (shapeId ShapeId) EnableContactEvents(flag bool)

EnableContactEvents enables contact events on the shape. It corresponds to b2Shape_EnableContactEvents.

func (ShapeId) EnableHitEvents added in v0.4.0

func (shapeId ShapeId) EnableHitEvents(flag bool)

EnableHitEvents enables hit events on the shape. It corresponds to b2Shape_EnableHitEvents.

func (ShapeId) EnablePreSolveEvents added in v0.4.0

func (shapeId ShapeId) EnablePreSolveEvents(flag bool)

EnablePreSolveEvents enables pre-solve events on the shape. It corresponds to b2Shape_EnablePreSolveEvents.

func (ShapeId) EnableSensorEvents added in v0.4.0

func (shapeId ShapeId) EnableSensorEvents(flag bool)

EnableSensorEvents enables sensor events on the shape. It corresponds to b2Shape_EnableSensorEvents.

func (ShapeId) GetBody added in v0.4.0

func (shapeId ShapeId) GetBody() BodyId

GetBody returns the body that owns the shape. It corresponds to b2Shape_GetBody.

func (ShapeId) GetBounds added in v1.1.0

func (shapeId ShapeId) GetBounds() AABB

GetBounds returns the shape's current axis-aligned bounds. It corresponds to b2Shape_GetBounds.

func (ShapeId) GetCapsule added in v0.4.0

func (shapeId ShapeId) GetCapsule() Capsule

GetCapsule returns the capsule geometry. It corresponds to b2Shape_GetCapsule.

func (ShapeId) GetChainSegment added in v0.4.0

func (shapeId ShapeId) GetChainSegment() ChainSegment

GetChainSegment returns the chain segment geometry. It corresponds to b2Shape_GetChainSegment.

func (ShapeId) GetCircle added in v0.4.0

func (shapeId ShapeId) GetCircle() Circle

GetCircle returns the circle geometry. It corresponds to b2Shape_GetCircle.

func (ShapeId) GetClosestPoint added in v0.4.0

func (shapeId ShapeId) GetClosestPoint(target Pos) Pos

GetClosestPoint returns the closest point on the shape to a world target. It corresponds to b2Shape_GetClosestPoint.

func (ShapeId) GetContactCapacity added in v0.4.0

func (shapeId ShapeId) GetContactCapacity() int

GetContactCapacity returns the shape's conservative contact capacity. It corresponds to b2Shape_GetContactCapacity.

func (ShapeId) GetContactData added in v0.4.0

func (shapeId ShapeId) GetContactData(data []ContactData) int

GetContactData fills touching contact data in body-list order. It corresponds to b2Shape_GetContactData.

func (ShapeId) GetDensity added in v0.4.0

func (shapeId ShapeId) GetDensity() Q

GetDensity returns the shape density. It corresponds to b2Shape_GetDensity.

func (ShapeId) GetFilter added in v0.4.0

func (shapeId ShapeId) GetFilter() Filter

GetFilter returns the shape collision filter. It corresponds to b2Shape_GetFilter.

func (ShapeId) GetFriction added in v0.4.0

func (shapeId ShapeId) GetFriction() Q

GetFriction returns the shape friction. It corresponds to b2Shape_GetFriction.

func (ShapeId) GetParentChain added in v0.4.0

func (shapeId ShapeId) GetParentChain() ChainId

GetParentChain returns the chain that owns the shape. It corresponds to b2Shape_GetParentChain.

func (ShapeId) GetPolygon added in v0.4.0

func (shapeId ShapeId) GetPolygon() Polygon

GetPolygon returns the polygon geometry. It corresponds to b2Shape_GetPolygon.

func (ShapeId) GetRestitution added in v0.4.0

func (shapeId ShapeId) GetRestitution() Q

GetRestitution returns the shape restitution. It corresponds to b2Shape_GetRestitution.

func (ShapeId) GetSegment added in v0.4.0

func (shapeId ShapeId) GetSegment() Segment

GetSegment returns the segment geometry. It corresponds to b2Shape_GetSegment.

func (ShapeId) GetSensorCapacity added in v0.4.0

func (shapeId ShapeId) GetSensorCapacity() int

GetSensorCapacity returns the number of current sensor overlaps. It corresponds to b2Shape_GetSensorCapacity in src/shape.c.

func (ShapeId) GetSensorData added in v1.1.0

func (shapeId ShapeId) GetSensorData(overlaps []ShapeId) int

GetSensorData fills overlaps with the current sensor overlaps. It corresponds to b2Shape_GetSensorData in src/shape.c.

func (ShapeId) GetSurfaceMaterial added in v0.4.0

func (shapeId ShapeId) GetSurfaceMaterial() SurfaceMaterial

GetSurfaceMaterial returns the shape surface material. It corresponds to b2Shape_GetSurfaceMaterial.

func (ShapeId) GetType added in v0.4.0

func (shapeId ShapeId) GetType() ShapeType

GetType returns the shape geometry type. It corresponds to b2Shape_GetType.

func (ShapeId) GetUserData added in v0.4.0

func (shapeId ShapeId) GetUserData() any

GetUserData returns the data attached to the shape. It corresponds to b2Shape_GetUserData.

func (ShapeId) GetUserMaterial added in v1.1.0

func (shapeId ShapeId) GetUserMaterial() uint64

GetUserMaterial returns the shape user material id. It corresponds to b2Shape_GetUserMaterial.

func (ShapeId) GetWorld added in v0.4.0

func (shapeId ShapeId) GetWorld() WorldId

GetWorld returns the world containing the shape. It corresponds to b2Shape_GetWorld.

func (ShapeId) IsNull

func (id ShapeId) IsNull() bool

IsNull reports whether the id references nothing.

func (ShapeId) IsSensor added in v0.4.0

func (shapeId ShapeId) IsSensor() bool

IsSensor reports whether the shape is a sensor. It corresponds to b2Shape_IsSensor.

func (ShapeId) IsValid

func (id ShapeId) IsValid() bool

IsValid reports whether the id references a live shape.

func (ShapeId) SetCapsule added in v0.4.0

func (shapeId ShapeId) SetCapsule(capsule *Capsule)

SetCapsule replaces the shape geometry with a capsule. It corresponds to b2Shape_SetCapsule.

func (ShapeId) SetChainSegment added in v1.1.0

func (shapeId ShapeId) SetChainSegment(chainSegment *ChainSegment)

SetChainSegment replaces the shape geometry with a chain segment that has no parent chain. A segment owned by a chain cannot change, and a degenerate segment is ignored. It corresponds to b2Shape_SetChainSegment.

func (ShapeId) SetCircle added in v0.4.0

func (shapeId ShapeId) SetCircle(circle *Circle)

SetCircle replaces the shape geometry with a circle. It corresponds to b2Shape_SetCircle.

func (ShapeId) SetDensity added in v0.4.0

func (shapeId ShapeId) SetDensity(density Q, updateBodyMass bool)

SetDensity changes the shape density and optionally updates body mass. It corresponds to b2Shape_SetDensity.

func (ShapeId) SetFilter added in v0.4.0

func (shapeId ShapeId) SetFilter(filter Filter)

SetFilter changes the shape collision filter. It corresponds to b2Shape_SetFilter.

func (ShapeId) SetFriction added in v0.4.0

func (shapeId ShapeId) SetFriction(friction Q)

SetFriction changes the shape friction. It corresponds to b2Shape_SetFriction.

func (ShapeId) SetPolygon added in v0.4.0

func (shapeId ShapeId) SetPolygon(polygon *Polygon)

SetPolygon replaces the shape geometry with a polygon. It corresponds to b2Shape_SetPolygon.

func (ShapeId) SetRestitution added in v0.4.0

func (shapeId ShapeId) SetRestitution(restitution Q)

SetRestitution changes the shape restitution. It corresponds to b2Shape_SetRestitution.

func (ShapeId) SetSegment added in v0.4.0

func (shapeId ShapeId) SetSegment(segment *Segment)

SetSegment replaces the shape geometry with a segment. It corresponds to b2Shape_SetSegment.

func (ShapeId) SetSurfaceMaterial added in v0.4.0

func (shapeId ShapeId) SetSurfaceMaterial(material SurfaceMaterial)

SetSurfaceMaterial changes the shape surface material. It corresponds to b2Shape_SetSurfaceMaterial.

func (ShapeId) SetUserData added in v0.4.0

func (shapeId ShapeId) SetUserData(userData any)

SetUserData attaches application data to the shape. It corresponds to b2Shape_SetUserData.

func (ShapeId) SetUserMaterial added in v1.1.0

func (shapeId ShapeId) SetUserMaterial(material uint64)

SetUserMaterial sets the shape user material id. It corresponds to b2Shape_SetUserMaterial.

func (ShapeId) TestPoint added in v0.4.0

func (shapeId ShapeId) TestPoint(point Pos) bool

TestPoint reports whether a world point lies within the shape. It corresponds to b2Shape_TestPoint.

type ShapeProxy

type ShapeProxy struct {
	// Points holds the cloud. Only the first Count entries are valid.
	Points [MaxPolygonVertices]Vec2

	// Count is the number of points. It is greater than zero.
	Count int

	// Radius is the external radius of the cloud. It may be zero.
	Radius Q
}

ShapeProxy is a point cloud with an external radius. It stands for any shape in the distance and cast routines.

func MakeOffsetProxy added in v0.3.0

func MakeOffsetProxy(points []Vec2, radius Q, position Vec2, rotation Rot) ShapeProxy

MakeOffsetProxy makes a proxy with the points transformed by a position and a rotation. The slice replaces the pointer and count pair of b2MakeOffsetProxy in src/distance.c.

func MakeProxy added in v0.2.0

func MakeProxy(points []Vec2, radius Q) ShapeProxy

MakeProxy makes a proxy for the overlap and distance routines. The slice replaces the pointer and count pair of b2MakeProxy in src/distance.c; extra points beyond the polygon limit do not enter.

type ShapeType

type ShapeType int

ShapeType identifies the geometry of a shape.

const (
	// CircleShape is a circle with an offset.
	CircleShape ShapeType = iota

	// CapsuleShape is an extruded circle.
	CapsuleShape

	// SegmentShape is a line segment.
	SegmentShape

	// PolygonShape is a convex polygon.
	PolygonShape

	// ChainSegmentShape is a line segment owned by a chain shape.
	ChainSegmentShape

	// ShapeTypeCount is the number of shape types.
	ShapeTypeCount
)

type Simplex added in v0.3.0

type Simplex struct {
	// V1, V2 and V3 are the vertices.
	V1, V2, V3 SimplexVertex

	// Count is the number of valid vertices.
	Count int
}

Simplex is the simplex of the GJK algorithm. It corresponds to b2Simplex in include/box2d/collision.h.

type SimplexCache added in v0.2.0

type SimplexCache struct {
	// Count is the number of stored simplex vertices.
	Count uint16

	// IndexA holds the vertices of shape A on the simplex.
	IndexA [3]uint8

	// IndexB holds the vertices of shape B on the simplex.
	IndexB [3]uint8
}

SimplexCache warm starts the distance solver between two calls. The zero value is an empty cache; ShapeDistance fills it. It corresponds to b2SimplexCache in include/box2d/collision.h.

type SimplexVertex added in v0.3.0

type SimplexVertex struct {
	// WA is the support point in proxy A.
	WA Vec2

	// WB is the support point in proxy B.
	WB Vec2

	// W is wA - wB.
	W Vec2

	// A is the barycentric coordinate of the closest point.
	A Q

	// IndexA is the index of WA.
	IndexA int

	// IndexB is the index of WB.
	IndexB int
}

SimplexVertex is a vertex of the GJK simplex, kept for debugging. It corresponds to b2SimplexVertex in include/box2d/collision.h.

type SurfaceMaterial

type SurfaceMaterial struct {
	// The Coulomb friction coefficient, usually in the range [0, 1].
	Friction Q

	// The coefficient of restitution, usually in the range [0, 1].
	Restitution Q

	// The rolling resistance, usually in the range [0, 1].
	RollingResistance Q

	// The tangent speed, for conveyor belts.
	TangentSpeed Q

	// Application material identifier, returned with query results. The
	// world does not use it.
	UserMaterialId uint64

	// Custom debug draw color.
	CustomColor uint32
}

SurfaceMaterial holds the surface properties of a shape.

func DefaultSurfaceMaterial

func DefaultSurfaceMaterial() SurfaceMaterial

DefaultSurfaceMaterial returns the default material: friction 0.6.

type Sweep added in v0.3.0

type Sweep struct {
	// LocalCenter is the local center of mass.
	LocalCenter Vec2

	// C1 is the starting world center of mass.
	C1 Vec2

	// C2 is the ending world center of mass.
	C2 Vec2

	// Q1 is the starting world rotation.
	Q1 Rot

	// Q2 is the ending world rotation.
	Q2 Rot
}

Sweep describes the motion of a body for the time of impact. Shapes are defined about the body origin, which may differ from the center of mass, so the sweep interpolates the center of mass. It corresponds to b2Sweep in include/box2d/collision.h.

type TOIInput added in v0.3.0

type TOIInput struct {
	// ProxyA is the proxy for shape A.
	ProxyA ShapeProxy

	// ProxyB is the proxy for shape B.
	ProxyB ShapeProxy

	// SweepA is the movement of shape A.
	SweepA Sweep

	// SweepB is the movement of shape B.
	SweepB Sweep

	// MaxFraction defines the sweep interval [0, MaxFraction].
	MaxFraction Q
}

TOIInput is the input of TimeOfImpact. It corresponds to b2TOIInput in include/box2d/collision.h.

type TOIOutput added in v0.3.0

type TOIOutput struct {
	// State is the type of result.
	State TOIState

	// Point is the hit point.
	Point Vec2

	// Normal is the hit normal.
	Normal Vec2

	// Fraction is the sweep time of the collision.
	Fraction Q
}

TOIOutput is the output of ComputeTimeOfImpact. It corresponds to b2TOIOutput in include/box2d/collision.h.

func ComputeTimeOfImpact added in v1.1.0

func ComputeTimeOfImpact(input *TOIInput) TOIOutput

ComputeTimeOfImpact computes the largest fraction of the sweeps at which the two proxies stay separated by the target. It uses the local separating axis method, so it may miss some intermediate, non-tunneling collisions. The reference counters under B2_SNOOP_TOI_COUNTERS are not ported. It corresponds to b2ComputeTimeOfImpact in src/distance.c.

type TOIState added in v0.3.0

type TOIState int

TOIState describes the result of TimeOfImpact. It corresponds to b2TOIState in include/box2d/collision.h.

const (
	// TOIStateUnknown means the solver did not reach a conclusion.
	TOIStateUnknown TOIState = iota

	// TOIStateFailed means the root finder ran out of iterations.
	TOIStateFailed

	// TOIStateOverlapped means the shapes overlap at the start.
	TOIStateOverlapped

	// TOIStateHit means the shapes touch at the fraction.
	TOIStateHit

	// TOIStateSeparated means the shapes stay apart over the whole interval.
	TOIStateSeparated
)

type Transform

type Transform struct {
	P Vec2
	Q Rot
}

Transform is a 2D rigid transform.

func GetSweepTransform added in v0.3.0

func GetSweepTransform(sweep *Sweep, time Q) Transform

GetSweepTransform evaluates the sweep at a time in [0, 1]. It corresponds to b2GetSweepTransform in src/distance.c.

func InvMulTransforms

func InvMulTransforms(a, b Transform) Transform

InvMulTransforms returns the transform that converts a point local to frame b into a point local to frame a.

v2 = inv(a.q) * (b.q * v1 + b.p - a.p)
   = inv(a.q) * b.q * v1 + inv(a.q) * (b.p - a.p)

func InvMulWorldTransforms added in v1.1.0

func InvMulWorldTransforms(a, b WorldTransform) Transform

InvMulWorldTransforms returns frame B relative to frame A. It corresponds to b2InvMulWorldTransforms.

func MulTransforms

func MulTransforms(a, b Transform) Transform

MulTransforms composes two transforms. Applied to a point local to frame b, the result converts it to a point local to frame a, then to a point in the world frame.

v2 = a.q.Rot(b.q.Rot(v1) + b.p) + a.p
   = (a.q * b.q).Rot(v1) + a.q.Rot(b.p) + a.p

func ToRelativeTransform added in v1.1.0

func ToRelativeTransform(t WorldTransform, base Pos) Transform

ToRelativeTransform shifts a world transform into the frame of a base position. It corresponds to b2ToRelativeTransform.

func TransformIdentity

func TransformIdentity() Transform

TransformIdentity returns the transform that moves and rotates nothing.

type TreeBoxCastCallbackFcn added in v1.1.0

type TreeBoxCastCallbackFcn func(input *BoxCastInput, proxyId int, userData uint64) Q

TreeBoxCastCallbackFcn receives each proxy the swept box may reach. It returns zero to stop the cast, a value below input.MaxFraction to clip the cast, or input.MaxFraction to continue without clipping. It corresponds to b2TreeBoxCastCallbackFcn in include/box2d/collision.h. D-014 applies.

type TreeQueryCallbackFcn added in v0.7.0

type TreeQueryCallbackFcn func(proxyId int, userData uint64) bool

TreeQueryCallbackFcn receives each proxy that overlaps the query box. It returns false to stop the query. It corresponds to b2TreeQueryCallbackFcn in include/box2d/collision.h. D-014: a closure replaces the context pointer.

type TreeRayCastCallbackFcn added in v0.7.0

type TreeRayCastCallbackFcn func(input *RayCastInput, proxyId int, userData uint64) Q

TreeRayCastCallbackFcn receives each proxy whose box the ray reaches. It returns zero to stop the cast, a fraction in (0, maxFraction] to clip the ray, or any other value to continue unchanged. It corresponds to b2TreeRayCastCallbackFcn in include/box2d/collision.h. D-014 applies.

type TreeStats added in v0.3.0

type TreeStats struct {
	// NodeVisits counts every node the walk touched.
	NodeVisits int

	// LeafVisits counts the leaves the walk tested.
	LeafVisits int
}

TreeStats counts the nodes a world query visited. It corresponds to b2TreeStats in include/box2d/collision.h.

type Vec2

type Vec2 struct {
	X, Y Q
}

Vec2 is a 2D vector. It represents a point or a free vector.

func AABBCenter

func AABBCenter(a AABB) Vec2

AABBCenter returns the center of a.

func AABBExtents

func AABBExtents(a AABB) Vec2

AABBExtents returns the half-widths of a.

func Abs

func Abs(a Vec2) Vec2

Abs returns the component-wise absolute value of a.

func Clamp

func Clamp(v, a, b Vec2) Vec2

Clamp returns v limited component-wise to the box [a, b].

func ClipVector added in v0.4.0

func ClipVector(vector Vec2, planes []CollisionPlane) Vec2

ClipVector ports b2ClipVector.

func CrossSV

func CrossSV(s Q, v Vec2) Vec2

CrossSV returns the cross product of a scalar and a vector.

func CrossVS

func CrossVS(v Vec2, s Q) Vec2

CrossVS returns the cross product of a vector and a scalar.

func InvRotateVector

func InvRotateVector(q Rot, v Vec2) Vec2

InvRotateVector rotates v by the inverse of q.

func InvTransformPoint

func InvTransformPoint(t Transform, p Vec2) Vec2

InvTransformPoint carries the point p from the parent frame into the frame of t, for example from world space into local space.

func InvTransformWorldPoint added in v1.1.0

func InvTransformWorldPoint(t WorldTransform, p Pos) Vec2

InvTransformWorldPoint moves a world position into a local frame. It corresponds to b2InvTransformWorldPoint.

func LeftPerp

func LeftPerp(v Vec2) Vec2

LeftPerp returns the left-pointing perpendicular of v. It equals CrossSV(one, v).

func Lerp

func Lerp(a, b Vec2, t Q) Vec2

Lerp interpolates between a and b by t.

It weighs both ends, unlike the Lerp method of the fixed-point module, which adds a scaled difference. The two round differently.

func Max

func Max(a, b Vec2) Vec2

Max returns the component-wise maximum of a and b.

func Min

func Min(a, b Vec2) Vec2

Min returns the component-wise minimum of a and b.

func Mul

func Mul(a, b Vec2) Vec2

Mul returns the component-wise product of a and b.

func MulAdd

func MulAdd(a Vec2, s Q, b Vec2) Vec2

MulAdd returns a + s * b.

func MulMV

func MulMV(m Mat22, v Vec2) Vec2

MulMV returns the product of the matrix m and the vector v.

func MulSub

func MulSub(a Vec2, s Q, b Vec2) Vec2

MulSub returns a - s * b.

func Neg

func Neg(a Vec2) Vec2

Neg returns the negation of a.

func RightPerp

func RightPerp(v Vec2) Vec2

RightPerp returns the right-pointing perpendicular of v. It equals CrossVS(v, one).

func RotGetXAxis

func RotGetXAxis(q Rot) Vec2

RotGetXAxis returns the x axis of q.

func RotGetYAxis

func RotGetYAxis(q Rot) Vec2

RotGetYAxis returns the y axis of q.

func RotateVector

func RotateVector(q Rot, v Vec2) Vec2

RotateVector rotates v by q.

func Solve22

func Solve22(m Mat22, b Vec2) Vec2

Solve22 solves m * x = b for the column vector b. It is cheaper than the inverse for a one-shot case. A singular matrix returns the zero vector.

func SubPos added in v1.1.0

func SubPos(a, b Pos) Vec2

SubPos returns a - b as a vector. It corresponds to b2SubPos.

func ToVec2 added in v1.1.0

func ToVec2(p Pos) Vec2

ToVec2 converts a world position to a vector. It corresponds to b2ToVec2.

func TransformPoint

func TransformPoint(t Transform, p Vec2) Vec2

TransformPoint carries the point p from the frame of t into the parent frame, for example from local space into world space.

func V2 added in v1.0.0

func V2[T Scalar](x, y T) Vec2

V2 returns the vector (x, y); both convert as F does.

func Vec2Zero

func Vec2Zero() Vec2

Vec2Zero returns the zero vector.

func (Vec2) Add added in v0.8.0

func (v Vec2) Add(o Vec2) Vec2

Add returns the component-wise sum of two vectors.

func (Vec2) Distance added in v0.8.0

func (v Vec2) Distance(o Vec2) Q

Distance returns the distance between v and o.

func (Vec2) DistanceSq added in v0.8.0

func (v Vec2) DistanceSq(o Vec2) Q

DistanceSq returns the squared distance between v and o.

func (Vec2) Div added in v0.8.0

func (v Vec2) Div(s Q) Vec2

Div returns v divided by s.

func (Vec2) Dot added in v0.8.0

func (v Vec2) Dot(o Vec2) Q

Dot returns the dot product of two vectors.

func (Vec2) Len added in v0.8.0

func (v Vec2) Len() Q

Len returns the length of the vector.

func (Vec2) LenSq added in v0.8.0

func (v Vec2) LenSq() Q

LenSq returns the squared length of the vector.

func (Vec2) Lerp added in v0.8.0

func (v Vec2) Lerp(target Vec2, t Q) Vec2

Lerp linearly interpolates between v and target by t.

func (Vec2) Mul added in v0.8.0

func (v Vec2) Mul(s Q) Vec2

Mul returns v scaled by s.

func (Vec2) Normalize added in v0.8.0

func (v Vec2) Normalize() Vec2

Normalize returns a unit vector with the same direction as v. A vector whose squared length is at or below 1000 * FLT_MIN returns the zero vector, as b2Normalize does.

func (Vec2) Sub added in v0.8.0

func (v Vec2) Sub(o Vec2) Vec2

Sub returns the component-wise difference of two vectors.

type Version

type Version struct {
	// Major counts significant changes.
	Major int

	// Minor counts incremental changes.
	Minor int

	// Revision counts bug fixes.
	Revision int
}

Version reports a three-part release number.

func ReferenceVersion

func ReferenceVersion() Version

ReferenceVersion returns the Box2D release that this package ports. The module has its own version; this one identifies the reference source.

type WeldJointDef added in v0.3.0

type WeldJointDef struct {
	// Base joint definition.
	Base JointDef

	// Linear stiffness in cycles per second. Zero means rigid.
	LinearHertz Q

	// Angular stiffness in cycles per second. Zero means rigid.
	AngularHertz Q

	// Linear damping ratio, non-dimensional. Use 1 for critical damping.
	LinearDampingRatio Q

	// Angular damping ratio, non-dimensional. Use 1 for critical damping.
	AngularDampingRatio Q
	// contains filtered or unexported fields
}

WeldJointDef configures a weld joint: it holds local frame B on local frame A, rigidly or with springs that mimic a soft body. The approximate solver cannot hold many bodies together rigidly. Initialize it with DefaultWeldJointDef.

func DefaultWeldJointDef added in v0.3.0

func DefaultWeldJointDef() WeldJointDef

DefaultWeldJointDef returns the default weld joint definition.

type WheelJointDef added in v0.3.0

type WheelJointDef struct {
	// Base joint definition.
	Base JointDef

	// Enable a linear spring along the local axis.
	EnableSpring bool

	// The spring stiffness in cycles per second.
	Hertz Q

	// The spring damping ratio, non-dimensional.
	DampingRatio Q

	// Enable and disable the joint limit.
	EnableLimit bool

	// The lower translation limit.
	LowerTranslation Q

	// The upper translation limit.
	UpperTranslation Q

	// Enable and disable the joint rotational motor.
	EnableMotor bool

	// The maximum motor torque, usually in newton-meters.
	MaxMotorTorque Q

	// The desired motor speed in turns per second.
	MotorSpeed Q
	// contains filtered or unexported fields
}

WheelJointDef configures a wheel joint: body B is a wheel that rotates freely and slides along the x-axis of local frame A, with a suspension spring. The translation is zero when the local frame origins coincide in world space. Initialize it with DefaultWheelJointDef.

func DefaultWheelJointDef added in v0.3.0

func DefaultWheelJointDef() WheelJointDef

DefaultWheelJointDef returns the default wheel joint definition.

type WorkerPanic added in v1.0.0

type WorkerPanic struct {
	WorkerIndex int
	Value       any
	Stack       []byte
}

WorkerIndex 0 is the goroutine that called Step. A serial step panics with the original value instead.

func (*WorkerPanic) Error added in v1.0.0

func (p *WorkerPanic) Error() string

func (*WorkerPanic) Unwrap added in v1.0.0

func (p *WorkerPanic) Unwrap() error

type WorldCastOutput added in v1.1.0

type WorldCastOutput = CastOutput

WorldCastOutput is the world-space result of a shape cast. Without the dbox2d_double tag it is the plain cast output. It corresponds to b2WorldCastOutput in include/box2d/collision.h.

type WorldDef

type WorldDef struct {
	// Gravity vector. The world has no up vector.
	Gravity Vec2

	// Restitution speed threshold, usually in meters per second. Collisions
	// above this speed have restitution applied, so they bounce.
	RestitutionThreshold Q

	// Threshold speed for hit events, usually in meters per second.
	HitEventThreshold Q

	// Contact stiffness in cycles per second. Increasing this increases the
	// speed of overlap recovery, but can introduce jitter.
	ContactHertz Q

	// Contact bounciness, non-dimensional. Decreasing this speeds up overlap
	// recovery, with a more energetic resolution as the trade-off.
	ContactDampingRatio Q

	// A cap on the overlap resolution speed, usually in meters per second.
	// The hertz and the damping ratio set the speed itself.
	MaxContactPushSpeed Q

	// RestitutionIterations is the number of restitution passes after the
	// sub-steps, in [0, 63]. More passes resolve stacked bounces better.
	RestitutionIterations int

	// EnableRestitutionPropagation lets the restitution passes also solve
	// the contacts without restitution, so a bounce travels through a stack.
	EnableRestitutionPropagation bool

	// Maximum linear speed, usually in meters per second.
	MaximumLinearSpeed Q

	// FrictionCallback customizes friction mixing for new contacts.
	FrictionCallback FrictionCallback

	// RestitutionCallback customizes restitution mixing for new contacts.
	RestitutionCallback RestitutionCallback

	// WorkerCount is the number of workers that step the world. 1 steps on
	// the calling goroutine. 0 picks min(runtime.GOMAXPROCS(0), 64). Any N
	// produces the same bits; WebAssembly always steps on one worker, and a
	// step with few awake bodies runs on the caller whatever N says.
	WorkerCount int

	// Enable sleeping to improve performance.
	EnableSleep bool

	// Enable continuous collision.
	EnableContinuous bool

	// Application data attached to the world.
	UserData any
	// contains filtered or unexported fields
}

WorldDef configures the creation of a world. Initialize it with DefaultWorldDef.

func DefaultWorldDef

func DefaultWorldDef() WorldDef

DefaultWorldDef returns the default world definition.

type WorldId

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

WorldId identifies a world. Its zero value is null.

func CreateWorld

func CreateWorld(def *WorldDef) WorldId

CreateWorld creates a world from a definition. The definition must come from DefaultWorldDef and is not retained. It returns the null id when every slot of the registry is in use.

func CreateWorldFromSnapshot added in v1.1.0

func CreateWorldFromSnapshot(image []byte, workerCount int) WorldId

CreateWorldFromSnapshot creates a new world from a snapshot, or returns the null id. It corresponds to b2CreateWorldFromSnapshot.

func LoadWorldId

func LoadWorldId(x uint32) WorldId

LoadWorldId unpacks a world id from a uint32.

func (WorldId) CastMover added in v0.4.0

func (worldId WorldId) CastMover(origin Pos, mover *Capsule, translation Vec2, filter QueryFilter) Q

CastMover sweeps a capsule, given relative to origin, through the world and returns the fraction of the translation it may travel. Shapes it already overlaps do not stop it; a capsule that already touches may move a little closer. A locked world panics. It corresponds to b2World_CastMover in src/world.c.

func (WorldId) CastRay added in v0.4.0

func (worldId WorldId) CastRay(origin Pos, translation Vec2, filter QueryFilter, fcn CastResultFcn) TreeStats

CastRay reports the shapes a ray hits, tree by tree. The callback clips the ray for the next tree; a zero return stops the cast. A locked world panics. It corresponds to b2World_CastRay in src/world.c.

func (WorldId) CastRayClosest added in v0.4.0

func (worldId WorldId) CastRayClosest(origin Pos, translation Vec2, filter QueryFilter) RayResult

CastRayClosest reports the closest hit of a ray, the most common cast in games. An initial overlap does not count as a hit. A locked world panics. It corresponds to b2World_CastRayClosest in src/world.c; the closure replaces b2RayCastClosestFcn.

func (WorldId) CastShape added in v0.4.0

func (worldId WorldId) CastShape(origin Pos, proxy *ShapeProxy, translation Vec2, filter QueryFilter, fcn CastResultFcn) TreeStats

CastShape sweeps a proxy, given relative to origin, through the world and reports each hit, tree by tree. The callback returns as for CastRay. A locked world panics. It corresponds to b2World_CastShape in src/world.c.

func (WorldId) CollideMover added in v0.4.0

func (worldId WorldId) CollideMover(origin Pos, mover *Capsule, filter QueryFilter, fcn PlaneResultFcn)

CollideMover reports the collision plane of every shape the mover capsule, given relative to origin, touches, tree by tree; the planes are relative to origin too. The callback returns false to stop the walk. A locked world panics. It corresponds to b2World_CollideMover in src/world.c.

func (WorldId) Draw added in v0.4.0

func (worldId WorldId) Draw(draw *DebugDraw)

Draw draws the shapes inside draw.DrawingBounds, then the names, mass, joints, contacts and islands of their bodies, as the flags select. Start from DefaultDebugDraw. A locked world panics. It corresponds to b2World_Draw in src/physics_world.c.

Example
worldId, _, _ := exampleWorld()
defer b2.DestroyWorld(worldId)

// Every callback defaults to a no-op and the default draws shapes over
// the whole world; wire up only the callback used here and count how
// many shapes the world hands back.
shapeCount := 0
draw := b2.DefaultDebugDraw()
draw.DrawSolidPolygonFcn = func(b2.WorldTransform, []b2.Vec2, b2.Q, b2.HexColor) { shapeCount++ }

worldId.Draw(&draw)

fmt.Println(shapeCount)
Output:
1

func (WorldId) DumpMemoryStats added in v0.5.0

func (id WorldId) DumpMemoryStats(w io.Writer)

DumpMemoryStats writes the memory use of the world to w, one section per structure. It corresponds to b2World_DumpMemoryStats in src/world.c.

func (WorldId) EnableContinuous added in v0.4.0

func (worldId WorldId) EnableContinuous(flag bool)

EnableContinuous changes continuous collision detection. It corresponds to b2World_EnableContinuous in src/world.c.

func (WorldId) EnableRestitutionPropagation added in v1.1.0

func (worldId WorldId) EnableRestitutionPropagation(flag bool)

EnableRestitutionPropagation lets the restitution passes solve every contact. It corresponds to b2World_EnableRestitutionPropagation in src/physics_world.c.

func (WorldId) EnableSleeping added in v0.4.0

func (worldId WorldId) EnableSleeping(flag bool)

EnableSleeping changes sleeping and wakes sleeping sets when disabled. It corresponds to b2World_EnableSleeping in src/world.c.

func (WorldId) EnableWarmStarting added in v0.4.0

func (worldId WorldId) EnableWarmStarting(flag bool)

EnableWarmStarting changes impulse warm starting. It corresponds to b2World_EnableWarmStarting in src/world.c.

func (WorldId) Explode added in v0.4.0

func (worldId WorldId) Explode(def *ExplosionDef)

Explode applies an impulse to every dynamic body near an explosion center, scaled by distance and by the shape perimeter facing the center. A locked world is a no-op. It corresponds to b2World_Explode in src/world.c.

Example
worldId, _, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

def := b2.DefaultExplosionDef()
def.Position = boxId.GetPosition()
def.Radius = b2.QFromInt(4)
def.Falloff = b2.QFromInt(2)
def.ImpulsePerLength = b2.QFromInt(8)
worldId.Explode(&def)

// The box center coincides with the explosion center, so the
// direction is undefined; the engine falls back to (1, 0) rather
// than leaving the impulse with a zero direction.
fmt.Println(boxId.GetLinearVelocity())
Output:
{8 0}

func (WorldId) GetAwakeBodyCount added in v0.4.0

func (worldId WorldId) GetAwakeBodyCount() int

GetAwakeBodyCount returns the number of bodies in the awake set. It corresponds to b2World_GetAwakeBodyCount in src/world.c.

func (WorldId) GetBodyEvents added in v0.4.0

func (worldId WorldId) GetBodyEvents() BodyEvents

GetBodyEvents returns the move events of the last step. It corresponds to b2World_GetBodyEvents in src/world.c.

func (WorldId) GetBounds added in v1.1.0

func (worldId WorldId) GetBounds() AABB

GetBounds returns the union of the root bounds of the static, kinematic and dynamic trees, skipping empty trees; an empty world reports a zero box. It corresponds to b2World_GetBounds in src/physics_world.c.

func (WorldId) GetContactEvents added in v0.4.0

func (worldId WorldId) GetContactEvents() ContactEvents

GetContactEvents returns the contact events of the last step. It corresponds to b2World_GetContactEvents in src/world.c.

func (WorldId) GetContactRecycleDistance added in v1.1.0

func (worldId WorldId) GetContactRecycleDistance() Q

GetContactRecycleDistance returns the contact recycle distance. It corresponds to b2World_GetContactRecycleDistance in src/physics_world.c.

func (WorldId) GetContactTuning added in v1.1.0

func (worldId WorldId) GetContactTuning() (hertz, dampingRatio, pushSpeed Q)

GetContactTuning returns the contact softness and push speed. It corresponds to b2World_GetContactTuning in src/physics_world.c.

func (WorldId) GetCounters added in v0.4.0

func (worldId WorldId) GetCounters() Counters

GetCounters reports entity, tree, arena and graph counts. It corresponds to b2World_GetCounters in src/world.c.

func (WorldId) GetGravity added in v0.4.0

func (worldId WorldId) GetGravity() Vec2

GetGravity returns the gravity vector. It corresponds to b2World_GetGravity.

func (WorldId) GetHitEventThreshold added in v0.4.0

func (worldId WorldId) GetHitEventThreshold() Q

GetHitEventThreshold returns the hit-event threshold. It corresponds to b2World_GetHitEventThreshold in src/world.c.

func (WorldId) GetJointEvents added in v1.1.0

func (worldId WorldId) GetJointEvents() []JointEvent

GetJointEvents returns the joint events of the last step: the awake joints whose force or torque crossed their threshold. It corresponds to b2World_GetJointEvents in src/physics_world.c.

func (WorldId) GetMaxLinearSpeed added in v1.1.0

func (worldId WorldId) GetMaxLinearSpeed() Q

GetMaxLinearSpeed returns the velocity cap. It corresponds to b2World_GetMaxLinearSpeed in src/physics_world.c.

func (WorldId) GetProfile added in v0.5.0

func (id WorldId) GetProfile() Profile

GetProfile returns the timing of the last Step. It corresponds to b2World_GetProfile in src/world.c.

func (WorldId) GetRestitutionIterations added in v1.1.0

func (worldId WorldId) GetRestitutionIterations() int

GetRestitutionIterations returns the number of restitution passes. It corresponds to b2World_GetRestitutionIterations in src/physics_world.c.

func (WorldId) GetRestitutionThreshold added in v0.4.0

func (worldId WorldId) GetRestitutionThreshold() Q

GetRestitutionThreshold returns the restitution speed threshold. It corresponds to b2World_GetRestitutionThreshold in src/world.c.

func (WorldId) GetSensorEvents added in v0.4.0

func (worldId WorldId) GetSensorEvents() SensorEvents

GetSensorEvents returns the sensor events of the last step. It corresponds to b2World_GetSensorEvents in src/world.c.

Example
worldDef := b2.DefaultWorldDef()
worldId := b2.CreateWorld(&worldDef)
defer b2.DestroyWorld(worldId)

sensorDef := b2.DefaultBodyDef()
sensorBodyId := b2.CreateBody(worldId, &sensorDef)
sensorShapeDef := b2.DefaultShapeDef()
sensorShapeDef.IsSensor = true
sensorShapeDef.EnableSensorEvents = true
sensorBox := b2.MakeBox(b2.QFromInt(2), b2.QFromInt(2))
b2.CreatePolygonShape(sensorBodyId, &sensorShapeDef, &sensorBox)

visitorDef := b2.DefaultBodyDef()
visitorDef.Type = b2.DynamicBody
visitorBodyId := b2.CreateBody(worldId, &visitorDef)
visitorShapeDef := b2.DefaultShapeDef()
visitorShapeDef.EnableSensorEvents = true
visitorBox := b2.MakeSquare(b2.QHalf())
visitorShapeId := b2.CreatePolygonShape(visitorBodyId, &visitorShapeDef, &visitorBox)

dt := b2.QOne().Div(b2.QFromInt(60))
worldId.Step(dt, 4)
begin := worldId.GetSensorEvents().BeginEvents
fmt.Println(len(begin) == 1 && begin[0].VisitorShapeId == visitorShapeId)

b2.DestroyShape(visitorShapeId, false)
worldId.Step(dt, 4)
end := worldId.GetSensorEvents().EndEvents
fmt.Println(len(end) == 1 && end[0].VisitorShapeId == visitorShapeId)
Output:
true
true

func (WorldId) GetSnapshot added in v1.1.0

func (worldId WorldId) GetSnapshot(image []byte) int

GetSnapshot writes the snapshot of the world into image and returns its size. When image is too small nothing is copied; the returned size tells the capacity to allocate. It corresponds to b2World_GetSnapshot.

func (WorldId) GetStateHash added in v1.1.0

func (worldId WorldId) GetStateHash() uint64

GetStateHash hashes the transforms, velocities, contacts, joint impulses and the id pools. Two runs that agree on it agree on the observable simulation. It corresponds to b2World_GetStateHash.

func (WorldId) GetUserData added in v0.4.0

func (worldId WorldId) GetUserData() any

GetUserData returns the data attached to the world. It corresponds to b2World_GetUserData in src/world.c.

func (WorldId) IsContinuousEnabled added in v0.4.0

func (worldId WorldId) IsContinuousEnabled() bool

IsContinuousEnabled reports whether continuous collision is enabled. It corresponds to b2World_IsContinuousEnabled in src/world.c.

func (WorldId) IsNull

func (id WorldId) IsNull() bool

IsNull reports whether the id references nothing.

func (WorldId) IsRestitutionPropagationEnabled added in v1.1.0

func (worldId WorldId) IsRestitutionPropagationEnabled() bool

IsRestitutionPropagationEnabled reports whether the restitution passes solve every contact. It corresponds to b2World_IsRestitutionPropagationEnabled in src/physics_world.c.

func (WorldId) IsSleepingEnabled added in v0.4.0

func (worldId WorldId) IsSleepingEnabled() bool

IsSleepingEnabled reports whether sleeping is enabled. It corresponds to b2World_IsSleepingEnabled in src/world.c.

func (WorldId) IsValid

func (id WorldId) IsValid() bool

IsValid reports whether the id references a live world. It lets an application hold ids safely across destruction.

func (WorldId) IsWarmStartingEnabled added in v0.4.0

func (worldId WorldId) IsWarmStartingEnabled() bool

IsWarmStartingEnabled reports whether warm starting is enabled. It corresponds to b2World_IsWarmStartingEnabled in src/world.c.

func (WorldId) OverlapAABB added in v0.4.0

func (worldId WorldId) OverlapAABB(origin Pos, aabb AABB, filter QueryFilter, fcn OverlapResultFcn) TreeStats

OverlapAABB reports every shape whose fat bounds overlap the box, given relative to origin, and whose filter accepts the query. It walks the static, the kinematic and the dynamic tree in that order; a false result ends only the current tree, as in the reference. A locked world panics. It corresponds to b2World_OverlapAABB in src/world.c.

func (WorldId) OverlapShape added in v0.4.0

func (worldId WorldId) OverlapShape(origin Pos, proxy *ShapeProxy, filter QueryFilter, fcn OverlapResultFcn) TreeStats

OverlapShape reports every shape that overlaps the proxy, given relative to origin, and whose filter accepts the query, tree by tree; a false result ends only the current tree. The distance solver decides the overlap, so the report is exact, not a bounds test. A locked world panics. It corresponds to b2World_OverlapShape in src/world.c.

func (WorldId) RebuildStaticTree added in v0.4.0

func (worldId WorldId) RebuildStaticTree()

RebuildStaticTree rebuilds the static broad-phase tree. It corresponds to b2World_RebuildStaticTree in src/world.c.

func (WorldId) RestoreFromSnapshot added in v1.1.0

func (worldId WorldId) RestoreFromSnapshot(image []byte) bool

RestoreFromSnapshot overwrites the simulation state of a live world with a snapshot. Callbacks, user data and the worker count are kept; the user data of bodies, shapes and joints is cleared, as it is not part of the image. A world that records or steps refuses. A corrupt image leaves the world unusable past the header check, as upstream. It corresponds to b2World_RestoreFromSnapshot.

func (WorldId) SetContactRecycleDistance added in v1.1.0

func (worldId WorldId) SetContactRecycleDistance(recycleDistance Q)

SetContactRecycleDistance changes the farthest relative movement that keeps a contact manifold. Zero turns contact recycling off. It corresponds to b2World_SetContactRecycleDistance in src/physics_world.c.

func (WorldId) SetContactTuning added in v0.4.0

func (worldId WorldId) SetContactTuning(hertz, dampingRatio, pushSpeed Q)

SetContactTuning changes contact softness and push speed. It corresponds to b2World_SetContactTuning in src/world.c.

func (WorldId) SetCustomFilterCallback added in v0.4.0

func (worldId WorldId) SetCustomFilterCallback(fcn CustomFilterFcn)

SetCustomFilterCallback sets the pair filter run during collision. It corresponds to b2World_SetCustomFilterCallback in src/world.c; the reference also stores a void* context, dropped here per D-014.

Example
worldId, groundId, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

// Rejecting every pair keeps the box from ever touching the ground. Only
// shapes that enable custom filtering reach the callback.
worldId.SetCustomFilterCallback(func(b2.ShapeId, b2.ShapeId) bool {
	return false
})
shapeDef := b2.DefaultShapeDef()
shapeDef.EnableCustomFiltering = true
segment := b2.Segment{Point1: b2.Vec2{X: b2.QFromInt(-5)}, Point2: b2.Vec2{X: b2.QFromInt(5)}}
b2.CreateSegmentShape(groundId, &shapeDef, &segment)

dt := b2.QOne().Div(b2.QFromInt(60))
for range 60 {
	worldId.Step(dt, 4)
}

fmt.Println(len(worldId.GetContactEvents().BeginEvents))
fmt.Println(groundId.IsValid() && boxId.IsValid())
Output:
0
true

func (WorldId) SetFrictionCallback added in v0.4.0

func (worldId WorldId) SetFrictionCallback(callback FrictionCallback)

SetFrictionCallback changes friction mixing for future contacts. It corresponds to b2World_SetFrictionCallback in src/world.c.

Example
worldDef := b2.DefaultWorldDef()
worldId := b2.CreateWorld(&worldDef)
defer b2.DestroyWorld(worldId)

worldId.SetFrictionCallback(func(frictionA b2.Q, _ uint64, frictionB b2.Q, _ uint64) b2.Q {
	return frictionA.Add(frictionB).Div(b2.QFromInt(2))
})

fmt.Println(worldId.IsValid())
Output:
true

func (WorldId) SetGravity added in v0.4.0

func (worldId WorldId) SetGravity(gravity Vec2)

SetGravity changes the world gravity vector. It corresponds to b2World_SetGravity in src/world.c.

func (WorldId) SetHitEventThreshold added in v0.4.0

func (worldId WorldId) SetHitEventThreshold(value Q)

SetHitEventThreshold limits the hit-event threshold to the valid Q range. It corresponds to b2World_SetHitEventThreshold in src/world.c.

func (WorldId) SetMaxLinearSpeed added in v1.1.0

func (worldId WorldId) SetMaxLinearSpeed(maximumLinearSpeed Q)

SetMaxLinearSpeed changes the velocity cap, which must be positive. It corresponds to b2World_SetMaxLinearSpeed in src/physics_world.c.

func (WorldId) SetPreSolveCallback added in v0.4.0

func (worldId WorldId) SetPreSolveCallback(preSolveFcn PreSolveFcn, preContinuousFcn PreContinuousFcn)

SetPreSolveCallback sets the callback run after a contact's manifold is updated, before the solver sees it, and the callback run on a time of impact event of the continuous stage. Either may be nil. It corresponds to b2World_SetPreSolveCallback in src/physics_world.c.

Example
worldId, _, boxId := exampleWorld()
defer b2.DestroyWorld(worldId)

// Clearing the points disables the contact for the step, so the box
// keeps falling through the ground instead of resting on it.
worldId.SetPreSolveCallback(func(_, _ b2.ShapeId, manifold *b2.Manifold) {
	manifold.PointCount = 0
}, nil)

startY := b2.ToVec2(boxId.GetPosition()).Y
dt := b2.QOne().Div(b2.QFromInt(60))
for range 60 {
	worldId.Step(dt, 4)
}

fmt.Println(b2.ToVec2(boxId.GetPosition()).Y.Less(startY))
Output:
true

func (WorldId) SetRestitutionCallback added in v0.4.0

func (worldId WorldId) SetRestitutionCallback(callback RestitutionCallback)

SetRestitutionCallback changes restitution mixing for future contacts. It corresponds to b2World_SetRestitutionCallback in src/world.c.

func (WorldId) SetRestitutionIterations added in v1.1.0

func (worldId WorldId) SetRestitutionIterations(iterations int)

SetRestitutionIterations changes the number of restitution passes, clamped to [0, 63]. It corresponds to b2World_SetRestitutionIterations in src/physics_world.c.

func (WorldId) SetRestitutionThreshold added in v0.4.0

func (worldId WorldId) SetRestitutionThreshold(value Q)

SetRestitutionThreshold limits the speed threshold to the valid Q range. It corresponds to b2World_SetRestitutionThreshold in src/world.c.

func (WorldId) SetUserData added in v0.4.0

func (worldId WorldId) SetUserData(userData any)

SetUserData attaches application data to the world. It corresponds to b2World_SetUserData in src/world.c.

func (WorldId) StartRecording added in v1.1.0

func (worldId WorldId) StartRecording(recording *Recording)

StartRecording starts recording the world into the buffer. The world must be at a step boundary, and a world with a pre-solve or custom filter callback cannot be recorded because replay cannot reproduce them. It corresponds to b2World_StartRecording.

func (WorldId) Step added in v0.4.0

func (worldId WorldId) Step(timeStep Q, subStepCount int)

Step advances the simulation by timeStep, split into subStepCount sub-steps. The reference recommends a fixed time step and 4 sub-steps. It corresponds to b2World_Step in src/world.c.

func (WorldId) StopRecording added in v1.1.0

func (worldId WorldId) StopRecording()

StopRecording ends the recording of the world. The buffer then holds a self-contained recording. It corresponds to b2World_StopRecording.

type WorldTransform added in v1.1.0

type WorldTransform = Transform

WorldTransform places a body in the world. Like Pos it is the plain transform without the dbox2d_double tag. It corresponds to b2WorldTransform in include/box2d/math_types.h.

func MakeWorldTransform added in v1.1.0

func MakeWorldTransform(t Transform) WorldTransform

MakeWorldTransform promotes a transform to a world transform. It corresponds to b2MakeWorldTransform.

func MulWorldTransforms added in v1.1.0

func MulWorldTransforms(a WorldTransform, b Transform) WorldTransform

MulWorldTransforms moves a local transform into the world. It corresponds to b2MulWorldTransforms.

Directories

Path Synopsis
internal
q32gen
Package q32gen derives the Q32 contact solver from contact_solver.go.
Package q32gen derives the Q32 contact solver from contact_solver.go.
shared
Package shared is the shared/ directory of the reference: the benchmark scenes of benchmarks.c, the ragdoll of human.c and the deterministic generator of random.h.
Package shared is the shared/ directory of the reference: the benchmark scenes of benchmarks.c, the ragdoll of human.c and the deterministic generator of random.h.
tools
benchcmp command
Command benchcmp compares two scene-benchmark result files and prints the ratio per scene.
Command benchcmp compares two scene-benchmark result files and prints the ratio per scene.
benchscale command
Command benchscale reads a set of scene-benchmark result files taken at several worker counts and prints how each side scales.
Command benchscale reads a set of scene-benchmark result files taken at several worker counts and prints how each side scales.
q32gen command
Command q32gen writes contact_solver_q32.go from contact_solver.go.
Command q32gen writes contact_solver_q32.go from contact_solver.go.

Jump to

Keyboard shortcuts

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