Help us shape the future of Go! Take the 2026 Go Developer Survey

dbox2d

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2026 License: MIT Imports: 12 Imported by: 0

README

dbox2d

dbox2d is a deterministic 2D physics library for Go and a port of Box2D v3.1.1. It has two scalar modes: the default build uses float32, while -tags dbox2d_fixed selects Q32.32 fixed-point arithmetic. In either mode, equal inputs produce the same result bits on every supported architecture and on every run.

Fixed point is the safer choice for cross-platform rollback, replay, and authoritative simulation. Float mode is also deterministic on the architectures covered by this repository's CI, and is usually faster in the measured workloads. A float-mode application must still control its complete simulation, not only its physics.

The project is pre-v1. Its public API and import path may change before the first stable release. It requires Go 1.26.4 or newer.

Tumbler in the browser host
Try the sample scenes in browser: float mode · fixed mode (WebGPU required)

What is included

The current port includes worlds, bodies, shapes, mass properties, contact manifolds, distance queries, shape casts, time of impact, sleeping islands, the constraint graph, the soft-step contact solver, events, dynamic trees, broadphase queries, chains, sensors, the character mover, and all seven Box2D joints plus the filter joint.

WorldId.Step creates new contact pairs, updates contacts, solves joints and contacts, handles fast bodies and bullets, and puts resting islands to sleep. It also exposes step profiling and memory statistics.

PORTING.md records the status of the Box2D port. Read DIVERGENCES.md when you need to understand a deliberate difference from the C implementation.

Install

go get github.com/dhannyell/dbox2d

The package follows the Box2D API closely. Reference functions named b2<Type>_<Name> normally become methods on the matching ID type:

b2Body_GetPosition(bodyId)              // bodyId.GetPosition()
b2RevoluteJoint_EnableLimit(jointId, x) // jointId.EnableLimit(true)
b2World_GetGravity(worldId)             // worldId.GetGravity()

Functions that do not operate on an existing handle remain package functions, including Create*, Destroy*, Default*Def, Make*, and geometry helpers.

Run the samples

The samples module contains 47 Box2D scenes in the Stacking, Benchmark, and Joints categories. A native host and a browser host render the same scenes with WebGPU.

cd samples
go run ./cmd/native

To build the browser host:

cd samples
CGO_ENABLED=0 GOOS=js GOARCH=wasm go build -o web/app.wasm ./cmd/web
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

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

Determinism and scalar modes

The default build stores simulation values in float32. The optional dbox2d_fixed build tag uses signed Q32.32 fixed point from fixed instead. Both modes keep a deterministic result for a given architecture-supported build, but they are different numeric systems and can follow different trajectories. ScalarMode reports the mode of a build: "float" or "fixed".

Build Scalar type Determinism promise When to use it
default float32 identical float32 bits on amd64, arm64, 386, and wasm most applications
-tags dbox2d_fixed Q32.32 fixed point identical Q32.32 bits across supported architectures authoritative simulation, replay, rollback, and checksums

Use the package constructors to create simulation values:

QZero()
QOne()
QHalf()
QFromInt(3)
QFromRatio(1, 8)
QMustParse("0.35")

QFromFloat64 and QToFloat64 are for values entering or leaving the simulation. The solver itself does not use them. Angles are expressed in turns: one quarter turn is QFromRatio(1, 4).

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.

SIMD family

The dbox2d_simd build tag enables a SIMD contact solver alongside the scalar solver in both modes. Colored contacts are solved in lanes; the overflow color remains scalar.

Mode amd64 arm64 wasm Other targets
fixed AVX2, width 8 NEON, width 4 generic generic
float AVX2, width 8 NEON, width 4 SIMD128, width 4 generic

In fixed mode, the fixed module selects the lane implementation and fixed.LanePath() reports the active path. Native vector paths require GOEXPERIMENT=simd with Go 1.27.0. Without the experiment, the same build tag uses the generic path.

On amd64, AVX2 falls back to the scalar contact solver at runtime when the CPU does not support AVX2.

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 SIMD and scalar families produce identical result bits on every supported path in both modes. Float SIMD never fuses multiply-add or multiply-subtract operations (DIVERGENCES.md D-019). Fixed SIMD uses the same Q16.16 contact grid as the scalar solver and matches it while no contact value saturates. A contact whose inverse mass or inertia falls outside the lane window of that grid solves in Q32.32 in both families (D-020).

Measured on an AMD Ryzen 7 5800X3D: milliseconds for 60 steps of a settled scene (after 240 warmup steps), median of 5 interleaved runs.

Scene Mode Workers Scalar SIMD AVX2 Generic
Tumbler float 1 444 298 531
Tumbler float 8 124 100 176
Tumbler fixed 1 1312 815 3563
Tumbler fixed 8 350 244 817
LargePyramid float 1 734 377 993
LargePyramid float 8 152 92 227
LargePyramid fixed 1 3125 1746 11093
LargePyramid fixed 8 636 416 1867
Barrel float 1 363 288 412
Barrel float 8 133 120 157
Barrel fixed 1 876 581 2555
Barrel fixed 8 258 203 578

Fixed SIMD remains 1.7 to 4.6 times slower than float SIMD in these scenes. On AVX2, each Q16.16 lane multiplication must widen to 64 bits before narrowing back to Q16.16.

The generic lane path exists for conformance and is slower than the scalar solver: up to 1.5 times in float mode and up to 3.5 times in fixed mode. Do not enable dbox2d_simd on targets without a native vector path. For fixed mode, this currently includes wasm.

Choosing a mode for deterministic simulation

Both modes support deterministic simulation. Q32.32 is the recommended choice for cross-platform rollback and replay because its arithmetic has a simpler, stronger reproducibility contract.

Float mode is suitable for rollback when an application verifies its whole simulation on every supported target. Use a fixed simulation tick, serialize all state that affects future frames, use a deterministic random-number generator, keep update order stable, and avoid platform-dependent math or application logic outside dbox2d. Compare checksums regularly in development and detect desynchronization in production.

Workers and callbacks

A world owns its workers through WorldDef.WorkerCount. Go callbacks keep their own state; they do not share the void* context convention of the C API. Changing the worker count does not change the result bits. The repository pins that contract in TestStepIsWorkerCountIndependent.

Debug drawing

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

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

Fixed point trades speed for reproducibility. The numbers below are medians from one machine: AMD Ryzen 7 5800X3D, Windows/amd64, GOMAXPROCS=16, six runs, summarized with benchstat. They are useful for understanding the trade-off, not as a promise for another machine or workload.

Workload Q32.32 float64 mirror Allocation
Pyramid step: 210 boxes, 590 contacts, 4 sub-steps ~2.1 ms ~0.64 ms 0
Free-fall step: 1,024 bodies, 4 sub-steps ~0.36 ms ~0.11 ms 0
Velocity integration: 1,024 bodies ~31 us ~4.4 us 0
One polygon collision ~0.40 us ~0.091 us 0
Broadphase update: moving pyramid proxies ~75 us ~79 us 0
Dynamic-tree query: 100 boxes, four hits ~0.14 us ~0.14 us 0
One shape-distance query ~0.33 us ~0.082 us 0
One time-of-impact query ~2.5 us ~0.46 us 0
Bullet step: 64 fast boxes, 4 sub-steps ~59 us not measured 0

The comparison rows use a line-by-line float64 mirror of the same code. It is a controlled measurement of the cost of the fixed-point implementation; it is not a claim that the mirror is the complete upstream Box2D pipeline.

In the contact-heavy pyramid, the fixed build is about 3.3 times slower than that mirror and allocates nothing after contacts have been created. Broadphase updates and tree queries are effectively at parity because they mostly compare bounds rather than perform fixed-point division.

Run the benchmarks on the hardware and workload that matter to your project:

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

The saturation counter of fixed is off by default and never changes a result. The tests that assert that no operation saturated read it, so they check nothing unless the build sets fixed_satcounter. CI sets it.

Reference source

The original C source is available locally on the reference/box2d-v3.1.1 branch. It never merges into the Go branch and never builds as part of this module. It is kept as a fixed reference for porting work:

git show reference/box2d-v3.1.1:src/manifold.c
git blame reference/box2d-v3.1.1 -- src/manifold.c

Upstream tags are intentionally absent from that branch. Go derives module versions from tags, and an upstream tag could otherwise make go get publish a version containing the C reference tree. Module users download only the tagged Go tree.

License

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

Documentation

Overview

Package dbox2d 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

An angle is a turn, not a radian, because a turn reduces without pi. 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(100000)
)

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. The zero vector returns a zero length and the zero vector.

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 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 IsValidRotation

func IsValidRotation(q Rot) bool

IsValidRotation reports whether q is a usable and normalized rotation.

func IsValidVec2

func IsValidVec2(v Vec2) bool

IsValidVec2 reports whether v is a usable vector.

func PointInCapsule

func PointInCapsule(point Vec2, shape *Capsule) bool

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

func PointInCircle

func PointInCircle(point Vec2, shape *Circle) 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 converts a scalar to a presentation value, such as a camera value. It must never be used by simulation code.

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 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.

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 ComputeCapsuleAABB

func ComputeCapsuleAABB(shape *Capsule, xf Transform) AABB

ComputeCapsuleAABB returns the bounding box of a transformed capsule.

func ComputeCircleAABB

func ComputeCircleAABB(shape *Circle, xf Transform) AABB

ComputeCircleAABB returns the bounding box of a transformed circle.

func ComputePolygonAABB

func ComputePolygonAABB(shape *Polygon, xf Transform) AABB

ComputePolygonAABB returns the bounding box of a transformed polygon.

func ComputeSegmentAABB

func ComputeSegmentAABB(shape *Segment, xf Transform) AABB

ComputeSegmentAABB returns the bounding box of a transformed segment.

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 Vec2

	// 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

	// Optional body name for debugging, up to 31 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

	// Prevent the body from rotating. Useful for characters.
	FixedRotation bool

	// 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
	// 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, point Vec2, 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, point Vec2, 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) ApplyMassFromShapes added in v0.4.0

func (bodyId BodyId) ApplyMassFromShapes()

ApplyMassFromShapes recomputes mass data from the body's shapes. It corresponds to b2Body_ApplyMassFromShapes.

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) ComputeAABB added in v0.4.0

func (bodyId BodyId) ComputeAABB() AABB

ComputeAABB returns the union of the body's shape bounds. It corresponds to b2Body_ComputeAABB.

func (BodyId) Disable added in v0.4.0

func (bodyId BodyId) Disable()

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

Example
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, _, boxId := exampleWorld()
	defer dbox2d.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) 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) EnableSleep added in v0.4.0

func (bodyId BodyId) EnableSleep(enableSleep bool)

EnableSleep enables or disables sleeping. It corresponds to b2Body_EnableSleep.

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
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

func main() {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)
	defer dbox2d.DestroyWorld(worldId)

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

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

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

	data := make([]dbox2d.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) GetLocalCenterOfMass added in v0.4.0

func (bodyId BodyId) GetLocalCenterOfMass() Vec2

GetLocalCenterOfMass returns the center of mass in local coordinates. It corresponds to b2Body_GetLocalCenterOfMass.

func (BodyId) GetLocalPoint added in v0.4.0

func (bodyId BodyId) GetLocalPoint(worldPoint Vec2) 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) 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() Vec2

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) 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() Transform

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) GetWorldCenterOfMass added in v0.4.0

func (bodyId BodyId) GetWorldCenterOfMass() Vec2

GetWorldCenterOfMass returns the center of mass in world coordinates. It corresponds to b2Body_GetWorldCenterOfMass.

func (BodyId) GetWorldPoint added in v0.4.0

func (bodyId BodyId) GetWorldPoint(localPoint Vec2) Vec2

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 Vec2) 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) 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) IsFixedRotation added in v0.4.0

func (bodyId BodyId) IsFixedRotation() bool

IsFixedRotation reports whether body rotation is fixed. It corresponds to b2Body_IsFixedRotation.

func (BodyId) IsNull

func (id BodyId) IsNull() bool

IsNull reports whether the id references nothing.

func (BodyId) IsSleepEnabled added in v0.4.0

func (bodyId BodyId) IsSleepEnabled() bool

IsSleepEnabled reports whether the body may sleep. It corresponds to b2Body_IsSleepEnabled.

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) SetFixedRotation added in v0.4.0

func (bodyId BodyId) SetFixedRotation(flag bool)

SetFixedRotation enables or disables body rotation. It corresponds to b2Body_SetFixedRotation.

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) SetName added in v0.4.0

func (bodyId BodyId) SetName(name string)

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

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 Transform, timeStep Q)

SetTargetTransform sets the velocity needed to reach a target transform. It corresponds to b2Body_SetTargetTransform.

func (BodyId) SetTransform added in v0.4.0

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

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

Example
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, _, boxId := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	boxId.SetTransform(dbox2d.Vec2{X: dbox2d.QOne(), Y: dbox2d.QFromInt(3)}, dbox2d.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
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, _, boxId := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

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

	fmt.Println(boxId.GetType() == dbox2d.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.

type BodyMoveEvent added in v0.3.0

type BodyMoveEvent struct {
	Transform  Transform
	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 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 RayCastCapsule

func RayCastCapsule(input *RayCastInput, shape *Capsule) 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 RayCastCircle

func RayCastCircle(input *RayCastInput, shape *Circle) 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 RayCastPolygon

func RayCastPolygon(input *RayCastInput, shape *Polygon) 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 RayCastSegment

func RayCastSegment(input *RayCastInput, shape *Segment, 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 ShapeCast added in v0.3.0

func ShapeCast(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 b2ShapeCast in src/distance.c.

func ShapeCastCapsule added in v0.3.0

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

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

func ShapeCastCircle added in v0.3.0

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

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

func ShapeCastPolygon added in v0.3.0

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

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

func ShapeCastSegment added in v0.3.0

func ShapeCastSegment(input *ShapeCastInput, shape *Segment) 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, 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 four points. The points are copied during creation.
	Points []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 ports b2CreateChain.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, groundId, _ := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	// An open chain of four points builds two segments; the two end
	// segments extend with ghost vertices for smooth rolling contact.
	def := dbox2d.DefaultChainDef()
	def.Points = []dbox2d.Vec2{
		{X: dbox2d.QFromInt(0)},
		{X: dbox2d.QFromInt(1)},
		{X: dbox2d.QFromInt(2)},
		{X: dbox2d.QFromInt(3)},
		{X: dbox2d.QFromInt(4)},
	}
	chainId := dbox2d.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) GetFriction added in v0.4.0

func (chainId ChainId) GetFriction() Q

GetFriction returns the first segment's friction. It corresponds to b2Chain_GetFriction.

func (ChainId) GetMaterial added in v0.4.0

func (chainId ChainId) GetMaterial() int

GetMaterial returns the first segment's user material id. It corresponds to b2Chain_GetMaterial.

func (ChainId) GetRestitution added in v0.4.0

func (chainId ChainId) GetRestitution() Q

GetRestitution returns the first segment's restitution. It corresponds to b2Chain_GetRestitution.

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) 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) SetFriction added in v0.4.0

func (chainId ChainId) SetFriction(friction Q)

SetFriction changes the friction of every chain segment. It corresponds to b2Chain_SetFriction.

func (ChainId) SetMaterial added in v0.4.0

func (chainId ChainId) SetMaterial(material int)

SetMaterial changes the user material id of every chain segment. It corresponds to b2Chain_SetMaterial.

func (ChainId) SetRestitution added in v0.4.0

func (chainId ChainId) SetRestitution(restitution Q)

SetRestitution changes the restitution of every chain segment. It corresponds to b2Chain_SetRestitution.

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

	// Manifold is the initial contact manifold. The world records it
	// before the solver runs, so every impulse is zero.
	Manifold Manifold
}

ContactBeginTouchEvent reports that two shapes started to touch.

type ContactData added in v0.4.0

type ContactData struct {
	// 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
}

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

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

	// 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 Counters added in v0.4.0

type Counters struct {
	BodyCount, ShapeCount, ContactCount, JointCount, IslandCount, StackUsed, StaticTreeHeight, TreeHeight int
	TaskCount                                                                                             int
	ColorCounts                                                                                           [graphColorCount]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 {
	// DrawPolygon draws a closed polygon provided in CCW order.
	DrawPolygon DrawPolygonFcn
	// DrawSolidPolygon draws a solid closed polygon provided in CCW order.
	DrawSolidPolygon DrawSolidPolygonFcn
	// DrawCircle draws a circle.
	DrawCircle DrawCircleFcn
	// DrawSolidCircle draws a solid circle.
	DrawSolidCircle DrawSolidCircleFcn
	// DrawSolidCapsule draws a solid capsule.
	DrawSolidCapsule DrawSolidCapsuleFcn
	// DrawSegment draws a line segment.
	DrawSegment DrawSegmentFcn
	// DrawTransform draws a transform at a host-chosen length scale.
	DrawTransform DrawTransformFcn
	// DrawPoint draws a point.
	DrawPoint DrawPointFcn
	// DrawString draws a string in world space.
	DrawString DrawStringFcn

	// DrawingBounds is the region used when UseDrawingBounds restricts drawing.
	DrawingBounds AABB
	// UseDrawingBounds restricts drawing to DrawingBounds; depth sorting may be unstable.
	UseDrawingBounds bool
	// DrawShapes draws shapes.
	DrawShapes 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
	// DrawContacts draws contact points.
	DrawContacts bool
	// DrawGraphColors visualizes the graph coloring used for contacts and joints.
	DrawGraphColors bool
	// DrawContactNormals draws contact normals.
	DrawContactNormals bool
	// DrawContactImpulses draws contact normal impulses.
	DrawContactImpulses bool
	// DrawContactFeatures draws contact feature ids.
	DrawContactFeatures bool
	// DrawFrictionImpulses draws contact friction impulses.
	DrawFrictionImpulses bool
	// DrawIslands draws islands as bounding boxes.
	DrawIslands bool
}

DebugDraw holds the callbacks and options used by WorldId.Draw. Set the option fields to choose what the callbacks receive.

func DefaultDebugDraw added in v0.4.0

func DefaultDebugDraw() DebugDraw

DefaultDebugDraw returns a debug drawer whose callbacks are safe no-ops.

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

	// TransformA is the world transform of shape A.
	TransformA Transform

	// TransformB is the world transform of shape B.
	TransformB Transform

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

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

type DistanceJointDef added in v0.3.0

type DistanceJointDef struct {
	// The first attached body.
	BodyIdA BodyId

	// The second attached body.
	BodyIdB BodyId

	// The local anchor point relative to the origin of body A.
	LocalAnchorA Vec2

	// The local anchor point relative to the origin of body B.
	LocalAnchorB Vec2

	// 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, otherwise the limit and the motor apply.
	EnableSpring bool

	// 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

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

	// Application data attached to the joint.
	UserData any
	// contains filtered or unexported fields
}

DistanceJointDef configures a distance joint: a point on each body kept at a fixed length, or within a length range. 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 ShapeDistance. It corresponds to b2DistanceOutput in include/box2d/collision.h.

func ShapeDistance added in v0.3.0

func ShapeDistance(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 reference stops on a search direction shorter than FLT_EPSILON; the port stops on a squared length of exactly zero (D-012).

type DrawCircleFcn added in v0.4.0

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

DrawCircleFcn draws a circle outline.

type DrawPointFcn added in v0.4.0

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

DrawPointFcn draws a point of the requested size.

type DrawPolygonFcn added in v0.4.0

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

DrawPolygonFcn draws a closed polygon in counter-clockwise order.

type DrawSegmentFcn added in v0.4.0

type DrawSegmentFcn func(p1, p2 Vec2, color HexColor)

DrawSegmentFcn draws a line segment.

type DrawSolidCapsuleFcn added in v0.4.0

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

DrawSolidCapsuleFcn draws a solid capsule.

type DrawSolidCircleFcn added in v0.4.0

type DrawSolidCircleFcn func(transform Transform, radius Q, color HexColor)

DrawSolidCircleFcn draws a solid circle.

type DrawSolidPolygonFcn added in v0.4.0

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

DrawSolidPolygonFcn draws a solid polygon with a rounded radius.

type DrawStringFcn added in v0.4.0

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

DrawStringFcn draws a world-space string.

type DrawTransformFcn added in v0.4.0

type DrawTransformFcn func(transform Transform)

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() *DynamicTree

NewDynamicTree returns an empty tree. It corresponds to b2DynamicTree_Create.

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 b2DynamicTree_CreateProxy.

func (*DynamicTree) Destroy added in v0.7.0

func (t *DynamicTree) Destroy()

Destroy releases the node pool. It corresponds to b2DynamicTree_Destroy.

func (*DynamicTree) DestroyProxy added in v0.7.0

func (t *DynamicTree) DestroyProxy(proxyId int)

DestroyProxy removes a proxy. It corresponds to b2DynamicTree_DestroyProxy.

func (*DynamicTree) EnlargeProxy added in v0.7.0

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

EnlargeProxy grows a proxy in place; a later Rebuild repairs the tree. The new box must not fit in the old one. It corresponds to b2DynamicTree_EnlargeProxy.

func (*DynamicTree) GetAABB added in v0.7.0

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

GetAABB returns the box of a proxy. It corresponds to b2DynamicTree_GetAABB.

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) 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) 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) Query added in v0.7.0

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

Query calls back every proxy that overlaps the box and passes the mask. It corresponds to b2DynamicTree_Query.

func (*DynamicTree) RayCast added in v0.7.0

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

RayCast calls back every proxy whose box the ray reaches. It corresponds to b2DynamicTree_RayCast.

func (*DynamicTree) Rebuild added in v0.7.0

func (t *DynamicTree) Rebuild(fullBuild bool) int

Rebuild rebuilds the enlarged part of the tree, or the whole tree when fullBuild is set. It returns the leaf count of the build. It corresponds to b2DynamicTree_Rebuild.

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) ShapeCast added in v0.7.0

func (t *DynamicTree) ShapeCast(input *ShapeCastInput, maskBits uint64, fcn TreeShapeCastCallbackFcn) TreeStats

ShapeCast calls back every proxy whose box the swept proxy may reach. It corresponds to b2DynamicTree_ShapeCast.

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.

func (*DynamicTree) ValidateNoEnlarged added in v0.7.0

func (t *DynamicTree) ValidateNoEnlarged()

ValidateNoEnlarged checks that no proxy is left enlarged. Like Validate, it does nothing unless the build enables validation. It corresponds to b2DynamicTree_ValidateNoEnlarged.

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 Vec2

	// 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 {
	// The first attached body.
	BodyIdA BodyId

	// The second attached body.
	BodyIdB BodyId

	// Application data attached to the joint.
	UserData any
	// contains filtered or unexported fields
}

FilterJointDef configures a filter joint: it only disables collision between two 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 int, frictionB Q, userMaterialIdB int) 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 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
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, groundId, boxId := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	// A rope of length two from the ground origin to the box center.
	def := dbox2d.DefaultDistanceJointDef()
	def.BodyIdA = groundId
	def.BodyIdB = boxId
	def.Length = dbox2d.QFromInt(2)
	jointId := dbox2d.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
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, groundId, boxId := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	// The box falls through the ground; the filter joint disables the
	// collision between the two bodies.
	def := dbox2d.DefaultFilterJointDef()
	def.BodyIdA = groundId
	def.BodyIdB = boxId
	jointId := dbox2d.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.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, groundId, boxId := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	// The motor drives the box toward an offset of (1, 2) from the ground.
	def := dbox2d.DefaultMotorJointDef()
	def.BodyIdA = groundId
	def.BodyIdB = boxId
	def.LinearOffset = dbox2d.Vec2{X: dbox2d.QOne(), Y: dbox2d.QFromInt(2)}
	def.MaxForce = dbox2d.QFromInt(100)
	jointId := dbox2d.CreateMotorJoint(worldId, &def)

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

func CreateMouseJoint added in v0.3.0

func CreateMouseJoint(worldId WorldId, def *MouseJointDef) JointId

CreateMouseJoint creates a mouse joint. The definition must come from DefaultMouseJointDef.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, groundId, boxId := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	// The target is a world point; the joint pulls the box toward it.
	def := dbox2d.DefaultMouseJointDef()
	def.BodyIdA = groundId
	def.BodyIdB = boxId
	def.Target = dbox2d.Vec2{X: dbox2d.QOne(), Y: dbox2d.QFromInt(2)}
	def.MaxForce = dbox2d.QFromInt(500)
	jointId := dbox2d.CreateMouseJoint(worldId, &def)

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

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.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, groundId, boxId := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	// The box slides along the vertical axis of the ground, between
	// zero and three units.
	def := dbox2d.DefaultPrismaticJointDef()
	def.BodyIdA = groundId
	def.BodyIdB = boxId
	def.LocalAxisA = dbox2d.Vec2{Y: dbox2d.QOne()}
	def.EnableLimit = true
	def.LowerTranslation = dbox2d.QZero()
	def.UpperTranslation = dbox2d.QFromInt(3)
	jointId := dbox2d.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
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, groundId, boxId := exampleWorld()
	defer dbox2d.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 := dbox2d.DefaultRevoluteJointDef()
	def.BodyIdA = groundId
	def.BodyIdB = boxId
	def.LocalAnchorB = dbox2d.Vec2{Y: dbox2d.QFromInt(-2)}
	def.EnableLimit = true
	def.LowerAngle = dbox2d.QMustParse("-0.25")
	def.UpperAngle = dbox2d.QMustParse("0.25")
	jointId := dbox2d.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
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, groundId, boxId := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	// A weld with a soft angular spring holds the box in place.
	def := dbox2d.DefaultWeldJointDef()
	def.BodyIdA = groundId
	def.BodyIdB = boxId
	def.LocalAnchorB = dbox2d.Vec2{Y: dbox2d.QFromInt(-2)}
	def.AngularHertz = dbox2d.QFromInt(2)
	def.AngularDampingRatio = dbox2d.QHalf()
	jointId := dbox2d.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.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, groundId, boxId := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	// A suspension: the box rides the vertical axis on a spring and its
	// motor spins it at one turn per second.
	def := dbox2d.DefaultWheelJointDef()
	def.BodyIdA = groundId
	def.BodyIdB = boxId
	def.EnableMotor = true
	def.MotorSpeed = dbox2d.QOne()
	def.MaxMotorTorque = dbox2d.QFromInt(10)
	jointId := dbox2d.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 joint limit.

func (JointId) EnableMotor added in v0.4.0

func (jointId JointId) EnableMotor(enableMotor bool)

EnableMotor enables or disables the joint motor.

func (JointId) EnableSpring added in v0.4.0

func (jointId JointId) EnableSpring(enableSpring bool)

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

func (JointId) GetAngle added in v0.4.0

func (jointId JointId) GetAngle() Q

GetAngle reports the revolute joint angle relative to its reference angle, in turns.

func (JointId) GetAngularDampingRatio added in v0.4.0

func (jointId JointId) GetAngularDampingRatio() Q

GetAngularDampingRatio reports the weld joint angular damping ratio (b2WeldJoint_GetAngularDampingRatio).

func (JointId) GetAngularHertz added in v0.4.0

func (jointId JointId) GetAngularHertz() Q

GetAngularHertz reports the weld joint angular frequency (b2WeldJoint_GetAngularHertz).

func (JointId) GetAngularOffset added in v0.4.0

func (jointId JointId) GetAngularOffset() Q

GetAngularOffset reports the motor joint's angular offset in turns (b2MotorJoint_GetAngularOffset).

func (JointId) GetAngularSeparation added in v0.4.0

func (jointId JointId) GetAngularSeparation() Q

GetAngularSeparation reports angular separation in turns (b2Joint_GetAngularSeparation).

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) GetCorrectionFactor added in v0.4.0

func (jointId JointId) GetCorrectionFactor() Q

GetCorrectionFactor reports the motor joint's correction factor (b2MotorJoint_GetCorrectionFactor).

func (JointId) GetCurrentLength added in v0.4.0

func (jointId JointId) GetCurrentLength() Q

GetCurrentLength reports the distance between the current world anchors.

func (JointId) GetLength added in v0.4.0

func (jointId JointId) GetLength() Q

GetLength reports the distance joint length.

func (JointId) GetLinearDampingRatio added in v0.4.0

func (jointId JointId) GetLinearDampingRatio() Q

GetLinearDampingRatio reports the weld joint linear damping ratio (b2WeldJoint_GetLinearDampingRatio).

func (JointId) GetLinearHertz added in v0.4.0

func (jointId JointId) GetLinearHertz() Q

GetLinearHertz reports the weld joint linear frequency (b2WeldJoint_GetLinearHertz).

func (JointId) GetLinearOffset added in v0.4.0

func (jointId JointId) GetLinearOffset() Vec2

GetLinearOffset reports the motor joint's linear offset (b2MotorJoint_GetLinearOffset).

func (JointId) GetLinearSeparation added in v0.4.0

func (jointId JointId) GetLinearSeparation() Q

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

func (JointId) GetLocalAnchorA added in v0.4.0

func (jointId JointId) GetLocalAnchorA() Vec2

GetLocalAnchorA reports the local anchor on body A (b2Joint_GetLocalAnchorA).

func (JointId) GetLocalAnchorB added in v0.4.0

func (jointId JointId) GetLocalAnchorB() Vec2

GetLocalAnchorB reports the local anchor on body B (b2Joint_GetLocalAnchorB).

func (JointId) GetLocalAxisA added in v0.4.0

func (jointId JointId) GetLocalAxisA() Vec2

GetLocalAxisA reports the local axis on an applicable joint (b2Joint_GetLocalAxisA).

func (JointId) GetLowerLimit added in v0.4.0

func (jointId JointId) GetLowerLimit() Q

GetLowerLimit reports the lower angular or linear joint limit.

func (JointId) GetMaxForce added in v0.4.0

func (jointId JointId) GetMaxForce() Q

GetMaxForce reports the maximum force of a motor or mouse joint (b2MotorJoint_GetMaxForce, b2MouseJoint_GetMaxForce).

func (JointId) GetMaxLength added in v0.4.0

func (jointId JointId) GetMaxLength() Q

GetMaxLength reports the upper distance limit.

func (JointId) GetMaxMotorForce added in v0.4.0

func (jointId JointId) GetMaxMotorForce() Q

GetMaxMotorForce reports the maximum distance or prismatic motor force.

func (JointId) GetMaxMotorTorque added in v0.4.0

func (jointId JointId) GetMaxMotorTorque() Q

GetMaxMotorTorque reports the maximum revolute or wheel motor torque.

func (JointId) GetMaxTorque added in v0.4.0

func (jointId JointId) GetMaxTorque() Q

GetMaxTorque reports the motor joint's maximum torque (b2MotorJoint_GetMaxTorque).

func (JointId) GetMinLength added in v0.4.0

func (jointId JointId) GetMinLength() Q

GetMinLength reports the lower distance limit.

func (JointId) GetMotorForce added in v0.4.0

func (jointId JointId) GetMotorForce() Q

GetMotorForce reports the last distance or prismatic motor force.

func (JointId) GetMotorSpeed added in v0.4.0

func (jointId JointId) GetMotorSpeed() Q

GetMotorSpeed reports the joint motor speed.

func (JointId) GetMotorTorque added in v0.4.0

func (jointId JointId) GetMotorTorque() Q

GetMotorTorque reports the last revolute or wheel motor torque.

func (JointId) GetReferenceAngle added in v0.4.0

func (jointId JointId) GetReferenceAngle() Q

GetReferenceAngle reports the reference angle in turns (b2Joint_GetReferenceAngle).

func (JointId) GetSpeed added in v0.4.0

func (jointId JointId) GetSpeed() Q

GetSpeed reports the current prismatic translation speed.

func (JointId) GetSpringDampingRatio added in v0.4.0

func (jointId JointId) GetSpringDampingRatio() Q

GetSpringDampingRatio reports the spring damping ratio.

func (JointId) GetSpringHertz added in v0.4.0

func (jointId JointId) GetSpringHertz() Q

GetSpringHertz reports the spring frequency.

func (JointId) GetTarget added in v0.4.0

func (jointId JointId) GetTarget() Vec2

GetTarget reports the mouse joint target (b2MouseJoint_GetTarget).

func (JointId) GetTargetAngle added in v0.4.0

func (jointId JointId) GetTargetAngle() Q

GetTargetAngle reports the revolute spring target angle in turns.

func (JointId) GetTargetTranslation added in v0.4.0

func (jointId JointId) GetTargetTranslation() Q

GetTargetTranslation reports the prismatic spring target translation.

func (JointId) GetTranslation added in v0.4.0

func (jointId JointId) GetTranslation() Q

GetTranslation reports the current translation along the prismatic axis.

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 angular or linear joint limit.

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 joint limit is enabled.

func (JointId) IsMotorEnabled added in v0.4.0

func (jointId JointId) IsMotorEnabled() bool

IsMotorEnabled reports whether the joint 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 weld joint angular damping ratio (b2WeldJoint_SetAngularDampingRatio).

func (JointId) SetAngularHertz added in v0.4.0

func (jointId JointId) SetAngularHertz(hertz Q)

SetAngularHertz changes the weld joint angular frequency (b2WeldJoint_SetAngularHertz).

func (JointId) SetAngularOffset added in v0.4.0

func (jointId JointId) SetAngularOffset(angularOffset Q)

SetAngularOffset changes the motor joint's angular offset in turns (b2MotorJoint_SetAngularOffset).

func (JointId) SetCollideConnected added in v0.4.0

func (jointId JointId) SetCollideConnected(shouldCollide bool)

SetCollideConnected changes whether the attached bodies collide (b2Joint_SetCollideConnected).

Example
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, groundId, boxId := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	def := dbox2d.DefaultDistanceJointDef()
	def.BodyIdA = groundId
	def.BodyIdB = boxId
	def.Length = dbox2d.QFromInt(2)
	jointId := dbox2d.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) SetCorrectionFactor added in v0.4.0

func (jointId JointId) SetCorrectionFactor(correctionFactor Q)

SetCorrectionFactor changes the motor joint's correction factor (b2MotorJoint_SetCorrectionFactor).

func (JointId) SetLength added in v0.4.0

func (jointId JointId) SetLength(length Q)

SetLength changes the distance joint length.

func (JointId) SetLengthRange added in v0.4.0

func (jointId JointId) SetLengthRange(minLength, maxLength Q)

SetLengthRange changes the distance joint limits.

func (JointId) SetLimits added in v0.4.0

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

SetLimits changes the angular or linear joint limits.

func (JointId) SetLinearDampingRatio added in v0.4.0

func (jointId JointId) SetLinearDampingRatio(dampingRatio Q)

SetLinearDampingRatio changes the weld joint linear damping ratio (b2WeldJoint_SetLinearDampingRatio).

func (JointId) SetLinearHertz added in v0.4.0

func (jointId JointId) SetLinearHertz(hertz Q)

SetLinearHertz changes the weld joint linear frequency (b2WeldJoint_SetLinearHertz).

func (JointId) SetLinearOffset added in v0.4.0

func (jointId JointId) SetLinearOffset(linearOffset Vec2)

SetLinearOffset changes the motor joint's linear offset (b2MotorJoint_SetLinearOffset).

func (JointId) SetLocalAnchorA added in v0.4.0

func (jointId JointId) SetLocalAnchorA(localAnchor Vec2)

SetLocalAnchorA changes the local anchor on body A (b2Joint_SetLocalAnchorA).

func (JointId) SetLocalAnchorB added in v0.4.0

func (jointId JointId) SetLocalAnchorB(localAnchor Vec2)

SetLocalAnchorB changes the local anchor on body B (b2Joint_SetLocalAnchorB).

func (JointId) SetLocalAxisA added in v0.4.0

func (jointId JointId) SetLocalAxisA(axis Vec2)

SetLocalAxisA changes the local axis on an applicable joint (b2Joint_SetLocalAxisA).

func (JointId) SetMaxForce added in v0.4.0

func (jointId JointId) SetMaxForce(maxForce Q)

SetMaxForce changes the maximum force of a motor or mouse joint (b2MotorJoint_SetMaxForce, b2MouseJoint_SetMaxForce).

func (JointId) SetMaxMotorForce added in v0.4.0

func (jointId JointId) SetMaxMotorForce(force Q)

SetMaxMotorForce changes the maximum distance or prismatic motor force.

func (JointId) SetMaxMotorTorque added in v0.4.0

func (jointId JointId) SetMaxMotorTorque(torque Q)

SetMaxMotorTorque changes the maximum revolute or wheel motor torque.

func (JointId) SetMaxTorque added in v0.4.0

func (jointId JointId) SetMaxTorque(maxTorque Q)

SetMaxTorque changes the motor joint's maximum torque (b2MotorJoint_SetMaxTorque).

func (JointId) SetMotorSpeed added in v0.4.0

func (jointId JointId) SetMotorSpeed(motorSpeed Q)

SetMotorSpeed changes the joint motor speed. Revolute and wheel values are turns per second (D-004); distance and prismatic values are metres/second.

func (JointId) SetReferenceAngle added in v0.4.0

func (jointId JointId) SetReferenceAngle(angle Q)

SetReferenceAngle changes the reference angle in turns (b2Joint_SetReferenceAngle).

func (JointId) SetSpringDampingRatio added in v0.4.0

func (jointId JointId) SetSpringDampingRatio(dampingRatio Q)

SetSpringDampingRatio changes the spring damping ratio.

func (JointId) SetSpringHertz added in v0.4.0

func (jointId JointId) SetSpringHertz(hertz Q)

SetSpringHertz changes the spring frequency.

func (JointId) SetTarget added in v0.4.0

func (jointId JointId) SetTarget(target Vec2)

SetTarget changes the mouse joint target (b2MouseJoint_SetTarget).

func (JointId) SetTargetAngle added in v0.4.0

func (jointId JointId) SetTargetAngle(angle Q)

SetTargetAngle changes the revolute spring target angle in turns.

func (JointId) SetTargetTranslation added in v0.4.0

func (jointId JointId) SetTargetTranslation(translation Q)

SetTargetTranslation changes the prismatic spring target translation.

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 JointType = iota
	FilterJoint
	MotorJoint
	MouseJoint
	PrismaticJoint
	RevoluteJoint
	WeldJoint
	WheelJoint
)

Joint types. upstream b2JointType

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.

func CollideCapsuleAndCircle added in v0.2.0

func CollideCapsuleAndCircle(capsuleA *Capsule, xfA Transform, circleB *Circle, xfB Transform) Manifold

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, xfA Transform, capsuleB *Capsule, xfB Transform) Manifold

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, xfA Transform, capsuleB *Capsule, xfB Transform, cache *SimplexCache) Manifold

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, xfA Transform, circleB *Circle, xfB Transform) Manifold

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, xfA Transform, polygonB *Polygon, xfB Transform, cache *SimplexCache) Manifold

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, xfA Transform, circleB *Circle, xfB Transform) Manifold

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, xfA Transform, capsuleB *Capsule, xfB Transform) Manifold

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, xfA Transform, circleB *Circle, xfB Transform) Manifold

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, xfA Transform, polygonB *Polygon, xfB Transform) Manifold

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, xfA Transform, capsuleB *Capsule, xfB Transform) Manifold

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, xfA Transform, circleB *Circle, xfB Transform) Manifold

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, xfA Transform, polygonB *Polygon, xfB Transform) Manifold

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

type ManifoldPoint

type ManifoldPoint struct {
	// Point is the contact point in world space. Use it for debugging only,
	// because it loses precision far from the origin.
	Point Vec2

	// AnchorA is the contact point relative to the origin of shape A, in
	// world space. Inside the solver it is relative to the center of mass.
	AnchorA Vec2

	// AnchorB is the contact point relative to the origin of shape B, in
	// world space. Inside the solver it is relative to the center of mass.
	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.
	NormalVelocity 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 local origin.
	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 divides by the determinant, because a fixed-point reciprocal loses the precision that the division keeps. See DIVERGENCES.md.

func Mat22Zero

func Mat22Zero() Mat22

Mat22Zero returns the zero matrix.

type MotorJointDef added in v0.3.0

type MotorJointDef struct {
	// The first attached body.
	BodyIdA BodyId

	// The second attached body.
	BodyIdB BodyId

	// Position of body B minus the position of body A, in the frame of
	// body A, in meters.
	LinearOffset Vec2

	// The angle of body B minus the angle of body A, in turns.
	AngularOffset Q

	// The maximum motor force in newtons.
	MaxForce Q

	// The maximum motor torque in newton-meters.
	MaxTorque Q

	// Position correction factor in the range [0, 1].
	CorrectionFactor Q

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

	// Application data attached to the joint.
	UserData any
	// contains filtered or unexported fields
}

MotorJointDef configures a motor joint: it drives the relative transform of two bodies toward an offset. Initialize it with DefaultMotorJointDef.

func DefaultMotorJointDef added in v0.3.0

func DefaultMotorJointDef() MotorJointDef

DefaultMotorJointDef returns the default motor joint definition.

type MouseJointDef added in v0.3.0

type MouseJointDef struct {
	// The first attached body. It is unused here, but it plays a role in
	// the solver order.
	BodyIdA BodyId

	// The second attached body.
	BodyIdB BodyId

	// The initial target point in world space.
	Target Vec2

	// Stiffness in cycles per second.
	Hertz Q

	// Damping ratio, non-dimensional.
	DampingRatio Q

	// Maximum force, usually in newtons.
	MaxForce Q

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

	// Application data attached to the joint.
	UserData any
	// contains filtered or unexported fields
}

MouseJointDef configures a mouse joint: it drags a point on body B toward a world target with a spring. Body A is a ground reference and gets no reaction. Initialize it with DefaultMouseJointDef.

func DefaultMouseJointDef added in v0.3.0

func DefaultMouseJointDef() MouseJointDef

DefaultMouseJointDef returns the default mouse 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
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

func main() {
	// A push limit of dbox2d.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 := []dbox2d.CollisionPlane{{
		Plane:     dbox2d.Plane{Normal: dbox2d.Vec2{Y: dbox2d.QOne()}},
		PushLimit: dbox2d.Huge,
	}}

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

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

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 PreSolveFcn added in v0.4.0

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

PreSolveFcn inspects a contact manifold before the solver runs. It corresponds to b2PreSolveFcn; return false to disable the contact this step. 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 {
	// The first attached body.
	BodyIdA BodyId

	// The second attached body.
	BodyIdB BodyId

	// The local anchor point relative to the origin of body A.
	LocalAnchorA Vec2

	// The local anchor point relative to the origin of body B.
	LocalAnchorB Vec2

	// The local translation unit axis in body A.
	LocalAxisA Vec2

	// The constrained angle between the bodies: angle of B minus angle of
	// A, in turns.
	ReferenceAngle Q

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

	// 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

	// 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

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

	// Application data attached to the joint.
	UserData any
	// contains filtered or unexported fields
}

PrismaticJointDef configures a prismatic joint: body B translates along an axis fixed in body A, with no relative rotation. 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
	MergeIslands        float64
	PrepareStages       float64
	SolveConstraints    float64
	PrepareConstraints  float64
	IntegrateVelocities float64
	WarmStart           float64
	SolveImpulses       float64
	IntegratePositions  float64
	RelaxImpulses       float64
	ApplyRestitution    float64
	StoreImpulses       float64
	SplitIslands        float64
	Transforms          float64
	HitEvents           float64
	Refit               float64
	Bullets             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 fattens the bounds in the dynamic tree, in meters. A proxy that moves less than the 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 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 converts a presentation value, such as a camera value, to a scalar. It must never be used by simulation code.

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(b, a Rot) Q

RelativeAngle returns the angle of b relative to a, in turns.

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

Sqrt returns the square root, rounded once to float32.

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      Vec2
	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 RestitutionCallback added in v0.4.0

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

RestitutionCallback mixes the restitution values of two shapes.

type RevoluteJointDef added in v0.3.0

type RevoluteJointDef struct {
	// The first attached body.
	BodyIdA BodyId

	// The second attached body.
	BodyIdB BodyId

	// The local anchor point relative to the origin of body A.
	LocalAnchorA Vec2

	// The local anchor point relative to the origin of body B.
	LocalAnchorB Vec2

	// The angle of body B minus the angle of body A in the reference
	// state, in turns. It is clamped to [-0.5, 0.5] turns.
	ReferenceAngle Q

	// The target angle for the joint in turns. The spring-damper pulls
	// 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. Must be greater than
	// -0.495 turns.
	LowerAngle Q

	// The upper angle for the joint limit in turns. Must be less than
	// 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

	// DrawSize scales the debug draw of the joint.
	DrawSize Q

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

	// Application data attached to the joint.
	UserData any
	// contains filtered or unexported fields
}

RevoluteJointDef configures a revolute joint: a shared anchor point 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 MakeRot

func MakeRot(t Q) Rot

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

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 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 SegmentDistance added in v0.2.0

func SegmentDistance(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

	// TransformA is the world transform of shape A.
	TransformA Transform

	// TransformB is the world transform of shape B.
	TransformB Transform

	// TranslationB is the translation of shape B.
	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 ShapeCast. 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

	// 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 becomes a circle at its midpoint.

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) 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) 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) GetAABB added in v0.4.0

func (shapeId ShapeId) GetAABB() AABB

GetAABB returns the shape's current axis-aligned bounds. It corresponds to b2Shape_GetAABB.

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) 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 Vec2) Vec2

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) GetMassData added in v0.4.0

func (shapeId ShapeId) GetMassData() MassData

GetMassData returns the shape mass, centroid and rotational inertia. It corresponds to b2Shape_GetMassData.

func (ShapeId) GetMaterial added in v0.4.0

func (shapeId ShapeId) GetMaterial() int

GetMaterial returns the shape user material id. It corresponds to b2Shape_GetMaterial.

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) GetSensorOverlaps added in v0.4.0

func (shapeId ShapeId) GetSensorOverlaps(overlaps []ShapeId) int

GetSensorOverlaps fills overlaps with current sensor overlaps. It corresponds to b2Shape_GetSensorOverlaps 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) 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) RayCast added in v0.4.0

func (shapeId ShapeId) RayCast(input *RayCastInput) CastOutput

RayCast casts a world-space ray against the shape. It corresponds to b2Shape_RayCast.

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) 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) SetMaterial added in v0.4.0

func (shapeId ShapeId) SetMaterial(material int)

SetMaterial sets the shape user material id. It corresponds to b2Shape_SetMaterial.

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) TestPoint added in v0.4.0

func (shapeId ShapeId) TestPoint(point Vec2) 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 int

	// 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

	// Fraction is the sweep time of the collision.
	Fraction Q
}

TOIOutput is the output of TimeOfImpact. It corresponds to b2TOIOutput in include/box2d/collision.h.

func TimeOfImpact added in v0.3.0

func TimeOfImpact(input *TOIInput) TOIOutput

TimeOfImpact 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 b2TimeOfImpact 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 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 TransformIdentity

func TransformIdentity() Transform

TransformIdentity returns the transform that moves and rotates nothing.

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 TreeShapeCastCallbackFcn added in v0.7.0

type TreeShapeCastCallbackFcn func(input *ShapeCastInput, proxyId int, userData uint64) Q

TreeShapeCastCallbackFcn receives each proxy whose box the swept proxy reaches. Its return value works like TreeRayCastCallbackFcn's. It corresponds to b2TreeShapeCastCallbackFcn 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 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 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 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. The zero vector returns the zero vector.

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 {
	// The first attached body.
	BodyIdA BodyId

	// The second attached body.
	BodyIdB BodyId

	// The local anchor point relative to the origin of body A.
	LocalAnchorA Vec2

	// The local anchor point relative to the origin of body B.
	LocalAnchorB Vec2

	// The angle of body B minus the angle of body A in the reference
	// state, in turns.
	ReferenceAngle Q

	// 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.
	LinearDampingRatio Q

	// Angular damping ratio, non-dimensional.
	AngularDampingRatio Q

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

	// Application data attached to the joint.
	UserData any
	// contains filtered or unexported fields
}

WeldJointDef configures a weld joint: it holds the relative transform of two bodies, rigidly or with a spring. 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 {
	// The first attached body.
	BodyIdA BodyId

	// The second attached body.
	BodyIdB BodyId

	// The local anchor point relative to the origin of body A.
	LocalAnchorA Vec2

	// The local anchor point relative to the origin of body B.
	LocalAnchorB Vec2

	// The local translation unit axis in body A.
	LocalAxisA Vec2

	// 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

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

	// Application data attached to the joint.
	UserData any
	// contains filtered or unexported fields
}

WheelJointDef configures a wheel joint: body B rotates freely about a point on an axis fixed in body A, with a suspension spring along the axis. Initialize it with DefaultWheelJointDef.

func DefaultWheelJointDef added in v0.3.0

func DefaultWheelJointDef() WheelJointDef

DefaultWheelJointDef returns the default wheel joint definition.

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

	// 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 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(mover *Capsule, translation Vec2, filter QueryFilter) Q

CastMover sweeps a capsule 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, 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, 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(proxy *ShapeProxy, translation Vec2, filter QueryFilter, fcn CastResultFcn) TreeStats

CastShape sweeps a proxy 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(mover *Capsule, filter QueryFilter, fcn PlaneResultFcn)

CollideMover reports the collision plane of every shape the mover capsule touches, tree by tree. 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 walks the world and invokes the callbacks selected by draw's flags.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, _, _ := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	// Every callback defaults to a no-op; wire up only the shapes callbacks
	// used here and count how many shapes the world hands back.
	shapeCount := 0
	draw := dbox2d.DefaultDebugDraw()
	draw.DrawShapes = true
	draw.DrawSolidPolygon = func(dbox2d.Transform, []dbox2d.Vec2, dbox2d.Q, dbox2d.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) 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) EnableSpeculative added in v0.4.0

func (worldId WorldId) EnableSpeculative(flag bool)

EnableSpeculative changes speculative collision handling. It corresponds to b2World_EnableSpeculative 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
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, _, boxId := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	def := dbox2d.DefaultExplosionDef()
	def.Position = boxId.GetPosition()
	def.Radius = dbox2d.QFromInt(4)
	def.Falloff = dbox2d.QFromInt(2)
	def.ImpulsePerLength = dbox2d.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) 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) 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) GetMaximumLinearSpeed added in v0.4.0

func (worldId WorldId) GetMaximumLinearSpeed() Q

GetMaximumLinearSpeed returns the velocity cap. It corresponds to b2World_GetMaximumLinearSpeed in src/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) 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
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

func main() {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)
	defer dbox2d.DestroyWorld(worldId)

	sensorDef := dbox2d.DefaultBodyDef()
	sensorBodyId := dbox2d.CreateBody(worldId, &sensorDef)
	sensorShapeDef := dbox2d.DefaultShapeDef()
	sensorShapeDef.IsSensor = true
	sensorShapeDef.EnableSensorEvents = true
	sensorBox := dbox2d.MakeBox(dbox2d.QFromInt(2), dbox2d.QFromInt(2))
	dbox2d.CreatePolygonShape(sensorBodyId, &sensorShapeDef, &sensorBox)

	visitorDef := dbox2d.DefaultBodyDef()
	visitorDef.Type = dbox2d.DynamicBody
	visitorBodyId := dbox2d.CreateBody(worldId, &visitorDef)
	visitorShapeDef := dbox2d.DefaultShapeDef()
	visitorShapeDef.EnableSensorEvents = true
	visitorBox := dbox2d.MakeSquare(dbox2d.QHalf())
	visitorShapeId := dbox2d.CreatePolygonShape(visitorBodyId, &visitorShapeDef, &visitorBox)

	dt := dbox2d.QOne().Div(dbox2d.QFromInt(60))
	worldId.Step(dt, 4)
	begin := worldId.GetSensorEvents().BeginEvents
	fmt.Println(len(begin) == 1 && begin[0].VisitorShapeId == visitorShapeId)

	dbox2d.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) 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) 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(aabb AABB, filter QueryFilter, fcn OverlapResultFcn) TreeStats

OverlapAABB reports every shape whose fat bounds overlap the box 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(proxy *ShapeProxy, filter QueryFilter, fcn OverlapResultFcn) TreeStats

OverlapShape reports every shape that overlaps the proxy 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) 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
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, groundId, boxId := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	// Rejecting every pair keeps the box from ever touching the ground.
	worldId.SetCustomFilterCallback(func(dbox2d.ShapeId, dbox2d.ShapeId) bool {
		return false
	})

	dt := dbox2d.QOne().Div(dbox2d.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
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

func main() {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)
	defer dbox2d.DestroyWorld(worldId)

	worldId.SetFrictionCallback(func(frictionA dbox2d.Q, _ int, frictionB dbox2d.Q, _ int) dbox2d.Q {
		return frictionA.Add(frictionB).Div(dbox2d.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) SetMaximumLinearSpeed added in v0.4.0

func (worldId WorldId) SetMaximumLinearSpeed(maximumLinearSpeed Q)

SetMaximumLinearSpeed changes the velocity cap. It corresponds to b2World_SetMaximumLinearSpeed in src/world.c.

func (WorldId) SetPreSolveCallback added in v0.4.0

func (worldId WorldId) SetPreSolveCallback(fcn PreSolveFcn)

SetPreSolveCallback sets the callback run after a contact's manifold is updated, before the solver sees it. It corresponds to b2World_SetPreSolveCallback in src/world.c.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/dbox2d"
)

// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
	worldDef := dbox2d.DefaultWorldDef()
	worldId := dbox2d.CreateWorld(&worldDef)

	groundDef := dbox2d.DefaultBodyDef()
	groundId := dbox2d.CreateBody(worldId, &groundDef)

	boxDef := dbox2d.DefaultBodyDef()
	boxDef.Type = dbox2d.DynamicBody
	boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
	boxId := dbox2d.CreateBody(worldId, &boxDef)
	shapeDef := dbox2d.DefaultShapeDef()
	box := dbox2d.MakeSquare(dbox2d.QHalf())
	dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)

	return worldId, groundId, boxId
}

func main() {
	worldId, _, boxId := exampleWorld()
	defer dbox2d.DestroyWorld(worldId)

	// Returning false disables the contact for the step, so the box
	// keeps falling through the ground instead of resting on it.
	worldId.SetPreSolveCallback(func(dbox2d.ShapeId, dbox2d.ShapeId, *dbox2d.Manifold) bool {
		return false
	})

	startY := boxId.GetPosition().Y
	dt := dbox2d.QOne().Div(dbox2d.QFromInt(60))
	for range 60 {
		worldId.Step(dt, 4)
	}

	fmt.Println(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) 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) 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.

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.
tools
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