b2

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: Zlib Imports: 3 Imported by: 0

README

b2

Go port of Box2D 2.4.1

The API has been simplified.

  • b2BodyDef -> BodyDef

Documentation

Original C++ documentation https://box2d.org/doc_version_2_4/

Documentation

Index

Constants

View Source
const (
	BodyIslandFlag        uint32 = 0x0001
	BodyAwakeFlag         uint32 = 0x0002
	BodyAutoSleepFlag     uint32 = 0x0004
	BodyBulletFlag        uint32 = 0x0008
	BodyFixedRotationFlag uint32 = 0x0010
	BodyEnabledFlag       uint32 = 0x0020
	BodyToiFlag           uint32 = 0x0040
)
View Source
const (
	ContactIslandFlag    uint32 = 0x0001
	ContactTouchingFlag  uint32 = 0x0002
	ContactEnabledFlag   uint32 = 0x0004
	ContactFilterFlag    uint32 = 0x0008
	ContactBulletHitFlag uint32 = 0x0010
	ContactToiFlag       uint32 = 0x0020
)
View Source
const Debug = false

@port(OK)

View Source
const DebugSolver = 0

Solver debugging is normally disabled because the block solver sometimes has to deal with a poorly conditioned effective mass matrix.

View Source
const E_nullProxy = -1
View Source
const LengthUnitsPerMeter float64 = 1.0

You can use this to change the length scale used by your game. For example for inches you could use 39.4

Default value 1.0
View Source
const MaxPolygonVertices int = 8

The maximum number of vertices on a convex polygon. You cannot increase this too much because b2BlockAllocator has a maximum object size.

Default value is 8

View Source
const (

	// The radius of the polygon/edge shape skin. This should not be modified. Making
	// this smaller means polygons will have an insufficient buffer for continuous collision.
	// Making it larger may create artifacts for vertex collision.
	PolygonRadius = (2.0 * linearSlop)
)

Global tuning constants based on meters-kilograms-seconds (MKS) units.

Collision

Variables

View Source
var BendingModel = struct {
	SpringAngleBendingModel uint8
	PbdAngleBendingModel    uint8
	XpbdAngleBendingModel   uint8
	PbdDistanceBendingModel uint8
	PbdHeightBendingModel   uint8
	PbdTriangleBendingModel uint8
}{
	SpringAngleBendingModel: 1,
	PbdAngleBendingModel:    2,
	XpbdAngleBendingModel:   3,
	PbdDistanceBendingModel: 4,
	PbdHeightBendingModel:   5,
	PbdTriangleBendingModel: 6,
}
View Source
var ContactFeature_Type = struct {
	E_vertex uint8
	E_face   uint8
}{
	E_vertex: 0,
	E_face:   1,
}
View Source
var EPAxis_Type = struct {
	E_unknown uint8
	E_edgeA   uint8
	E_edgeB   uint8
}{
	E_unknown: 0,
	E_edgeA:   1,
	E_edgeB:   2,
}

This structure is used to keep track of the best separating axis.

View Source
var PointState = struct {
	NullState    uint8 // point does not exist
	AddState     uint8 // point was added in the update
	PersistState uint8 // point persisted across the update
	RemoveState  uint8 // point was removed in the update
}{
	NullState:    0,
	AddState:     1,
	PersistState: 2,
	RemoveState:  3,
}
View Source
var SeparationFunction_Type = struct {
	E_points uint8
	E_faceA  uint8
	E_faceB  uint8
}{
	E_points: 0,
	E_faceA:  1,
	E_faceB:  2,
}
View Source
var StretchingModel = struct {
	PbdStretchingModel  uint8
	XpbdStretchingModel uint8
}{
	PbdStretchingModel:  1,
	XpbdStretchingModel: 2,
}

Functions

func AbsInt

func AbsInt(v int) int

func AddType

func AddType(createFcn ContactCreateFcn, destroyFcn ContactDestroyFcn, type1, type2 ShapeType)

func AngularStiffness

func AngularStiffness(stiffness *float64, damping *float64, frequencyHertz float64, dampingRatio float64, bodyA *Body, bodyB *Body)

Utility to compute rotational stiffness values frequency and damping ratio

func ChainAndCircleContact_Destroy

func ChainAndCircleContact_Destroy(contact IContact)

func ChainAndPolygonContact_Destroy

func ChainAndPolygonContact_Destroy(contact IContact)

func CircleContact_Destroy

func CircleContact_Destroy(contact IContact)

func ClipSegmentToLine

func ClipSegmentToLine(vOut []ClipVertex, vIn []ClipVertex, normal Vec2, offset float64, vertexIndexA int) int

Sutherland-Hodgman clipping.

func CollideEdgeAndPolygon

func CollideEdgeAndPolygon(manifold *Manifold, edgeA *EdgeShape, xfA Transform, polygonB *PolygonShape, xfB Transform)

Compute the collision manifold between an edge and a polygon.

func ComputeEdgeSeparation

func ComputeEdgeSeparation(polygonB tempPolygon, v1 Vec2, normal1 Vec2) ePAxis

func ComputePolygonSeparation

func ComputePolygonSeparation(polygonB tempPolygon, v1 Vec2, v2 Vec2) ePAxis

func ContactDestroy

func ContactDestroy(contact IContact)

func ContactInitializeRegisters

func ContactInitializeRegisters()

func ContactUpdate

func ContactUpdate(contact IContact, listener IContactListener)

Update the contact manifold and touching status. Note: do not assume the fixture AABBs are overlapping or are valid.

func Distance

func Distance(output *DistanceOutput, cache *simplexCache, input *DistanceInput)

func EdgeAndCircleContact_Destroy

func EdgeAndCircleContact_Destroy(contact IContact)

func EdgeAndPolygonContact_Destroy

func EdgeAndPolygonContact_Destroy(contact IContact)

func FloatClamp

func FloatClamp(a, low, high float64) float64

func GetPointStates

func GetPointStates(state1 *[maxManifoldPoints]uint8, state2 *[maxManifoldPoints]uint8, manifold1 Manifold, manifold2 Manifold)

func InvSqrt

func InvSqrt(x float64) float64

This is a approximate yet fast inverse square-root.

func IsPowerOfTwo

func IsPowerOfTwo(x uint32) bool

func IsProjectedPointOnLineSegment

func IsProjectedPointOnLineSegment(v1 Vec2, v2 Vec2, p Vec2) bool

Check if the projected testpoint onto the line is on the line segment

func IsValid

func IsValid(x float64) bool

This function is used to ensure that a floating point number is not a NaN or infinity.

func JointDestroy

func JointDestroy(joint IJoint)

func LinearStiffness

func LinearStiffness(stiffness *float64, damping *float64, frequencyHertz float64, dampingRatio float64, bodyA *Body, bodyB *Body)

Utility to compute linear stiffness values from frequency and damping ratio

func MakeSimplexCache

func MakeSimplexCache() simplexCache

func MixFriction

func MixFriction(friction1, friction2 float64) float64

Friction mixing law. The idea is to allow either fixture to drive the friction to zero. For example, anything slides on ice.

func MixRestitution

func MixRestitution(restitution1, restitution2 float64) float64

Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. For example, a superball bounces on anything.

func MixRestitutionThreshold

func MixRestitutionThreshold(threshold1, threshold2 float64) float64

Restitution mixing law. This picks the lowest value.

func NextPowerOfTwo

func NextPowerOfTwo(x uint32) uint32

"Next Largest Power of 2 Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next largest power of 2. For a 32-bit value:"

func PolygonAndCircleContact_Destroy

func PolygonAndCircleContact_Destroy(contact IContact)

func PolygonContact_Destroy

func PolygonContact_Destroy(contact IContact)

func ShapeCast

func ShapeCast(output *ShapeCastOutput, input *ShapeCastInput) bool

GJK-raycast Algorithm by Gino van den Bergen. "Smooth Mesh Contacts with GJK" in Game Physics Pearls. 2010

Perform a linear shape cast of shape B moving and shape A fixed. Determines the hit point, normal, and translation fraction. @returns true if hit, false if there is no hit or an initial overlap

func TestOverlapBoundingBoxes

func TestOverlapBoundingBoxes(a, b AABB) bool

func TestOverlapShapes

func TestOverlapShapes(shapeA IShape, indexA int, shapeB IShape, indexB int, xfA Transform, xfB Transform) bool

func TimeOfImpact

func TimeOfImpact(output *TOIOutput, input *TOIInput)

Compute the upper bound on time before two shapes penetrate. Time is represented as a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate, non-tunneling collision. If you change the time interval, you should call this function again. Note: use b2Distance to compute the contact point and normal at the time of impact. CCD via the local separating axis method. This seeks progression by computing the largest time at which separation is maintained.

func ValidateHull

func ValidateHull(hull *Hull) bool

This determines if a hull is valid. Checks for: - convexity - collinear points This is expensive and should not be called at runtime.

func Vec2Cross

func Vec2Cross(a, b Vec2) float64

Perform the cross product on two vectors. In 2D this produces a scalar.

func Vec2Distance

func Vec2Distance(a, b Vec2) float64

func Vec2DistanceSquared

func Vec2DistanceSquared(a, b Vec2) float64

func Vec2Dot

func Vec2Dot(a, b Vec2) float64

Perform the dot product on two vectors.

func Vec2Equals

func Vec2Equals(a, b Vec2) bool

func Vec2NotEquals

func Vec2NotEquals(a, b Vec2) bool

func Vec3Dot

func Vec3Dot(a, b Vec3) float64

Perform the dot product on two vectors.

Types

type AABB

type AABB struct {
	LowerBound Vec2 // the lower vertex
	UpperBound Vec2 // the upper vertex
}

An axis aligned bounding box.

func (*AABB) CombineInPlace

func (bb *AABB) CombineInPlace(aabb AABB)

Combine an AABB into this one.

func (*AABB) CombineTwoInPlace

func (bb *AABB) CombineTwoInPlace(aabb1, aabb2 AABB)

Combine two AABBs into this one.

func (AABB) Contains

func (bb AABB) Contains(aabb AABB) bool

Does this aabb contain the provided AABB.

func (AABB) GetCenter

func (bb AABB) GetCenter() Vec2

Get the center of the AABB.

func (AABB) GetExtents

func (bb AABB) GetExtents() Vec2

Get the extents of the AABB (half-widths).

func (AABB) GetPerimeter

func (bb AABB) GetPerimeter() float64

Get the perimeter length

func (AABB) IsValid

func (bb AABB) IsValid() bool

func (AABB) RayCast

func (bb AABB) RayCast(output *RayCastOutput, input RayCastInput) bool

From Real-time Collision Detection, p179.

type Body

type Body struct {
	UserData any
	// contains filtered or unexported fields
}

func NewBody

func NewBody(bd *BodyDef, world *World) *Body

func (*Body) Advance

func (body *Body) Advance(alpha float64)

func (Body) Angle

func (body Body) Angle() float64

func (*Body) ApplyAngularImpulse

func (body *Body) ApplyAngularImpulse(impulse float64, wake bool)

func (*Body) ApplyForce

func (body *Body) ApplyForce(force Vec2, point Vec2, wake bool)

func (*Body) ApplyForceToCenter

func (body *Body) ApplyForceToCenter(force Vec2, wake bool)

func (*Body) ApplyLinearImpulse

func (body *Body) ApplyLinearImpulse(impulse Vec2, point Vec2, wake bool)

func (*Body) ApplyLinearImpulseToCenter

func (body *Body) ApplyLinearImpulseToCenter(impulse Vec2, wake bool)

func (*Body) ApplyTorque

func (body *Body) ApplyTorque(torque float64, wake bool)

func (Body) ContactList

func (body Body) ContactList() *ContactEdge

func (*Body) CreateFixture

func (body *Body) CreateFixture(shape IShape, density float64) *Fixture

func (*Body) CreateFixtureFromDef

func (body *Body) CreateFixtureFromDef(def *FixtureDef) *Fixture

func (*Body) DestroyFixture

func (body *Body) DestroyFixture(fixture *Fixture)

func (*Body) Dump

func (body *Body) Dump()

func (Body) FixtureList

func (body Body) FixtureList() *Fixture

func (Body) GetAngularDamping

func (body Body) GetAngularDamping() float64

func (Body) GetAngularVelocity

func (body Body) GetAngularVelocity() float64

func (Body) GetWorld

func (body Body) GetWorld() *World

func (Body) GravityScale

func (body Body) GravityScale() float64

func (Body) Inertia

func (body Body) Inertia() float64

func (Body) IsAwake

func (body Body) IsAwake() bool

func (Body) IsBullet

func (body Body) IsBullet() bool

func (Body) IsDynamic

func (body Body) IsDynamic() bool

func (Body) IsEnabled

func (body Body) IsEnabled() bool

func (Body) IsFixedRotation

func (body Body) IsFixedRotation() bool

func (Body) IsKinematic

func (body Body) IsKinematic() bool

func (Body) IsSleepingAllowed

func (body Body) IsSleepingAllowed() bool

func (Body) IsStatic

func (body Body) IsStatic() bool

func (Body) JointList

func (body Body) JointList() *JointEdge

func (Body) LinearDamping

func (body Body) LinearDamping() float64

func (Body) LinearVelocity

func (body Body) LinearVelocity() Vec2

func (Body) LinearVelocityFromLocalPoint

func (body Body) LinearVelocityFromLocalPoint(localPoint Vec2) Vec2

func (Body) LinearVelocityFromWorldPoint

func (body Body) LinearVelocityFromWorldPoint(worldPoint Vec2) Vec2

func (Body) LocalCenter

func (body Body) LocalCenter() Vec2

func (Body) LocalPoint

func (body Body) LocalPoint(worldPoint Vec2) Vec2

Gets a local point relative to the body's origin given a world point.

func (Body) LocalVector

func (body Body) LocalVector(worldVector Vec2) Vec2

func (Body) Mass

func (body Body) Mass() float64

func (Body) MassData

func (body Body) MassData() MassData

func (Body) Next

func (body Body) Next() *Body

func (Body) Position

func (body Body) Position() Vec2

func (*Body) ResetMassData

func (body *Body) ResetMassData()

func (*Body) SetActive

func (body *Body) SetActive(flag bool)

func (*Body) SetAngularDamping

func (body *Body) SetAngularDamping(angularDamping float64)

func (*Body) SetAngularVelocity

func (body *Body) SetAngularVelocity(w float64)

func (*Body) SetAwake

func (body *Body) SetAwake(flag bool)

func (*Body) SetBullet

func (body *Body) SetBullet(flag bool)

func (*Body) SetFixedRotation

func (body *Body) SetFixedRotation(flag bool)

func (*Body) SetGravityScale

func (body *Body) SetGravityScale(scale float64)

func (*Body) SetLinearDamping

func (body *Body) SetLinearDamping(linearDamping float64)

func (*Body) SetLinearVelocity

func (body *Body) SetLinearVelocity(v Vec2)

func (*Body) SetMassData

func (body *Body) SetMassData(massData *MassData)

func (*Body) SetSleepingAllowed

func (body *Body) SetSleepingAllowed(flag bool)

func (*Body) SetTransform

func (body *Body) SetTransform(position Vec2, angle float64)

func (*Body) SetType

func (body *Body) SetType(bt BodyType)

func (Body) ShouldCollide

func (body Body) ShouldCollide(other *Body) bool

func (*Body) SynchronizeFixtures

func (body *Body) SynchronizeFixtures()

func (*Body) SynchronizeTransform

func (body *Body) SynchronizeTransform()

func (Body) Transform

func (body Body) Transform() Transform

func (Body) Type

func (body Body) Type() BodyType

func (Body) WorldCenter

func (body Body) WorldCenter() Vec2

func (Body) WorldPoint

func (body Body) WorldPoint(localPoint Vec2) Vec2

func (Body) WorldVector

func (body Body) WorldVector(localVector Vec2) Vec2

type BodyDef

type BodyDef struct {

	// Note: if a dynamic body would have zero mass, the mass is set to one.
	Type BodyType

	// The world position of the body. Avoid creating bodies at the origin
	// since this can lead to many overlapping shapes.
	Position Vec2

	// The linear velocity of the body's origin in world co-ordinates.
	LinearVelocity Vec2

	// The world angle of the body in radians.
	Angle float64

	// The angular velocity of the body.
	AngularVelocity float64

	// Linear damping is use to reduce the linear velocity. The damping parameter
	// can be larger than 1.0 but the damping effect becomes sensitive to the
	// time step when the damping parameter is large.
	// Units are 1/time
	LinearDamping float64

	// Angular damping is use to reduce the angular velocity. The damping parameter
	// can be larger than 1.0 but the damping effect becomes sensitive to the
	// time step when the damping parameter is large.
	// Units are 1/time
	AngularDamping float64

	// Set this flag to false if this body should never fall asleep. Note that
	// this increases CPU usage.
	AllowSleep bool

	// Is this body initially awake or sleeping?
	Awake bool

	// Should this body be prevented from rotating? Useful for characters.
	FixedRotation bool

	// Is this a fast moving body that should be prevented from tunneling through
	// other moving bodies? Note that all bodies are prevented from tunneling through
	// kinematic and static bodies. This setting is only considered on dynamic bodies.
	// @warning You should use this flag sparingly since it increases processing time.
	Bullet bool

	// Does this body start out enabled?
	Enabled bool

	// Scale the gravity applied to this body.
	GravityScale float64

	// Use this to store application specific body data.
	UserData any
}

A body definition holds all the data needed to construct a rigid body. You can safely re-use body definitions. Shapes are added to a body after construction.

func DefaultBodyDef

func DefaultBodyDef() BodyDef

This constructor sets the body definition default values.

func NewBodyDef

func NewBodyDef() *BodyDef

type BodyType

type BodyType uint8
const (
	// Zero mass, zero velocity, may be manually moved
	Static BodyType = iota
	// Zero mass, non-zero velocity set by user, moved by solver
	Kinematic
	// Positive mass, non-zero velocity determined by forces, moved by solver
	Dynamic
)

type BroadPhase

type BroadPhase struct {
	M_tree DynamicTree

	M_proxyCount int

	M_moveBuffer   []int
	M_moveCapacity int
	M_moveCount    int

	M_pairBuffer   []Pair
	M_pairCapacity int
	M_pairCount    int

	M_queryProxyId int
}

func MakeBroadPhase

func MakeBroadPhase() BroadPhase

func (*BroadPhase) BufferMove

func (bp *BroadPhase) BufferMove(proxyId int)

func (*BroadPhase) CreateProxy

func (bp *BroadPhase) CreateProxy(aabb AABB, userData any) int

func (*BroadPhase) DestroyProxy

func (bp *BroadPhase) DestroyProxy(proxyId int)

func (BroadPhase) GetFatAABB

func (bp BroadPhase) GetFatAABB(proxyId int) AABB

func (BroadPhase) GetProxyCount

func (bp BroadPhase) GetProxyCount() int

func (BroadPhase) GetTreeBalance

func (bp BroadPhase) GetTreeBalance() int

func (BroadPhase) GetTreeHeight

func (bp BroadPhase) GetTreeHeight() int

func (BroadPhase) GetTreeQuality

func (bp BroadPhase) GetTreeQuality() float64

func (BroadPhase) GetUserData

func (bp BroadPhase) GetUserData(proxyId int) any

func (*BroadPhase) MoveProxy

func (bp *BroadPhase) MoveProxy(proxyId int, aabb AABB, displacement Vec2)

func (*BroadPhase) Query

func (bp *BroadPhase) Query(callback TreeQueryCallback, aabb AABB)

func (*BroadPhase) QueryCallback

func (bp *BroadPhase) QueryCallback(proxyId int) bool

This is called from b2DynamicTree::Query when we are gathering pairs.

func (*BroadPhase) RayCast

func (bp *BroadPhase) RayCast(callback TreeRayCastCallback, input RayCastInput)

func (*BroadPhase) ShiftOrigin

func (bp *BroadPhase) ShiftOrigin(newOrigin Vec2)

func (BroadPhase) TestOverlap

func (bp BroadPhase) TestOverlap(proxyIdA int, proxyIdB int) bool

func (*BroadPhase) TouchProxy

func (bp *BroadPhase) TouchProxy(proxyId int)

func (*BroadPhase) UnBufferMove

func (bp *BroadPhase) UnBufferMove(proxyId int)

func (*BroadPhase) UpdatePairs

func (bp *BroadPhase) UpdatePairs(addPairCallback BroadPhaseAddPairCallback)

type BroadPhaseAddPairCallback

type BroadPhaseAddPairCallback func(userDataA any, userDataB any)

type BroadPhaseQueryCallback

type BroadPhaseQueryCallback func(fixture *Fixture) bool

type ChainAndCircleContact

type ChainAndCircleContact struct {
	Contact
}

func (*ChainAndCircleContact) Evaluate

func (contact *ChainAndCircleContact) Evaluate(manifold *Manifold, xfA Transform, xfB Transform)

type ChainAndPolygonContact

type ChainAndPolygonContact struct {
	Contact
}

func (*ChainAndPolygonContact) Evaluate

func (contact *ChainAndPolygonContact) Evaluate(manifold *Manifold, xfA Transform, xfB Transform)

type ChainShape

type ChainShape struct {
	Shape

	// The vertices. Owned by this class.
	M_vertices []Vec2

	// The vertex count.
	M_count int

	M_prevVertex Vec2
	M_nextVertex Vec2
}

A circle shape.

func MakeChainShape

func MakeChainShape() ChainShape

func (*ChainShape) Clear

func (chain *ChainShape) Clear()

func (ChainShape) Clone

func (chain ChainShape) Clone() IShape

func (ChainShape) ComputeAABB

func (chain ChainShape) ComputeAABB(aabb *AABB, xf Transform, childIndex int)

func (ChainShape) ComputeMass

func (chain ChainShape) ComputeMass(massData *MassData, density float64)

func (*ChainShape) CreateChain

func (chain *ChainShape) CreateChain(vertices []Vec2, count int, prevVertex Vec2, nextVertex Vec2)

Create a chain with ghost vertices to connect multiple chains together. @param vertices an array of vertices, these are copied @param count the vertex count @param prevVertex previous vertex from chain that connects to the start @param nextVertex next vertex from chain that connects to the end

func (*ChainShape) CreateLoop

func (chain *ChainShape) CreateLoop(vertices []Vec2, count int)

Create a loop. This automatically adjusts connectivity. @param vertices an array of vertices, these are copied @param count the vertex count

func (*ChainShape) Destroy

func (chain *ChainShape) Destroy()

func (ChainShape) GetChildCount

func (chain ChainShape) GetChildCount() int

func (ChainShape) GetChildEdge

func (chain ChainShape) GetChildEdge(edge *EdgeShape, index int)

func (ChainShape) RayCast

func (chain ChainShape) RayCast(output *RayCastOutput, input RayCastInput, xf Transform, childIndex int) bool

func (ChainShape) TestPoint

func (chain ChainShape) TestPoint(xf Transform, p Vec2) bool

type CircleContact

type CircleContact struct {
	Contact
}

func (*CircleContact) Evaluate

func (contact *CircleContact) Evaluate(manifold *Manifold, xfA Transform, xfB Transform)

type CircleShape

type CircleShape struct {
	Shape
	Pos Vec2
}

A solid circle shape

func MakeCircleShape

func MakeCircleShape() CircleShape

func NewCircleShape

func NewCircleShape() *CircleShape

func (CircleShape) Clone

func (shape CircleShape) Clone() IShape

func (CircleShape) ComputeAABB

func (shape CircleShape) ComputeAABB(aabb *AABB, transform Transform, childIndex int)

func (CircleShape) ComputeMass

func (shape CircleShape) ComputeMass(massData *MassData, density float64)

func (CircleShape) Destroy

func (shape CircleShape) Destroy()

func (CircleShape) GetChildCount

func (shape CircleShape) GetChildCount() int

func (CircleShape) RayCast

func (shape CircleShape) RayCast(output *RayCastOutput, input RayCastInput, transform Transform, childIndex int) bool

Collision Detection in Interactive 3D Environments by Gino van den Bergen From Section 3.1.2 x = s + a * r norm(x) = radius

@note because the circle is solid, rays that start inside do not hit because the normal is not defined.

func (CircleShape) TestPoint

func (shape CircleShape) TestPoint(transform Transform, p Vec2) bool

type ClipVertex

type ClipVertex struct {
	V  Vec2
	Id ContactID
}

Used for computing contact manifolds.

type Contact

type Contact struct {
	M_flags uint32

	// World pool and list pointers.
	M_prev IContact //should be backed by a pointer
	M_next IContact //should be backed by a pointer

	// Nodes for connecting bodies.
	M_nodeA *ContactEdge
	M_nodeB *ContactEdge

	M_fixtureA *Fixture
	M_fixtureB *Fixture

	M_indexA int
	M_indexB int

	M_manifold *Manifold

	M_toiCount             int
	M_toi                  float64
	M_friction             float64
	M_restitution          float64
	M_restitutionThreshold float64

	M_tangentSpeed float64
}

func MakeContact

func MakeContact(fA *Fixture, indexA int, fB *Fixture, indexB int) Contact

func (*Contact) FlagForFiltering

func (contact *Contact) FlagForFiltering()

func (Contact) GetChildIndexA

func (contact Contact) GetChildIndexA() int

func (Contact) GetChildIndexB

func (contact Contact) GetChildIndexB() int

func (Contact) GetFixtureA

func (contact Contact) GetFixtureA() *Fixture

func (Contact) GetFixtureB

func (contact Contact) GetFixtureB() *Fixture

func (Contact) GetFlags

func (contact Contact) GetFlags() uint32

func (Contact) GetFriction

func (contact Contact) GetFriction() float64

Get the friction.

func (Contact) GetManifold

func (contact Contact) GetManifold() *Manifold

func (Contact) GetNext

func (contact Contact) GetNext() IContact

func (Contact) GetNodeA

func (contact Contact) GetNodeA() *ContactEdge

func (Contact) GetNodeB

func (contact Contact) GetNodeB() *ContactEdge

func (Contact) GetPrev

func (contact Contact) GetPrev() IContact

func (Contact) GetRestitution

func (contact Contact) GetRestitution() float64

Get the restitution.

func (Contact) GetRestitutionThreshold

func (contact Contact) GetRestitutionThreshold() float64

Get the restitution threshold.

func (Contact) GetTOI

func (contact Contact) GetTOI() float64

func (Contact) GetTOICount

func (contact Contact) GetTOICount() int

func (Contact) GetTangentSpeed

func (contact Contact) GetTangentSpeed() float64

Get the desired tangent speed. In meters per second.

func (Contact) GetWorldManifold

func (contact Contact) GetWorldManifold(worldManifold *WorldManifold)

func (Contact) IsEnabled

func (contact Contact) IsEnabled() bool

func (Contact) IsTouching

func (contact Contact) IsTouching() bool

func (*Contact) ResetFriction

func (contact *Contact) ResetFriction()

Reset the friction mixture to the default value.

func (*Contact) ResetRestitution

func (contact *Contact) ResetRestitution()

Reset the restitution to the default value.

func (*Contact) ResetRestitutionThreshold

func (contact *Contact) ResetRestitutionThreshold()

Reset the restitution threshold to the default value.

func (*Contact) SetChildIndexA

func (contact *Contact) SetChildIndexA(index int)

func (*Contact) SetChildIndexB

func (contact *Contact) SetChildIndexB(index int)

func (*Contact) SetEnabled

func (contact *Contact) SetEnabled(flag bool)

func (*Contact) SetFixtureA

func (contact *Contact) SetFixtureA(fixture *Fixture)

func (*Contact) SetFixtureB

func (contact *Contact) SetFixtureB(fixture *Fixture)

func (*Contact) SetFlags

func (contact *Contact) SetFlags(flags uint32)

func (*Contact) SetFriction

func (contact *Contact) SetFriction(friction float64)

Override the default friction mixture. You can call this in b2ContactListener::PreSolve. This value persists until set or reset.

func (*Contact) SetManifold

func (contact *Contact) SetManifold(manifold *Manifold)

func (*Contact) SetNext

func (contact *Contact) SetNext(next IContact)

func (*Contact) SetNodeA

func (contact *Contact) SetNodeA(node *ContactEdge)

func (*Contact) SetNodeB

func (contact *Contact) SetNodeB(node *ContactEdge)

func (*Contact) SetPrev

func (contact *Contact) SetPrev(prev IContact)

func (*Contact) SetRestitution

func (contact *Contact) SetRestitution(restitution float64)

Override the default restitution mixture. You can call this in b2ContactListener::PreSolve. The value persists until you set or reset.

func (*Contact) SetRestitutionThreshold

func (contact *Contact) SetRestitutionThreshold(threshold float64)

Override the default restitution velocity threshold mixture. You can call this in b2ContactListener::PreSolve. The value persists until you set or reset.

func (*Contact) SetTOI

func (contact *Contact) SetTOI(toi float64)

func (*Contact) SetTOICount

func (contact *Contact) SetTOICount(toiCount int)

func (*Contact) SetTangentSpeed

func (contact *Contact) SetTangentSpeed(speed float64)

Set the desired tangent speed for a conveyor belt behavior. In meters per second.

type ContactCreateFcn

type ContactCreateFcn func(fixtureA *Fixture, indexA int, fixtureB *Fixture, indexB int) IContact // returned contact should be a pointer

type ContactDestroyFcn

type ContactDestroyFcn func(contact IContact) // contact should be a pointer

type ContactEdge

type ContactEdge struct {
	Other   *Body        // provides quick access to the other body attached.
	Contact IContact     // the contact
	Prev    *ContactEdge // the previous contact edge in the body's contact list
	Next    *ContactEdge // the next contact edge in the body's contact list
}

A contact edge is used to connect bodies and contacts together in a contact graph where each body is a node and each contact is an edge. A contact edge belongs to a doubly linked list maintained in each attached body. Each contact has two contact nodes, one for each attached body.

func NewContactEdge

func NewContactEdge() *ContactEdge

type ContactFeature

type ContactFeature struct {
	IndexA uint8 ///< Feature index on shapeA
	IndexB uint8 ///< Feature index on shapeB
	TypeA  uint8 ///< The feature type on shapeA
	TypeB  uint8 ///< The feature type on shapeB
}

The features that intersect to form the contact point This must be 4 bytes or less.

type ContactFilter

type ContactFilter struct {
}

func (*ContactFilter) ShouldCollide

func (cf *ContactFilter) ShouldCollide(fixtureA *Fixture, fixtureB *Fixture) bool

Return true if contact calculations should be performed between these two shapes. If you implement your own collision filter you may want to build from this implementation.

type ContactID

type ContactID ContactFeature

func (ContactID) Key

func (v ContactID) Key() uint32

Contact ids to facilitate warm starting. Used to quickly compare contact ids.

func (*ContactID) SetKey

func (v *ContactID) SetKey(key uint32)

type ContactImpulse

type ContactImpulse struct {
	NormalImpulses  [maxManifoldPoints]float64
	TangentImpulses [maxManifoldPoints]float64
	Count           int
}

Contact impulses for reporting. Impulses are used instead of forces because sub-step forces may approach infinity for rigid body collisions. These match up one-to-one with the contact points in b2Manifold.

func MakeContactImpulse

func MakeContactImpulse() ContactImpulse

type ContactManager

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

func MakeContactManager

func MakeContactManager() ContactManager

func NewContactManager

func NewContactManager() *ContactManager

func (*ContactManager) AddPair

func (mgr *ContactManager) AddPair(proxyUserDataA any, proxyUserDataB any)

func (*ContactManager) Collide

func (mgr *ContactManager) Collide()

This is the top level collision call for the time step. Here all the narrow phase collision is processed for the world contact list.

func (*ContactManager) Destroy

func (mgr *ContactManager) Destroy(c IContact)

func (*ContactManager) FindNewContacts

func (mgr *ContactManager) FindNewContacts()

type ContactPositionConstraint

type ContactPositionConstraint struct {
	LocalPoints                [maxManifoldPoints]Vec2
	LocalNormal                Vec2
	LocalPoint                 Vec2
	IndexA                     int
	IndexB                     int
	InvMassA, InvMassB         float64
	LocalCenterA, LocalCenterB Vec2
	InvIA, InvIB               float64
	Type                       ManifoldType
	RadiusA, RadiusB           float64
	PointCount                 int
}

type ContactRegister

type ContactRegister struct {
	CreateFcn  ContactCreateFcn
	DestroyFcn ContactDestroyFcn
	Primary    bool
}

type ContactSolver

type ContactSolver struct {
	M_step                TimeStep
	M_positions           []position
	M_velocities          []velocity
	M_positionConstraints []ContactPositionConstraint
	M_velocityConstraints []ContactVelocityConstraint
	M_contacts            []IContact // has to be backed by pointers
	M_count               int
}

func MakeContactSolver

func MakeContactSolver(def *ContactSolverDef) ContactSolver

func (*ContactSolver) Destroy

func (solver *ContactSolver) Destroy()

func (*ContactSolver) InitializeVelocityConstraints

func (solver *ContactSolver) InitializeVelocityConstraints()

Initialize position dependent portions of the velocity constraints.

func (*ContactSolver) SolvePositionConstraints

func (solver *ContactSolver) SolvePositionConstraints() bool

Sequential solver.

func (*ContactSolver) SolveTOIPositionConstraints

func (solver *ContactSolver) SolveTOIPositionConstraints(toiIndexA int, toiIndexB int) bool

Sequential position solver for position constraints.

func (*ContactSolver) SolveVelocityConstraints

func (solver *ContactSolver) SolveVelocityConstraints()

func (*ContactSolver) StoreImpulses

func (solver *ContactSolver) StoreImpulses()

func (*ContactSolver) WarmStart

func (solver *ContactSolver) WarmStart()

type ContactSolverDef

type ContactSolverDef struct {
	Step       TimeStep
	Contacts   []IContact // has to be backed by pointers
	Count      int
	Positions  []position
	Velocities []velocity
}

func MakeContactSolverDef

func MakeContactSolverDef() ContactSolverDef

type ContactVelocityConstraint

type ContactVelocityConstraint struct {
	Points             [maxManifoldPoints]VelocityConstraintPoint
	Normal             Vec2
	NormalMass         Mat22
	K                  Mat22
	IndexA             int
	IndexB             int
	InvMassA, InvMassB float64
	InvIA, InvIB       float64
	Friction           float64
	Restitution        float64
	Threshold          float64
	TangentSpeed       float64
	PointCount         int
	ContactIndex       int
}

type DistanceInput

type DistanceInput struct {
	ProxyA     DistanceProxy
	ProxyB     DistanceProxy
	TransformA Transform
	TransformB Transform
	UseRadii   bool
}

Input for b2Distance. You have to option to use the shape radii in the computation. Even

func MakeDistanceInput

func MakeDistanceInput() DistanceInput

type DistanceJoint

type DistanceJoint struct {
	*Joint

	M_stiffness float64
	M_damping   float64
	M_bias      float64
	M_length    float64
	M_minLength float64
	M_maxLength float64

	// Solver shared
	M_localAnchorA Vec2
	M_localAnchorB Vec2
	M_gamma        float64
	M_impulse      float64
	M_lowerImpulse float64
	M_upperImpulse float64

	// Solver temp
	M_indexA        int
	M_indexB        int
	M_u             Vec2
	M_rA            Vec2
	M_rB            Vec2
	M_localCenterA  Vec2
	M_localCenterB  Vec2
	M_currentLength float64
	M_invMassA      float64
	M_invMassB      float64
	M_invIA         float64
	M_invIB         float64
	M_softMass      float64
	M_mass          float64
}

A distance joint constrains two points on two bodies to remain at a fixed distance from each other. You can view this as a massless, rigid rod.

func MakeDistanceJoint

func MakeDistanceJoint(def *DistanceJointDef) *DistanceJoint

func (DistanceJoint) Dump

func (joint DistanceJoint) Dump()

func (DistanceJoint) GetAnchorA

func (joint DistanceJoint) GetAnchorA() Vec2

func (DistanceJoint) GetAnchorB

func (joint DistanceJoint) GetAnchorB() Vec2

func (DistanceJoint) GetCurrentLength

func (joint DistanceJoint) GetCurrentLength() float64

Get the current length

func (DistanceJoint) GetDamping

func (joint DistanceJoint) GetDamping() float64

Get linear damping in N*s/m

func (DistanceJoint) GetLength

func (joint DistanceJoint) GetLength() float64

Get the rest length

func (DistanceJoint) GetLocalAnchorA

func (joint DistanceJoint) GetLocalAnchorA() Vec2

The local anchor point relative to bodyA's origin.

func (DistanceJoint) GetLocalAnchorB

func (joint DistanceJoint) GetLocalAnchorB() Vec2

The local anchor point relative to bodyB's origin.

func (DistanceJoint) GetMaxLength

func (joint DistanceJoint) GetMaxLength() float64

Get the maximum length

func (DistanceJoint) GetMinLength

func (joint DistanceJoint) GetMinLength() float64

Get the minimum length

func (DistanceJoint) GetReactionForce

func (joint DistanceJoint) GetReactionForce(inv_dt float64) Vec2

func (DistanceJoint) GetReactionTorque

func (joint DistanceJoint) GetReactionTorque(inv_dt float64) float64

func (DistanceJoint) GetStiffness

func (joint DistanceJoint) GetStiffness() float64

Get the linear stiffness in N/m

func (*DistanceJoint) InitVelocityConstraints

func (joint *DistanceJoint) InitVelocityConstraints(data SolverData)

func (*DistanceJoint) SetDamping

func (joint *DistanceJoint) SetDamping(damping float64)

Set linear damping in N*s/m

func (*DistanceJoint) SetLength

func (joint *DistanceJoint) SetLength(length float64) float64

Set the rest length @returns clamped rest length

func (*DistanceJoint) SetMaxLength

func (joint *DistanceJoint) SetMaxLength(maxLength float64) float64

Set the maximum length @returns the clamped maximum length

func (*DistanceJoint) SetMinLength

func (joint *DistanceJoint) SetMinLength(minLength float64) float64

Set the minimum length @returns the clamped minimum length

func (*DistanceJoint) SetStiffness

func (joint *DistanceJoint) SetStiffness(stiffness float64)

Set the linear stiffness in N/m

func (*DistanceJoint) SolvePositionConstraints

func (joint *DistanceJoint) SolvePositionConstraints(data SolverData) bool

func (*DistanceJoint) SolveVelocityConstraints

func (joint *DistanceJoint) SolveVelocityConstraints(data SolverData)

type DistanceJointDef

type DistanceJointDef struct {
	JointDef

	// The local anchor point relative to bodyA's origin.
	LocalAnchorA Vec2

	// The local anchor point relative to bodyB's origin.
	LocalAnchorB Vec2

	// The rest length of this joint. Clamped to a stable minimum value.
	Length float64

	// Minimum length. Clamped to a stable minimum value.
	MinLength float64

	// Maximum length. Must be greater than or equal to the minimum length.
	MaxLength float64

	// The linear stiffness in N/m.
	Stiffness float64

	// The linear damping in N*s/m.
	Damping float64
}

Distance joint definition. This requires defining an anchor point on both bodies and the non-zero distance of the distance joint. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. This helps when saving and loading a game.

func MakeDistanceJointDef

func MakeDistanceJointDef() DistanceJointDef

func (*DistanceJointDef) Initialize

func (joint *DistanceJointDef) Initialize(b1 *Body, b2 *Body, anchor1 Vec2, anchor2 Vec2)

Initialize the bodies, anchors, and rest length using world space anchors. The minimum and maximum lengths are set to the rest length.

type DistanceOutput

type DistanceOutput struct {
	PointA     Vec2 // closest point on shapeA
	PointB     Vec2 // closest point on shapeB
	Distance   float64
	Iterations int // number of GJK iterations used
}

Output for b2Distance.

func MakeDistanceOutput

func MakeDistanceOutput() DistanceOutput

type DistanceProxy

type DistanceProxy struct {
	M_buffer   [2]Vec2
	M_vertices []Vec2 // is a memory blob using pointer arithmetic in original implementation
	M_count    int
	M_radius   float64
}

A distance proxy is used by the GJK algorithm. It encapsulates any shape.

func MakeDistanceProxy

func MakeDistanceProxy() DistanceProxy

func (DistanceProxy) GetSupport

func (p DistanceProxy) GetSupport(d Vec2) int

func (DistanceProxy) GetSupportVertex

func (p DistanceProxy) GetSupportVertex(d Vec2) Vec2

func (DistanceProxy) GetVertex

func (p DistanceProxy) GetVertex(index int) Vec2

func (DistanceProxy) GetVertexCount

func (p DistanceProxy) GetVertexCount() int

func (*DistanceProxy) Set

func (p *DistanceProxy) Set(shape IShape, index int)

Initialize the proxy using the given shape. The shape must remain in scope while the proxy is in use.

type DynamicTree

type DynamicTree struct {

	// Private members:
	M_root int

	M_nodeCount    int
	M_nodeCapacity int

	M_freeList int

	M_insertionCount int
	// contains filtered or unexported fields
}

A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. A dynamic tree arranges data in a binary tree to accelerate queries such as volume queries and ray casts. Leafs are proxies with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor so that the proxy AABB is bigger than the client object. This allows the client object to move by small amounts without triggering a tree update.

Nodes are pooled and relocatable, so we use node indices rather than pointers.

func MakeDynamicTree

func MakeDynamicTree() DynamicTree

func (*DynamicTree) AllocateNode

func (tree *DynamicTree) AllocateNode() int

Allocate a node from the pool. Grow the pool if necessary.

func (*DynamicTree) Balance

func (tree *DynamicTree) Balance(iA int) int

Perform a left or right rotation if node A is imbalanced. Returns the new root index.

func (DynamicTree) ClearMoved

func (tree DynamicTree) ClearMoved(proxyId int)

func (DynamicTree) ComputeHeight

func (tree DynamicTree) ComputeHeight(nodeId int) int

Compute the height of a sub-tree.

func (DynamicTree) ComputeTotalHeight

func (tree DynamicTree) ComputeTotalHeight() int

func (*DynamicTree) CreateProxy

func (tree *DynamicTree) CreateProxy(aabb AABB, userData any) int

Create a proxy in the tree as a leaf node. We return the index of the node instead of a pointer so that we can grow the node pool.

func (*DynamicTree) DestroyProxy

func (tree *DynamicTree) DestroyProxy(proxyId int)

func (*DynamicTree) FreeNode

func (tree *DynamicTree) FreeNode(nodeId int)

Return a node to the pool.

func (DynamicTree) GetAreaRatio

func (tree DynamicTree) GetAreaRatio() float64

func (DynamicTree) GetFatAABB

func (tree DynamicTree) GetFatAABB(proxyId int) AABB

func (DynamicTree) GetHeight

func (tree DynamicTree) GetHeight() int

func (DynamicTree) GetMaxBalance

func (tree DynamicTree) GetMaxBalance() int

func (DynamicTree) GetUserData

func (tree DynamicTree) GetUserData(proxyId int) any

func (*DynamicTree) InsertLeaf

func (tree *DynamicTree) InsertLeaf(leaf int)

func (*DynamicTree) MoveProxy

func (tree *DynamicTree) MoveProxy(proxyId int, aabb AABB, displacement Vec2) bool

func (*DynamicTree) Query

func (tree *DynamicTree) Query(queryCallback TreeQueryCallback, aabb AABB)

func (DynamicTree) RayCast

func (tree DynamicTree) RayCast(rayCastCallback TreeRayCastCallback, input RayCastInput)

func (*DynamicTree) RebuildBottomUp

func (tree *DynamicTree) RebuildBottomUp()

func (*DynamicTree) RemoveLeaf

func (tree *DynamicTree) RemoveLeaf(leaf int)

func (*DynamicTree) ShiftOrigin

func (tree *DynamicTree) ShiftOrigin(newOrigin Vec2)

func (DynamicTree) Validate

func (tree DynamicTree) Validate()

func (DynamicTree) ValidateMetrics

func (tree DynamicTree) ValidateMetrics(index int)

func (DynamicTree) ValidateStructure

func (tree DynamicTree) ValidateStructure(index int)

func (DynamicTree) WasMoved

func (tree DynamicTree) WasMoved(proxyId int) bool

type EdgeAndCircleContact

type EdgeAndCircleContact struct {
	Contact
}

func (*EdgeAndCircleContact) Evaluate

func (contact *EdgeAndCircleContact) Evaluate(manifold *Manifold, xfA Transform, xfB Transform)

type EdgeAndPolygonContact

type EdgeAndPolygonContact struct {
	Contact
}

func (*EdgeAndPolygonContact) Evaluate

func (contact *EdgeAndPolygonContact) Evaluate(manifold *Manifold, xfA Transform, xfB Transform)

type EdgeShape

type EdgeShape struct {
	Shape
	// These are the edge vertices
	M_vertex1, M_vertex2 Vec2

	// Optional adjacent vertices. These are used for smooth collision.
	M_vertex0, M_vertex3 Vec2

	// Uses m_vertex0 and m_vertex3 to create smooth collision.
	M_oneSided bool
}

A line segment (edge) shape. These can be connected in chains or loops to other edge shapes. Edges created independently are two-sided and do no provide smooth movement across junctions.

func MakeEdgeShape

func MakeEdgeShape() EdgeShape

func NewEdgeShape

func NewEdgeShape() *EdgeShape

func (EdgeShape) Clone

func (edge EdgeShape) Clone() IShape

func (EdgeShape) ComputeAABB

func (edge EdgeShape) ComputeAABB(aabb *AABB, xf Transform, childIndex int)

func (EdgeShape) ComputeMass

func (edge EdgeShape) ComputeMass(massData *MassData, density float64)

func (*EdgeShape) Destroy

func (edge *EdgeShape) Destroy()

func (EdgeShape) GetChildCount

func (edge EdgeShape) GetChildCount() int

func (EdgeShape) RayCast

func (edge EdgeShape) RayCast(output *RayCastOutput, input RayCastInput, xf Transform, childIndex int) bool

p = p1 + t * d v = v1 + s * e p1 + t * d = v1 + s * e s * e - t * d = p1 - v1

func (*EdgeShape) SetOneSided

func (edge *EdgeShape) SetOneSided(v0 Vec2, v1 Vec2, v2 Vec2, v3 Vec2)

Set this as a part of a sequence. Vertex v0 precedes the edge and vertex v3 follows. These extra vertices are used to provide smooth movement across junctions. This also makes the collision one-sided. The edge normal points to the right looking from v1 to v2.

func (*EdgeShape) SetTwoSided

func (edge *EdgeShape) SetTwoSided(v1 Vec2, v2 Vec2)

Set this as an isolated edge. Collision is two-sided.

func (EdgeShape) TestPoint

func (edge EdgeShape) TestPoint(xf Transform, p Vec2) bool

type Filter

type Filter struct {
	// The collision category bits. Normally you would just set one bit.
	CategoryBits uint16

	// The collision mask bits. This states the categories that this
	// shape would accept for collision.
	MaskBits uint16

	// Collision groups allow a certain group of objects to never collide (negative)
	// or always collide (positive). Zero means no collision group. Non-zero group
	// filtering always wins against the mask bits.
	GroupIndex int16
}

This holds contact filtering data.

func DefaultFilter

func DefaultFilter() Filter

type Fixture

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

A fixture is used to attach a shape to a body for collision detection. A fixture inherits its transform from its parent. Fixtures hold additional non-geometric data such as friction, collision filters, etc. Fixtures are created via b2Body::CreateFixture. @warning you cannot reuse fixtures.

func NewFixture

func NewFixture() *Fixture

func (Fixture) AABB

func (fix Fixture) AABB(childIndex int) AABB

Get the fixture's AABB. This AABB may be enlarge and/or stale. If you need a more accurate AABB, compute it using the shape and the body transform.

func (Fixture) Body

func (fix Fixture) Body() *Body

func (*Fixture) Create

func (fix *Fixture) Create(body *Body, def *FixtureDef)

func (*Fixture) CreateProxies

func (fix *Fixture) CreateProxies(broadPhase *BroadPhase, xf Transform)

func (Fixture) Density

func (fix Fixture) Density() float64

Get the density of this fixture.

func (*Fixture) Destroy

func (fix *Fixture) Destroy()

func (*Fixture) DestroyProxies

func (fix *Fixture) DestroyProxies(broadPhase *BroadPhase)

func (*Fixture) Dump

func (fix *Fixture) Dump(bodyIndex int)

func (Fixture) FilterData

func (fix Fixture) FilterData() Filter

func (Fixture) Friction

func (fix Fixture) Friction() float64

Get the coefficient of friction.

func (Fixture) IsSensor

func (fix Fixture) IsSensor() bool

func (Fixture) MassData

func (fix Fixture) MassData(massData *MassData)

func (Fixture) Next

func (fix Fixture) Next() *Fixture

func (Fixture) RayCast

func (fix Fixture) RayCast(output *RayCastOutput, input RayCastInput, childIndex int) bool

func (*Fixture) Refilter

func (fix *Fixture) Refilter()

func (Fixture) Restitution

func (fix Fixture) Restitution() float64

Get the coefficient of restitution.

func (Fixture) RestitutionThreshold

func (fix Fixture) RestitutionThreshold() float64

Get the restitution velocity threshold.

func (*Fixture) SetDensity

func (fix *Fixture) SetDensity(density float64)

Set the density of this fixture. This will _not_ automatically adjust the mass of the body. You must call b2Body::ResetMassData to update the body's mass.

func (*Fixture) SetFilterData

func (fix *Fixture) SetFilterData(filter Filter)

func (*Fixture) SetFriction

func (fix *Fixture) SetFriction(friction float64)

Set the coefficient of friction. This will _not_ change the friction of existing contacts.

func (*Fixture) SetRestitution

func (fix *Fixture) SetRestitution(restitution float64)

Set the coefficient of restitution. This will _not_ change the restitution of existing contacts.

func (*Fixture) SetRestitutionThreshold

func (fix *Fixture) SetRestitutionThreshold(threshold float64)

Set the restitution threshold. This will _not_ change the restitution threshold of existing contacts.

func (*Fixture) SetSensor

func (fix *Fixture) SetSensor(sensor bool)

func (*Fixture) SetUserData

func (fix *Fixture) SetUserData(data any)

func (Fixture) Shape

func (fix Fixture) Shape() IShape

func (*Fixture) Synchronize

func (fix *Fixture) Synchronize(broadPhase *BroadPhase, transform1 Transform, transform2 Transform)

func (Fixture) TestPoint

func (fix Fixture) TestPoint(p Vec2) bool

func (Fixture) Type

func (fix Fixture) Type() ShapeType

func (Fixture) UserData

func (fix Fixture) UserData() any

type FixtureDef

type FixtureDef struct {

	// The shape, this must be set. The shape will be cloned, so you
	// can create the shape on the stack.
	Shape IShape

	// Use this to store application specific fixture data.
	UserData any

	// The friction coefficient, usually in the range [0,1].
	Friction float64

	// The restitution (elasticity) usually in the range [0,1].
	Restitution float64

	// Restitution velocity threshold, usually in m/s. Collisions above this
	// speed have restitution applied (will bounce).
	RestitutionThreshold float64

	// The density, usually in kg/m^2.
	Density float64

	// A sensor shape collects contact information but never generates a collision
	// response.
	IsSensor bool

	// Contact filtering data.
	Filter Filter
}

A fixture definition is used to create a fixture. This class defines an abstract fixture definition. You can reuse fixture definitions safely.

func DefaultFixtureDef

func DefaultFixtureDef() FixtureDef

The constructor sets the default fixture definition values.

type FixtureProxy

type FixtureProxy struct {
	Aabb       AABB
	Fixture    *Fixture
	ChildIndex int
	ProxyId    int
}

This proxy is used internally to connect fixtures to the broad-phase.

type FrictionJoint

type FrictionJoint struct {
	*Joint

	M_localAnchorA Vec2
	M_localAnchorB Vec2

	// Solver shared
	M_linearImpulse  Vec2
	M_angularImpulse float64
	M_maxForce       float64
	M_maxTorque      float64

	// Solver temp
	M_indexA       int
	M_indexB       int
	M_rA           Vec2
	M_rB           Vec2
	M_localCenterA Vec2
	M_localCenterB Vec2
	M_invMassA     float64
	M_invMassB     float64
	M_invIA        float64
	M_invIB        float64
	M_linearMass   Mat22
	M_angularMass  float64
}

Friction joint. This is used for top-down friction. It provides 2D translational friction and angular friction.

func MakeFrictionJoint

func MakeFrictionJoint(def *FrictionJointDef) *FrictionJoint

func (*FrictionJoint) Dump

func (joint *FrictionJoint) Dump()

func (FrictionJoint) GetAnchorA

func (joint FrictionJoint) GetAnchorA() Vec2

func (FrictionJoint) GetAnchorB

func (joint FrictionJoint) GetAnchorB() Vec2

func (FrictionJoint) GetLocalAnchorA

func (joint FrictionJoint) GetLocalAnchorA() Vec2

The local anchor point relative to bodyA's origin.

func (FrictionJoint) GetLocalAnchorB

func (joint FrictionJoint) GetLocalAnchorB() Vec2

The local anchor point relative to bodyB's origin.

func (FrictionJoint) GetMaxForce

func (joint FrictionJoint) GetMaxForce() float64

func (FrictionJoint) GetMaxTorque

func (joint FrictionJoint) GetMaxTorque() float64

func (FrictionJoint) GetReactionForce

func (joint FrictionJoint) GetReactionForce(inv_dt float64) Vec2

func (FrictionJoint) GetReactionTorque

func (joint FrictionJoint) GetReactionTorque(inv_dt float64) float64

func (*FrictionJoint) InitVelocityConstraints

func (joint *FrictionJoint) InitVelocityConstraints(data SolverData)

func (*FrictionJoint) SetMaxForce

func (joint *FrictionJoint) SetMaxForce(force float64)

func (*FrictionJoint) SetMaxTorque

func (joint *FrictionJoint) SetMaxTorque(torque float64)

func (*FrictionJoint) SolvePositionConstraints

func (joint *FrictionJoint) SolvePositionConstraints(data SolverData) bool

func (*FrictionJoint) SolveVelocityConstraints

func (joint *FrictionJoint) SolveVelocityConstraints(data SolverData)

type FrictionJointDef

type FrictionJointDef struct {
	JointDef

	// The local anchor point relative to bodyA's origin.
	LocalAnchorA Vec2

	// The local anchor point relative to bodyB's origin.
	LocalAnchorB Vec2

	// The maximum friction force in N.
	MaxForce float64

	// The maximum friction torque in N-m.
	MaxTorque float64
}

Friction joint definition.

func MakeFrictionJointDef

func MakeFrictionJointDef() FrictionJointDef

func (*FrictionJointDef) Initialize

func (joint *FrictionJointDef) Initialize(bA *Body, bB *Body, anchor Vec2)

type GearJoint

type GearJoint struct {
	*Joint

	M_joint1 IJoint // backed by pointer
	M_joint2 IJoint // backed by pointer

	M_typeA JointType
	M_typeB JointType

	// Body A is connected to body C
	// Body B is connected to body D
	M_bodyC *Body
	M_bodyD *Body

	// Solver shared
	M_localAnchorA Vec2
	M_localAnchorB Vec2
	M_localAnchorC Vec2
	M_localAnchorD Vec2

	M_localAxisC Vec2
	M_localAxisD Vec2

	M_referenceAngleA float64
	M_referenceAngleB float64

	M_constant  float64
	M_ratio     float64
	M_tolerance float64

	M_impulse float64

	// Solver temp
	M_indexA, M_indexB, M_indexC, M_indexD int
	M_lcA, M_lcB, M_lcC, M_lcD             Vec2
	M_mA, M_mB, M_mC, M_mD                 float64
	M_iA, M_iB, M_iC, M_iD                 float64
	M_JvAC, M_JvBD                         Vec2
	M_JwA, M_JwB, M_JwC, M_JwD             float64
	M_mass                                 float64
}

A gear joint is used to connect two joints together. Either joint can be a revolute or prismatic joint. You specify a gear ratio to bind the motions together: coordinate1 + ratio * coordinate2 = constant The ratio can be negative or positive. If one joint is a revolute joint and the other joint is a prismatic joint, then the ratio will have units of length or units of 1/length. @warning You have to manually destroy the gear joint if joint1 or joint2 is destroyed.

func MakeGearJoint

func MakeGearJoint(def *GearJointDef) *GearJoint

func (*GearJoint) Dump

func (joint *GearJoint) Dump()

func (GearJoint) GetAnchorA

func (joint GearJoint) GetAnchorA() Vec2

func (GearJoint) GetAnchorB

func (joint GearJoint) GetAnchorB() Vec2

func (GearJoint) GetJoint1

func (joint GearJoint) GetJoint1() IJoint

Get the first joint.

func (GearJoint) GetJoint2

func (joint GearJoint) GetJoint2() IJoint

Get the second joint.

func (GearJoint) GetRatio

func (joint GearJoint) GetRatio() float64

func (GearJoint) GetReactionForce

func (joint GearJoint) GetReactionForce(inv_dt float64) Vec2

func (GearJoint) GetReactionTorque

func (joint GearJoint) GetReactionTorque(inv_dt float64) float64

func (*GearJoint) InitVelocityConstraints

func (joint *GearJoint) InitVelocityConstraints(data SolverData)

func (*GearJoint) SetRatio

func (joint *GearJoint) SetRatio(ratio float64)

func (*GearJoint) SolvePositionConstraints

func (joint *GearJoint) SolvePositionConstraints(data SolverData) bool

func (*GearJoint) SolveVelocityConstraints

func (joint *GearJoint) SolveVelocityConstraints(data SolverData)

type GearJointDef

type GearJointDef struct {
	JointDef

	// The first revolute/prismatic joint attached to the gear joint.
	Joint1 IJoint // has to be backed by pointer

	// The second revolute/prismatic joint attached to the gear joint.
	Joint2 IJoint // has to be backed by pointer

	// The gear ratio.
	// @see b2GearJoint for explanation.
	Ratio float64
}

Gear joint definition. This definition requires two existing revolute or prismatic joints (any combination will work). @warning bodyB on the input joints must both be dynamic

func MakeGearJointDef

func MakeGearJointDef() GearJointDef

type Hull

type Hull struct {
	Points [MaxPolygonVertices]Vec2
	Count  int
}

Convex hull used for polygon collision

func ComputeHull

func ComputeHull(points []Vec2, count int) Hull

Compute the convex hull of a set of points. Returns an empty hull if it fails. Some failure cases: - all points very close together - all points on a line - less than 3 points - more than b2_maxPolygonVertices points This welds close points and removes collinear points.

quickhull algorithm - merges vertices based on b2_linearSlop - removes collinear points using b2_linearSlop - returns an empty hull if it fails

func RecurseHull

func RecurseHull(p1 Vec2, p2 Vec2, ps []Vec2, count int) Hull

quickhull recursion

type IContact

type IContact interface {
	GetFlags() uint32
	SetFlags(flags uint32)

	GetPrev() IContact
	SetPrev(prev IContact)

	GetNext() IContact
	SetNext(prev IContact)

	GetNodeA() *ContactEdge
	SetNodeA(node *ContactEdge)

	GetNodeB() *ContactEdge
	SetNodeB(node *ContactEdge)

	GetFixtureA() *Fixture
	SetFixtureA(fixture *Fixture)

	GetFixtureB() *Fixture
	SetFixtureB(fixture *Fixture)

	GetChildIndexA() int
	SetChildIndexA(index int)

	GetChildIndexB() int
	SetChildIndexB(index int)

	GetManifold() *Manifold
	SetManifold(manifold *Manifold)

	GetTOICount() int
	SetTOICount(toiCount int)

	GetTOI() float64
	SetTOI(toiCount float64)

	GetFriction() float64
	SetFriction(friction float64)
	ResetFriction()

	GetRestitution() float64
	SetRestitution(restitution float64)
	ResetRestitution()
	SetRestitutionThreshold(float64)
	GetRestitutionThreshold() float64
	ResetRestitutionThreshold()

	GetTangentSpeed() float64
	SetTangentSpeed(tangentSpeed float64)

	IsTouching() bool
	IsEnabled() bool
	SetEnabled(bool)

	Evaluate(manifold *Manifold, xfA Transform, xfB Transform)

	FlagForFiltering()

	GetWorldManifold(worldManifold *WorldManifold)
}

func ChainAndCircleContact_Create

func ChainAndCircleContact_Create(fixtureA *Fixture, indexA int, fixtureB *Fixture, indexB int) IContact

func ChainAndPolygonContact_Create

func ChainAndPolygonContact_Create(fixtureA *Fixture, indexA int, fixtureB *Fixture, indexB int) IContact

func CircleContact_Create

func CircleContact_Create(fixtureA *Fixture, indexA int, fixtureB *Fixture, indexB int) IContact

func ContactFactory

func ContactFactory(fixtureA *Fixture, indexA int, fixtureB *Fixture, indexB int) IContact

func EdgeAndCircleContact_Create

func EdgeAndCircleContact_Create(fixtureA *Fixture, indexA int, fixtureB *Fixture, indexB int) IContact

func EdgeAndPolygonContact_Create

func EdgeAndPolygonContact_Create(fixtureA *Fixture, indexA int, fixtureB *Fixture, indexB int) IContact

func PolygonAndCircleContact_Create

func PolygonAndCircleContact_Create(fixtureA *Fixture, indexA int, fixtureB *Fixture, indexB int) IContact

func PolygonContact_Create

func PolygonContact_Create(fixtureA *Fixture, indexA int, fixtureB *Fixture, indexB int) IContact

type IContactFilter

type IContactFilter interface {
	ShouldCollide(fixtureA *Fixture, fixtureB *Fixture) bool
}

type IContactListener

type IContactListener interface {
	// Called when two fixtures begin to touch.
	BeginContact(contact IContact) // contact has to be backed by a pointer

	// Called when two fixtures cease to touch.
	EndContact(contact IContact) // contact has to be backed by a pointer

	// This is called after a contact is updated. This allows you to inspect a
	// contact before it goes to the solver. If you are careful, you can modify the
	// contact manifold (e.g. disable contact).
	// A copy of the old manifold is provided so that you can detect changes.
	// Note: this is called only for awake bodies.
	// Note: this is called even when the number of contact points is zero.
	// Note: this is not called for sensors.
	// Note: if you set the number of contact points to zero, you will not
	// get an EndContact callback. However, you may get a BeginContact callback
	// the next step.
	PreSolve(contact IContact, oldManifold Manifold) // contact has to be backed by a pointer

	// This lets you inspect a contact after the solver is finished. This is useful
	// for inspecting impulses.
	// Note: the contact manifold does not include time of impact impulses, which can be
	// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly
	// in a separate data structure.
	// Note: this is only called for contacts that are touching, solid, and awake.
	PostSolve(contact IContact, impulse *ContactImpulse) // contact has to be backed by a pointer
}

type IDestructionListener

type IDestructionListener interface {
	// Called when any fixture is about to be destroyed due
	// to the destruction of its parent body.
	SayGoodbyeToFixture(fixture *Fixture)

	SayGoodbyeToJoint(joint IJoint) // backed by pointer
}

type IJoint

type IJoint interface {
	// Dump this joint to the log file.
	Dump()

	// Shift the origin for any points stored in world coordinates.
	ShiftOrigin(newOrigin Vec2)

	GetType() JointType
	SetType(t JointType)

	GetBodyA() *Body
	SetBodyA(body *Body)

	GetBodyB() *Body
	SetBodyB(body *Body)

	GetIndex() int
	SetIndex(index int)

	GetNext() IJoint     // backed by pointer
	SetNext(next IJoint) // backed by pointer

	GetPrev() IJoint     // backed by pointer
	SetPrev(prev IJoint) // backed by pointer

	GetEdgeA() *JointEdge
	SetEdgeA(edge *JointEdge)

	GetEdgeB() *JointEdge
	SetEdgeB(edge *JointEdge)

	GetUserData() any
	SetUserData(data any)

	IsCollideConnected() bool
	SetCollideConnected(flag bool)

	IsEnabled() bool

	//@goadd
	Destroy()

	InitVelocityConstraints(data SolverData)

	SolveVelocityConstraints(data SolverData)

	SolvePositionConstraints(data SolverData) bool

	GetIslandFlag() bool
	SetIslandFlag(flag bool)
}

func JointCreate

func JointCreate(def IJointDef) IJoint

type IJointDef

type IJointDef interface {
	GetType() JointType
	SetType(t JointType)
	GetUserData() any
	SetUserData(userData any)
	GetBodyA() *Body
	SetBodyA(body *Body)
	GetBodyB() *Body
	SetBodyB(body *Body)
	IsCollideConnected() bool
	SetCollideConnected(flag bool)
}

type IShape

type IShape interface {
	Destroy()

	// Clone the concrete shape using the provided allocator.
	Clone() IShape

	// Get the type of this shape. You can use this to down cast to the concrete shape.
	// @return the shape type.
	GetType() ShapeType

	// Get the type of this shape. You can use this to down cast to the concrete shape.
	// @return the shape type.
	GetRadius() float64

	// Get the number of child primitives.
	GetChildCount() int

	// Test a point for containment in this shape. This only works for convex shapes.
	// @param xf the shape world transform.
	// @param p a point in world coordinates.
	TestPoint(xf Transform, p Vec2) bool

	// Cast a ray against a child shape.
	// @param output the ray-cast results.
	// @param input the ray-cast input parameters.
	// @param transform the transform to be applied to the shape.
	// @param childIndex the child shape index
	RayCast(output *RayCastOutput, input RayCastInput, transform Transform, childIndex int) bool

	// Given a transform, compute the associated axis aligned bounding box for a child shape.
	// @param aabb returns the axis aligned box.
	// @param xf the world transform of the shape.
	// @param childIndex the child shape
	ComputeAABB(aabb *AABB, xf Transform, childIndex int)

	// Compute the mass properties of this shape using its dimensions and density.
	// The inertia tensor is computed about the local origin.
	// @param massData returns the mass data for this shape.
	// @param density the density in kilograms per meter squared.
	ComputeMass(massData *MassData, density float64)
}

type Island

type Island struct {
	M_listener IContactListener

	M_bodies   []*Body
	M_contacts []IContact // has to be backed by pointers
	M_joints   []IJoint   // has to be backed by pointers

	M_positions  []position
	M_velocities []velocity

	M_bodyCount    int
	M_jointCount   int
	M_contactCount int

	M_bodyCapacity    int
	M_contactCapacity int
	M_jointCapacity   int
}

This is an internal class.

func MakeIsland

func MakeIsland(bodyCapacity int, contactCapacity int, jointCapacity int, listener IContactListener) Island

func (*Island) Add

func (island *Island) Add(joint IJoint)

func (*Island) AddBody

func (island *Island) AddBody(body *Body)

func (*Island) AddContact

func (island *Island) AddContact(contact IContact)

func (*Island) Clear

func (island *Island) Clear()

func (*Island) Destroy

func (island *Island) Destroy()

func (*Island) Report

func (island *Island) Report(constraints []ContactVelocityConstraint)

func (*Island) Solve

func (island *Island) Solve(profile *Profile, step TimeStep, gravity Vec2, allowSleep bool)

func (*Island) SolveTOI

func (island *Island) SolveTOI(subStep TimeStep, toiIndexA int, toiIndexB int)

type Jacobian

type Jacobian struct {
	Linear   Vec2
	AngularA float64
	AngularB float64
}

type Joint

type Joint struct {
	M_type  JointType
	M_prev  IJoint // has to be backed by pointer
	M_next  IJoint // has to be backed by pointer
	M_edgeA *JointEdge
	M_edgeB *JointEdge

	M_index            int
	M_islandFlag       bool
	M_collideConnected bool
	UserData           any
	// contains filtered or unexported fields
}

The base joint class. Joints are used to constraint two bodies together in various fashions. Some joints also feature limits and motors.

func MakeJoint

func MakeJoint(def IJointDef) *Joint

func (*Joint) Destroy

func (j *Joint) Destroy()

@goadd

func (Joint) Dump

func (j Joint) Dump()

Dump this joint to the log file.

func (Joint) GetBodyA

func (j Joint) GetBodyA() *Body

func (Joint) GetBodyB

func (j Joint) GetBodyB() *Body

func (Joint) GetEdgeA

func (j Joint) GetEdgeA() *JointEdge

@goadd

func (Joint) GetEdgeB

func (j Joint) GetEdgeB() *JointEdge

@goadd

func (Joint) GetIndex

func (j Joint) GetIndex() int

@goadd

func (Joint) GetIslandFlag

func (j Joint) GetIslandFlag() bool

func (Joint) GetNext

func (j Joint) GetNext() IJoint

func (Joint) GetPrev

func (j Joint) GetPrev() IJoint

func (Joint) GetType

func (j Joint) GetType() JointType

func (Joint) GetUserData

func (j Joint) GetUserData() any

func (*Joint) InitVelocityConstraints

func (j *Joint) InitVelocityConstraints(data SolverData)

func (Joint) IsCollideConnected

func (j Joint) IsCollideConnected() bool

func (Joint) IsEnabled

func (j Joint) IsEnabled() bool

Short-cut function to determine if either body is enabled.

func (*Joint) SetBodyA

func (j *Joint) SetBodyA(body *Body)

@goadd

func (*Joint) SetBodyB

func (j *Joint) SetBodyB(body *Body)

@goadd

func (*Joint) SetCollideConnected

func (j *Joint) SetCollideConnected(flag bool)

@goadd

func (*Joint) SetEdgeA

func (j *Joint) SetEdgeA(edge *JointEdge)

@goadd

func (*Joint) SetEdgeB

func (j *Joint) SetEdgeB(edge *JointEdge)

@goadd

func (*Joint) SetIndex

func (j *Joint) SetIndex(index int)

func (*Joint) SetIslandFlag

func (j *Joint) SetIslandFlag(flag bool)

func (*Joint) SetNext

func (j *Joint) SetNext(next IJoint)

@goadd

func (*Joint) SetPrev

func (j *Joint) SetPrev(prev IJoint)

@goadd

func (*Joint) SetType

func (j *Joint) SetType(t JointType)

@goadd

func (*Joint) SetUserData

func (j *Joint) SetUserData(data any)

func (Joint) ShiftOrigin

func (j Joint) ShiftOrigin(newOrigin Vec2)

Shift the origin for any points stored in world coordinates.

func (*Joint) SolvePositionConstraints

func (j *Joint) SolvePositionConstraints(data SolverData) bool

func (*Joint) SolveVelocityConstraints

func (j *Joint) SolveVelocityConstraints(data SolverData)

type JointDef

type JointDef struct {

	// The joint type is set automatically for concrete joint types.
	Type JointType

	// Use this to attach application specific data to your joints.
	UserData any

	// The first attached body.
	BodyA *Body

	// The second attached body.
	BodyB *Body

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

Joint definitions are used to construct joints.

func DefaultJointDef

func DefaultJointDef() JointDef

func (JointDef) GetBodyA

func (def JointDef) GetBodyA() *Body

func (JointDef) GetBodyB

func (def JointDef) GetBodyB() *Body

func (JointDef) GetType

func (def JointDef) GetType() JointType

Implementing JointDefInterface on Joint (used as a base struct)

func (JointDef) GetUserData

func (def JointDef) GetUserData() any

func (JointDef) IsCollideConnected

func (def JointDef) IsCollideConnected() bool

func (*JointDef) SetBodyA

func (def *JointDef) SetBodyA(body *Body)

func (*JointDef) SetBodyB

func (def *JointDef) SetBodyB(body *Body)

func (*JointDef) SetCollideConnected

func (def *JointDef) SetCollideConnected(flag bool)

func (*JointDef) SetType

func (def *JointDef) SetType(t JointType)

func (*JointDef) SetUserData

func (def *JointDef) SetUserData(userdata any)

type JointEdge

type JointEdge struct {
	Other *Body      // provides quick access to the other body attached.
	Joint IJoint     // the joint; backed by pointer
	Prev  *JointEdge // the previous joint edge in the body's joint list
	Next  *JointEdge // the next joint edge in the body's joint list
}

A joint edge is used to connect bodies and joints together in a joint graph where each body is a node and each joint is an edge. A joint edge belongs to a doubly linked list maintained in each attached body. Each joint has two joint nodes, one for each attached body.

type JointType

type JointType uint8
const (
	UnknownJointType JointType = iota // 0
	RevoluteJointType
	PrismaticJointType
	DistanceJointType
	PulleyJointType
	MouseJointType
	GearJointType
	WheelJointType
	WeldJointType
	FrictionJointType
	MotorJointType
)

type Manifold

type Manifold struct {
	Type ManifoldType
	// the points of contact
	Points [maxManifoldPoints]ManifoldPoint
	// not use for Type::e_points
	LocalNormal Vec2
	// usage depends on manifold type
	LocalPoint Vec2
	// the number of manifold points
	PointCount int
}

func NewManifold

func NewManifold() *Manifold

type ManifoldPoint

type ManifoldPoint struct {
	LocalPoint     Vec2      // usage depends on manifold type
	NormalImpulse  float64   // the non-penetration impulse
	TangentImpulse float64   // the friction impulse
	Id             ContactID // uniquely identifies a contact point between two shapes
}

A manifold point is a contact point belonging to a contact manifold. It holds details related to the geometry and dynamics of the contact points. The local point usage depends on the manifold type: -e_circles: the local center of circleB -e_faceA: the local center of cirlceB or the clip point of polygonB -e_faceB: the clip point of polygonA This structure is stored across time steps, so we keep it small. Note: the impulses are used for internal caching and may not provide reliable contact forces, especially for high speed collisions.

type ManifoldType

type ManifoldType uint8
const (
	Circles ManifoldType = 0
	FaceA   ManifoldType = 1
	FaceB   ManifoldType = 2
)

type MassData

type MassData struct {
	// The mass of the shape, usually in kilograms.
	Mass float64

	// The position of the shape's centroid relative to the shape's origin.
	Center Vec2

	// The rotational inertia of the shape about the local origin.
	I float64
}

This holds the mass data computed for a shape.

func MakeMassData

func MakeMassData() MassData

func NewMassData

func NewMassData() *MassData

type Mat22

type Mat22 struct {
	Ex, Ey Vec2
}

A 2-by-2 matrix. Stored in column-major order.

func MakeMat22

func MakeMat22() Mat22

The default constructor does nothing

func MakeMat22FromColumns

func MakeMat22FromColumns(c1, c2 Vec2) Mat22

Construct this matrix using columns.

func MakeMat22FromScalars

func MakeMat22FromScalars(a11, a12, a21, a22 float64) Mat22

Construct this matrix using scalars.

func Mat22Abs

func Mat22Abs(A Mat22) Mat22

func Mat22Add

func Mat22Add(A, B Mat22) Mat22

func Mat22Mul

func Mat22Mul(A, B Mat22) Mat22

A * B

func Mat22MulT

func Mat22MulT(A, B Mat22) Mat22

A^T * B

func NewMat22

func NewMat22() *Mat22

func NewMat22FromColumns

func NewMat22FromColumns(c1, c2 Vec2) *Mat22

func NewMat22FromScalars

func NewMat22FromScalars(a11, a12, a21, a22 float64) *Mat22

func (Mat22) GetInverse

func (m Mat22) GetInverse() Mat22

func (*Mat22) Set

func (m *Mat22) Set(c1 Vec2, c2 Vec2)

Initialize this matrix using columns.

func (*Mat22) SetIdentity

func (m *Mat22) SetIdentity()

Set this to the identity matrix.

func (*Mat22) SetZero

func (m *Mat22) SetZero()

Set this matrix to all zeros.

func (Mat22) Solve

func (m Mat22) Solve(b Vec2) Vec2

Solve A * x = b, where b is a column vector. This is more efficient than computing the inverse in one-shot cases.

type Mat33

type Mat33 struct {
	Ex, Ey, Ez Vec3
}

A 3-by-3 matrix. Stored in column-major order.

func MakeMat33

func MakeMat33() Mat33

The default constructor does nothing (for performance).

func MakeMat33FromColumns

func MakeMat33FromColumns(c1, c2, c3 Vec3) Mat33

Construct this matrix using columns.

func NewMat33

func NewMat33() *Mat33

func NewMat33FromColumns

func NewMat33FromColumns(c1, c2, c3 Vec3) *Mat33

func (Mat33) GetInverse22

func (mat Mat33) GetInverse22(M *Mat33)

func (Mat33) GetSymInverse33

func (mat Mat33) GetSymInverse33(M *Mat33)

Returns the zero matrix if singular.

func (*Mat33) SetZero

func (m *Mat33) SetZero()

Set this matrix to all zeros.

func (Mat33) Solve22

func (mat Mat33) Solve22(b Vec2) Vec2

Solve A * x = b, where b is a column vector. This is more efficient than computing the inverse in one-shot cases.

func (Mat33) Solve33

func (mat Mat33) Solve33(b Vec3) Vec3

Solve A * x = b, where b is a column vector. This is more efficient than computing the inverse in one-shot cases.

type MotorJoint

type MotorJoint struct {
	*Joint

	// Solver shared
	M_linearOffset     Vec2
	M_angularOffset    float64
	M_linearImpulse    Vec2
	M_angularImpulse   float64
	M_maxForce         float64
	M_maxTorque        float64
	M_correctionFactor float64

	// Solver temp
	M_indexA       int
	M_indexB       int
	M_rA           Vec2
	M_rB           Vec2
	M_localCenterA Vec2
	M_localCenterB Vec2
	M_linearError  Vec2
	M_angularError float64
	M_invMassA     float64
	M_invMassB     float64
	M_invIA        float64
	M_invIB        float64
	M_linearMass   Mat22
	M_angularMass  float64
}

A motor joint is used to control the relative motion between two bodies. A typical usage is to control the movement of a dynamic body with respect to the ground.

func MakeMotorJoint

func MakeMotorJoint(def *MotorJointDef) *MotorJoint

func (*MotorJoint) Dump

func (joint *MotorJoint) Dump()

func (MotorJoint) GetAnchorA

func (joint MotorJoint) GetAnchorA() Vec2

func (MotorJoint) GetAnchorB

func (joint MotorJoint) GetAnchorB() Vec2

func (MotorJoint) GetAngularOffset

func (joint MotorJoint) GetAngularOffset() float64

func (MotorJoint) GetCorrectionFactor

func (joint MotorJoint) GetCorrectionFactor() float64

func (MotorJoint) GetLinearOffset

func (joint MotorJoint) GetLinearOffset() Vec2

func (MotorJoint) GetMaxForce

func (joint MotorJoint) GetMaxForce() float64

func (MotorJoint) GetMaxTorque

func (joint MotorJoint) GetMaxTorque() float64

func (MotorJoint) GetReactionForce

func (joint MotorJoint) GetReactionForce(inv_dt float64) Vec2

func (MotorJoint) GetReactionTorque

func (joint MotorJoint) GetReactionTorque(inv_dt float64) float64

func (*MotorJoint) InitVelocityConstraints

func (joint *MotorJoint) InitVelocityConstraints(data SolverData)

func (*MotorJoint) SetAngularOffset

func (joint *MotorJoint) SetAngularOffset(angularOffset float64)

func (*MotorJoint) SetCorrectionFactor

func (joint *MotorJoint) SetCorrectionFactor(factor float64)

func (*MotorJoint) SetLinearOffset

func (joint *MotorJoint) SetLinearOffset(linearOffset Vec2)

func (*MotorJoint) SetMaxForce

func (joint *MotorJoint) SetMaxForce(force float64)

func (*MotorJoint) SetMaxTorque

func (joint *MotorJoint) SetMaxTorque(torque float64)

func (*MotorJoint) SolvePositionConstraints

func (joint *MotorJoint) SolvePositionConstraints(data SolverData) bool

func (*MotorJoint) SolveVelocityConstraints

func (joint *MotorJoint) SolveVelocityConstraints(data SolverData)

type MotorJointDef

type MotorJointDef struct {
	JointDef

	// Position of bodyB minus the position of bodyA, in bodyA's frame, in meters.
	LinearOffset Vec2

	// The bodyB angle minus bodyA angle in radians.
	AngularOffset float64

	// The maximum motor force in N.
	MaxForce float64

	// The maximum motor torque in N-m.
	MaxTorque float64

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

Motor joint definition.

func MakeMotorJointDef

func MakeMotorJointDef() MotorJointDef

func (*MotorJointDef) Initialize

func (def *MotorJointDef) Initialize(bA *Body, bB *Body)

type MouseJoint

type MouseJoint struct {
	*Joint

	M_localAnchorB Vec2
	M_targetA      Vec2
	M_stiffness    float64
	M_damping      float64
	M_beta         float64

	// Solver shared
	M_impulse  Vec2
	M_maxForce float64
	M_gamma    float64

	// Solver temp
	M_indexA       int
	M_indexB       int
	M_rB           Vec2
	M_localCenterB Vec2
	M_invMassB     float64
	M_invIB        float64
	M_mass         Mat22
	M_C            Vec2
}

A mouse joint is used to make a point on a body track a specified world point. This a soft constraint with a maximum force. This allows the constraint to stretch and without applying huge forces. NOTE: this joint is not documented in the manual because it was developed to be used in the testbed. If you want to learn how to use the mouse joint, look at the testbed.

func MakeMouseJoint

func MakeMouseJoint(def *MouseJointDef) *MouseJoint

func (*MouseJoint) Dump

func (def *MouseJoint) Dump()

The mouse joint does not support dumping.

func (MouseJoint) GetAnchorA

func (joint MouseJoint) GetAnchorA() Vec2

func (MouseJoint) GetAnchorB

func (joint MouseJoint) GetAnchorB() Vec2

func (MouseJoint) GetDamping

func (joint MouseJoint) GetDamping() float64

Get linear damping in N*s/m

func (MouseJoint) GetMaxForce

func (joint MouseJoint) GetMaxForce() float64

Get the maximum force in Newtons.

func (MouseJoint) GetReactionForce

func (joint MouseJoint) GetReactionForce(inv_dt float64) Vec2

func (MouseJoint) GetReactionTorque

func (joint MouseJoint) GetReactionTorque(inv_dt float64) float64

func (MouseJoint) GetStiffness

func (joint MouseJoint) GetStiffness() float64

Get the linear stiffness in N/m

func (MouseJoint) GetTarget

func (joint MouseJoint) GetTarget() Vec2

Use this to update the target point.

func (*MouseJoint) InitVelocityConstraints

func (joint *MouseJoint) InitVelocityConstraints(data SolverData)

func (*MouseJoint) SetDamping

func (joint *MouseJoint) SetDamping(damping float64)

Set linear damping in N*s/m

func (*MouseJoint) SetMaxForce

func (joint *MouseJoint) SetMaxForce(force float64)

Set the maximum force in Newtons.

func (*MouseJoint) SetStiffness

func (joint *MouseJoint) SetStiffness(stiffness float64)

Set the linear stiffness in N/m

func (*MouseJoint) SetTarget

func (joint *MouseJoint) SetTarget(target Vec2)

func (*MouseJoint) ShiftOrigin

func (joint *MouseJoint) ShiftOrigin(newOrigin Vec2)

func (*MouseJoint) SolvePositionConstraints

func (joint *MouseJoint) SolvePositionConstraints(data SolverData) bool

func (*MouseJoint) SolveVelocityConstraints

func (joint *MouseJoint) SolveVelocityConstraints(data SolverData)

type MouseJointDef

type MouseJointDef struct {
	JointDef

	// The initial world target point. This is assumed
	// to coincide with the body anchor initially.
	Target Vec2

	// The maximum constraint force that can be exerted
	// to move the candidate body. Usually you will express
	// as some multiple of the weight (multiplier * mass * gravity).
	MaxForce float64

	// The linear stiffness in N/m
	Stiffness float64

	// The linear damping in N*s/m
	Damping float64
}

Mouse joint definition. This requires a world target point, tuning parameters, and the time step.

func MakeMouseJointDef

func MakeMouseJointDef() MouseJointDef

type Pair

type Pair struct {
	ProxyIdA int
	ProxyIdB int
}

type PairByLessThan

type PairByLessThan []Pair

Was used for sorting the pair buffer to expose duplicates: sort.Sort(PairByLessThan(bp.M_pairBuffer[:bp.M_pairCount]))

func (PairByLessThan) Len

func (a PairByLessThan) Len() int

func (PairByLessThan) Less

func (a PairByLessThan) Less(i, j int) bool

func (PairByLessThan) Swap

func (a PairByLessThan) Swap(i, j int)

type PolygonAndCircleContact

type PolygonAndCircleContact struct {
	Contact
}

func (*PolygonAndCircleContact) Evaluate

func (contact *PolygonAndCircleContact) Evaluate(manifold *Manifold, xfA Transform, xfB Transform)

type PolygonContact

type PolygonContact struct {
	Contact
}

func (*PolygonContact) Evaluate

func (contact *PolygonContact) Evaluate(manifold *Manifold, xfA Transform, xfB Transform)

type PolygonShape

type PolygonShape struct {
	Shape
	Centroid Vec2
	Vertices [MaxPolygonVertices]Vec2
	Normals  [MaxPolygonVertices]Vec2
	Count    int
}

func MakePolygonShape

func MakePolygonShape() PolygonShape

func NewPolygonShape

func NewPolygonShape() *PolygonShape

func (PolygonShape) Clone

func (poly PolygonShape) Clone() IShape

func (PolygonShape) ComputeAABB

func (poly PolygonShape) ComputeAABB(aabb *AABB, xf Transform, childIndex int)

func (PolygonShape) ComputeMass

func (poly PolygonShape) ComputeMass(massData *MassData, density float64)

func (*PolygonShape) Destroy

func (edge *PolygonShape) Destroy()

func (PolygonShape) GetChildCount

func (poly PolygonShape) GetChildCount() int

func (*PolygonShape) GetVertex

func (poly *PolygonShape) GetVertex(index int) *Vec2

func (PolygonShape) RayCast

func (poly PolygonShape) RayCast(output *RayCastOutput, input RayCastInput, xf Transform, childIndex int) bool

@note because the polygon is solid, rays that start inside do not hit because the normal is not defined.

func (*PolygonShape) Set

func (poly *PolygonShape) Set(vertices []Vec2, count int) bool

Create a convex hull from the given array of local points. The count must be in the range [3, b2_maxPolygonVertices]. @warning the points may be re-ordered, even if they form a convex polygon @warning collinear points are handled but not removed. Collinear points may lead to poor stacking behavior.

func (*PolygonShape) SetAsBox

func (poly *PolygonShape) SetAsBox(halfWidth float64, halfHeight float64)

SetAsBox builds vertices to represent an axis-aligned box centered on the local origin.

func (*PolygonShape) SetAsBoxFromCenterAndAngle

func (poly *PolygonShape) SetAsBoxFromCenterAndAngle(hx float64, hy float64, center Vec2, angle float64)

func (*PolygonShape) SetAsHull

func (poly *PolygonShape) SetAsHull(hull Hull)

Create a polygon from a given convex hull (see b2ComputeHull). @warning the hull must be valid or this will crash or have unexpected behavior

func (PolygonShape) TestPoint

func (poly PolygonShape) TestPoint(xf Transform, p Vec2) bool

func (PolygonShape) Validate

func (poly PolygonShape) Validate() bool

type PositionSolverManifold

type PositionSolverManifold struct {
	Normal     Vec2
	Point      Vec2
	Separation float64
}

func MakePositionSolverManifold

func MakePositionSolverManifold() PositionSolverManifold

func (*PositionSolverManifold) Initialize

func (solvermanifold *PositionSolverManifold) Initialize(pc *ContactPositionConstraint, xfA Transform, xfB Transform, index int)

type PrismaticJoint

type PrismaticJoint struct {
	*Joint

	M_localAnchorA     Vec2
	M_localAnchorB     Vec2
	M_localXAxisA      Vec2
	M_localYAxisA      Vec2
	M_referenceAngle   float64
	M_impulse          Vec2
	M_motorImpulse     float64
	M_lowerImpulse     float64
	M_upperImpulse     float64
	M_lowerTranslation float64
	M_upperTranslation float64
	M_maxMotorForce    float64
	M_motorSpeed       float64
	M_enableLimit      bool
	M_enableMotor      bool

	// Solver temp
	M_indexA       int
	M_indexB       int
	M_localCenterA Vec2
	M_localCenterB Vec2
	M_invMassA     float64
	M_invMassB     float64
	M_invIA        float64
	M_invIB        float64
	M_axis, M_perp Vec2
	M_s1, M_s2     float64
	M_a1, M_a2     float64
	M_K            Mat22
	M_translation  float64
	M_axialMass    float64
}

A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in bodyA. Relative rotation is prevented. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction.

func MakePrismaticJoint

func MakePrismaticJoint(def *PrismaticJointDef) *PrismaticJoint

func (*PrismaticJoint) Dump

func (joint *PrismaticJoint) Dump()

func (*PrismaticJoint) EnableLimit

func (joint *PrismaticJoint) EnableLimit(flag bool)

func (*PrismaticJoint) EnableMotor

func (joint *PrismaticJoint) EnableMotor(flag bool)

func (PrismaticJoint) GetAnchorA

func (joint PrismaticJoint) GetAnchorA() Vec2

func (PrismaticJoint) GetAnchorB

func (joint PrismaticJoint) GetAnchorB() Vec2

func (PrismaticJoint) GetJointSpeed

func (joint PrismaticJoint) GetJointSpeed() float64

func (PrismaticJoint) GetJointTranslation

func (joint PrismaticJoint) GetJointTranslation() float64

func (PrismaticJoint) GetLocalAnchorA

func (joint PrismaticJoint) GetLocalAnchorA() Vec2

The local anchor point relative to bodyA's origin.

func (PrismaticJoint) GetLocalAnchorB

func (joint PrismaticJoint) GetLocalAnchorB() Vec2

The local anchor point relative to bodyB's origin.

func (PrismaticJoint) GetLocalAxisA

func (joint PrismaticJoint) GetLocalAxisA() Vec2

The local joint axis relative to bodyA.

func (PrismaticJoint) GetLowerLimit

func (joint PrismaticJoint) GetLowerLimit() float64

func (PrismaticJoint) GetMaxMotorForce

func (joint PrismaticJoint) GetMaxMotorForce() float64

func (PrismaticJoint) GetMotorForce

func (joint PrismaticJoint) GetMotorForce(inv_dt float64) float64

func (PrismaticJoint) GetMotorSpeed

func (joint PrismaticJoint) GetMotorSpeed() float64

func (PrismaticJoint) GetReactionForce

func (joint PrismaticJoint) GetReactionForce(inv_dt float64) Vec2

func (PrismaticJoint) GetReactionTorque

func (joint PrismaticJoint) GetReactionTorque(inv_dt float64) float64

func (PrismaticJoint) GetReferenceAngle

func (joint PrismaticJoint) GetReferenceAngle() float64

Get the reference angle.

func (PrismaticJoint) GetUpperLimit

func (joint PrismaticJoint) GetUpperLimit() float64

func (*PrismaticJoint) InitVelocityConstraints

func (joint *PrismaticJoint) InitVelocityConstraints(data SolverData)

func (PrismaticJoint) IsLimitEnabled

func (joint PrismaticJoint) IsLimitEnabled() bool

func (PrismaticJoint) IsMotorEnabled

func (joint PrismaticJoint) IsMotorEnabled() bool

func (*PrismaticJoint) SetLimits

func (joint *PrismaticJoint) SetLimits(lower float64, upper float64)

func (*PrismaticJoint) SetMaxMotorForce

func (joint *PrismaticJoint) SetMaxMotorForce(force float64)

func (*PrismaticJoint) SetMotorSpeed

func (joint *PrismaticJoint) SetMotorSpeed(speed float64)

func (*PrismaticJoint) SolvePositionConstraints

func (joint *PrismaticJoint) SolvePositionConstraints(data SolverData) bool

A velocity based solver computes reaction forces(impulses) using the velocity constraint solver.Under this context, the position solver is not there to resolve forces.It is only there to cope with integration error.

Therefore, the pseudo impulses in the position solver do not have any physical meaning.Thus it is okay if they suck.

We could take the active state from the velocity solver.However, the joint might push past the limit when the velocity solver indicates the limit is inactive.

func (*PrismaticJoint) SolveVelocityConstraints

func (joint *PrismaticJoint) SolveVelocityConstraints(data SolverData)

type PrismaticJointDef

type PrismaticJointDef struct {
	JointDef

	// The local anchor point relative to bodyA's origin.
	LocalAnchorA Vec2

	// The local anchor point relative to bodyB's origin.
	LocalAnchorB Vec2

	// The local translation unit axis in bodyA.
	LocalAxisA Vec2

	// The constrained angle between the bodies: bodyB_angle - bodyA_angle.
	ReferenceAngle float64

	// Enable/disable the joint limit.
	EnableLimit bool

	// The lower translation limit, usually in meters.
	LowerTranslation float64

	// The upper translation limit, usually in meters.
	UpperTranslation float64

	// Enable/disable the joint motor.
	EnableMotor bool

	// The maximum motor torque, usually in N-m.
	MaxMotorForce float64

	// The desired motor speed in radians per second.
	MotorSpeed float64
}

Prismatic joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game.

func MakePrismaticJointDef

func MakePrismaticJointDef() PrismaticJointDef

func (*PrismaticJointDef) Initialize

func (joint *PrismaticJointDef) Initialize(bA *Body, bB *Body, anchor Vec2, axis Vec2)

type Profile

type Profile struct {
	Step          float64
	Collide       float64
	Solve         float64
	SolveInit     float64
	SolveVelocity float64
	SolvePosition float64
	Broadphase    float64
	SolveTOI      float64
}

Profiling data. Times are in milliseconds.

type PulleyJoint

type PulleyJoint struct {
	*Joint

	M_groundAnchorA Vec2
	M_groundAnchorB Vec2
	M_lengthA       float64
	M_lengthB       float64

	// Solver shared
	M_localAnchorA Vec2
	M_localAnchorB Vec2
	M_constant     float64
	M_ratio        float64
	M_impulse      float64

	// Solver temp
	M_indexA       int
	M_indexB       int
	M_uA           Vec2
	M_uB           Vec2
	M_rA           Vec2
	M_rB           Vec2
	M_localCenterA Vec2
	M_localCenterB Vec2
	M_invMassA     float64
	M_invMassB     float64
	M_invIA        float64
	M_invIB        float64
	M_mass         float64
}

The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that: length1 + ratio * length2 <= constant Yes, the force transmitted is scaled by the ratio. Warning: the pulley joint can get a bit squirrelly by itself. They often work better when combined with prismatic joints. You should also cover the the anchor points with static shapes to prevent one side from going to zero length.

func MakePulleyJoint

func MakePulleyJoint(def *PulleyJointDef) *PulleyJoint

func (*PulleyJoint) Dump

func (joint *PulleyJoint) Dump()

func (PulleyJoint) GetAnchorA

func (joint PulleyJoint) GetAnchorA() Vec2

func (PulleyJoint) GetAnchorB

func (joint PulleyJoint) GetAnchorB() Vec2

func (PulleyJoint) GetCurrentLengthA

func (joint PulleyJoint) GetCurrentLengthA() float64

func (PulleyJoint) GetCurrentLengthB

func (joint PulleyJoint) GetCurrentLengthB() float64

func (PulleyJoint) GetGroundAnchorA

func (joint PulleyJoint) GetGroundAnchorA() Vec2

func (PulleyJoint) GetGroundAnchorB

func (joint PulleyJoint) GetGroundAnchorB() Vec2

func (PulleyJoint) GetLengthA

func (joint PulleyJoint) GetLengthA() float64

func (PulleyJoint) GetLengthB

func (joint PulleyJoint) GetLengthB() float64

func (PulleyJoint) GetRatio

func (joint PulleyJoint) GetRatio() float64

func (PulleyJoint) GetReactionForce

func (joint PulleyJoint) GetReactionForce(inv_dt float64) Vec2

func (PulleyJoint) GetReactionTorque

func (joint PulleyJoint) GetReactionTorque(inv_dt float64) float64

func (*PulleyJoint) InitVelocityConstraints

func (joint *PulleyJoint) InitVelocityConstraints(data SolverData)

func (*PulleyJoint) ShiftOrigin

func (joint *PulleyJoint) ShiftOrigin(newOrigin Vec2)

func (*PulleyJoint) SolvePositionConstraints

func (joint *PulleyJoint) SolvePositionConstraints(data SolverData) bool

func (*PulleyJoint) SolveVelocityConstraints

func (joint *PulleyJoint) SolveVelocityConstraints(data SolverData)

type PulleyJointDef

type PulleyJointDef struct {
	JointDef

	// The first ground anchor in world coordinates. This point never moves.
	GroundAnchorA Vec2

	// The second ground anchor in world coordinates. This point never moves.
	GroundAnchorB Vec2

	// The local anchor point relative to bodyA's origin.
	LocalAnchorA Vec2

	// The local anchor point relative to bodyB's origin.
	LocalAnchorB Vec2

	// The a reference length for the segment attached to bodyA.
	LengthA float64

	// The a reference length for the segment attached to bodyB.
	LengthB float64

	// The pulley ratio, used to simulate a block-and-tackle.
	Ratio float64
}

Pulley joint definition. This requires two ground anchors, two dynamic body anchor points, and a pulley ratio.

func MakePulleyJointDef

func MakePulleyJointDef() PulleyJointDef

func (*PulleyJointDef) Initialize

func (def *PulleyJointDef) Initialize(bA *Body, bB *Body, groundA Vec2, groundB Vec2, anchorA Vec2, anchorB Vec2, r float64)

type RayCastInput

type RayCastInput struct {
	P1, P2      Vec2
	MaxFraction float64
}

Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).

type RayCastOutput

type RayCastOutput struct {
	Normal   Vec2
	Fraction float64
}

Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2 come from b2RayCastInput.

func MakeRayCastOutput

func MakeRayCastOutput() RayCastOutput

type RaycastCallback

type RaycastCallback func(fixture *Fixture, point Vec2, normal Vec2, fraction float64) float64

Called for each fixture found in the query. You control how the ray cast proceeds by returning a float: return -1: ignore this fixture and continue return 0: terminate the ray cast return fraction: clip the ray to this point return 1: don't clip the ray and continue @param fixture the fixture hit by the ray @param point the point of initial intersection @param normal the normal vector at the point of intersection @return -1 to filter, 0 to terminate, fraction to clip the ray for closest hit, 1 to continue

type RevoluteJoint

type RevoluteJoint struct {
	*Joint

	// Solver shared
	M_localAnchorA Vec2
	M_localAnchorB Vec2

	M_motorImpulse   float64
	M_lowerImpulse   float64
	M_upperImpulse   float64
	M_enableMotor    bool
	M_maxMotorTorque float64
	M_motorSpeed     float64
	M_enableLimit    bool
	M_referenceAngle float64
	M_lowerAngle     float64
	M_upperAngle     float64

	// Solver temp
	M_indexA       int
	M_indexB       int
	M_rA           Vec2
	M_rB           Vec2
	M_localCenterA Vec2
	M_localCenterB Vec2
	M_invMassA     float64
	M_invMassB     float64
	M_invIA        float64
	M_invIB        float64
	M_K            Mat22
	M_angle        float64
	M_axialMass    float64
	// contains filtered or unexported fields
}

A revolute joint constrains two bodies to share a common point while they are free to rotate about the point. The relative rotation about the shared point is the joint angle. You can limit the relative rotation with a joint limit that specifies a lower and upper angle. You can use a motor to drive the relative rotation about the shared point. A maximum motor torque is provided so that infinite forces are not generated.

func MakeRevoluteJoint

func MakeRevoluteJoint(def *RevoluteJointDef) *RevoluteJoint

func (*RevoluteJoint) Dump

func (joint *RevoluteJoint) Dump()

func (*RevoluteJoint) EnableLimit

func (joint *RevoluteJoint) EnableLimit(flag bool)

func (*RevoluteJoint) EnableMotor

func (joint *RevoluteJoint) EnableMotor(flag bool)

func (RevoluteJoint) GetAnchorA

func (joint RevoluteJoint) GetAnchorA() Vec2

func (RevoluteJoint) GetAnchorB

func (joint RevoluteJoint) GetAnchorB() Vec2

func (RevoluteJoint) GetJointAngle

func (joint RevoluteJoint) GetJointAngle() float64

func (*RevoluteJoint) GetJointSpeed

func (joint *RevoluteJoint) GetJointSpeed() float64

func (RevoluteJoint) GetLocalAnchorA

func (joint RevoluteJoint) GetLocalAnchorA() Vec2

The local anchor point relative to bodyA's origin.

func (RevoluteJoint) GetLocalAnchorB

func (joint RevoluteJoint) GetLocalAnchorB() Vec2

The local anchor point relative to bodyB's origin.

func (RevoluteJoint) GetLowerLimit

func (joint RevoluteJoint) GetLowerLimit() float64

func (RevoluteJoint) GetMaxMotorTorque

func (joint RevoluteJoint) GetMaxMotorTorque() float64

func (RevoluteJoint) GetMotorSpeed

func (joint RevoluteJoint) GetMotorSpeed() float64

func (RevoluteJoint) GetMotorTorque

func (joint RevoluteJoint) GetMotorTorque(inv_dt float64) float64

func (RevoluteJoint) GetReactionForce

func (joint RevoluteJoint) GetReactionForce(inv_dt float64) Vec2

func (RevoluteJoint) GetReactionTorque

func (joint RevoluteJoint) GetReactionTorque(inv_dt float64) float64

func (RevoluteJoint) GetReferenceAngle

func (joint RevoluteJoint) GetReferenceAngle() float64

Get the reference angle.

func (RevoluteJoint) GetUpperLimit

func (joint RevoluteJoint) GetUpperLimit() float64

func (*RevoluteJoint) InitVelocityConstraints

func (joint *RevoluteJoint) InitVelocityConstraints(data SolverData)

func (RevoluteJoint) IsLimitEnabled

func (joint RevoluteJoint) IsLimitEnabled() bool

func (RevoluteJoint) IsMotorEnabled

func (joint RevoluteJoint) IsMotorEnabled() bool

func (*RevoluteJoint) SetLimits

func (joint *RevoluteJoint) SetLimits(lower float64, upper float64)

func (*RevoluteJoint) SetMaxMotorTorque

func (joint *RevoluteJoint) SetMaxMotorTorque(torque float64)

func (*RevoluteJoint) SetMotorSpeed

func (joint *RevoluteJoint) SetMotorSpeed(speed float64)

func (*RevoluteJoint) SolvePositionConstraints

func (joint *RevoluteJoint) SolvePositionConstraints(data SolverData) bool

func (*RevoluteJoint) SolveVelocityConstraints

func (joint *RevoluteJoint) SolveVelocityConstraints(data SolverData)

type RevoluteJointDef

type RevoluteJointDef struct {
	JointDef

	// The local anchor point relative to bodyA's origin.
	LocalAnchorA Vec2

	// The local anchor point relative to bodyB's origin.
	LocalAnchorB Vec2

	// The bodyB angle minus bodyA angle in the reference state (radians).
	ReferenceAngle float64

	// A flag to enable joint limits.
	EnableLimit bool

	// The lower angle for the joint limit (radians).
	LowerAngle float64

	// The upper angle for the joint limit (radians).
	UpperAngle float64

	// A flag to enable the joint motor.
	EnableMotor bool

	// The desired motor speed. Usually in radians per second.
	MotorSpeed float64

	// The maximum motor torque used to achieve the desired motor speed.
	// Usually in N-m.
	MaxMotorTorque float64
}

Revolute joint definition. This requires defining an anchor point where the bodies are joined. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. You also need to specify the initial relative angle for joint limits. This helps when saving and loading a game. The local anchor points are measured from the body's origin rather than the center of mass because:

  1. you might not know where the center of mass will be.
  2. if you add/remove shapes from a body and recompute the mass, the joints will be broken.

func MakeRevoluteJointDef

func MakeRevoluteJointDef() RevoluteJointDef

func (*RevoluteJointDef) Initialize

func (def *RevoluteJointDef) Initialize(bA *Body, bB *Body, anchor Vec2)

type Rope

type Rope struct {
	M_position Vec2

	M_count        int
	M_stretchCount int
	M_bendCount    int

	M_stretchConstraints []RopeStretch
	M_bendConstraints    []RopeBend

	M_bindPositions []Vec2
	M_ps            []Vec2
	M_p0s           []Vec2
	M_vs            []Vec2

	M_invMasses []float64
	M_gravity   Vec2

	M_tuning RopeTuning
}

func MakeRope

func MakeRope() Rope

func (*Rope) ApplyBendForces

func (rope *Rope) ApplyBendForces(dt float64)

func (*Rope) Create

func (rope *Rope) Create(def *RopeDef)

func (*Rope) Destroy

func (rope *Rope) Destroy()

func (Rope) GetVertexCount

func (rope Rope) GetVertexCount() int

func (Rope) GetVertices

func (rope Rope) GetVertices() []Vec2

func (*Rope) Reset

func (rope *Rope) Reset(position Vec2)

func (*Rope) SetTuning

func (rope *Rope) SetTuning(tuning RopeTuning)

func (*Rope) SolveBend_PBD_Angle

func (rope *Rope) SolveBend_PBD_Angle()

func (*Rope) SolveBend_PBD_Distance

func (rope *Rope) SolveBend_PBD_Distance()

func (*Rope) SolveBend_PBD_Height

func (rope *Rope) SolveBend_PBD_Height()

Constraint based implementation of: P. Volino: Simple Linear Bending Stiffness in Particle Systems

func (*Rope) SolveBend_PBD_Triangle

func (rope *Rope) SolveBend_PBD_Triangle()

M. Kelager: A Triangle Bending Constraint Model for PBD

func (*Rope) SolveBend_XPBD_Angle

func (rope *Rope) SolveBend_XPBD_Angle(dt float64)

func (*Rope) SolveStretch_PBD

func (rope *Rope) SolveStretch_PBD()

func (*Rope) SolveStretch_XPBD

func (rope *Rope) SolveStretch_XPBD(dt float64)

func (*Rope) Step

func (rope *Rope) Step(dt float64, iterations int, position Vec2)

type RopeBend

type RopeBend struct {
	I1               int
	I2               int
	I3               int
	InvMass1         float64
	InvMass2         float64
	InvMass3         float64
	InvEffectiveMass float64
	Lambda           float64
	L1               float64
	L2               float64

	Spring float64
	Damper float64
	// contains filtered or unexported fields
}

type RopeDef

type RopeDef struct {
	Position Vec2
	Vertices []Vec2
	Count    int
	Masses   []float64
	Gravity  Vec2
	Tuning   RopeTuning
}

func MakeRopeDef

func MakeRopeDef() RopeDef

type RopeStretch

type RopeStretch struct {
	I1       int
	I2       int
	InvMass1 float64
	InvMass2 float64
	L        float64
	Lambda   float64
	Spring   float64
	Damper   float64
}

type RopeTuning

type RopeTuning struct {
	StretchingModel    uint8
	BendingModel       uint8
	Damping            float64
	StretchStiffness   float64
	StretchHertz       float64
	StretchDamping     float64
	BendStiffness      float64
	BendHertz          float64
	BendDamping        float64
	Isometric          bool
	FixedEffectiveMass bool
	WarmStart          bool
}

func MakeRopeTuning

func MakeRopeTuning() RopeTuning

type Rot

type Rot struct {
	/// Sine and cosine
	Sine, Cosine float64
}

Rotation

func MakeRotFromAngle

func MakeRotFromAngle(anglerad float64) Rot

Initialize from an angle in radians

func NewRotFromAngle

func NewRotFromAngle(anglerad float64) *Rot

func RotMul

func RotMul(q, r Rot) Rot

Multiply two rotations: q * r

func RotMulT

func RotMulT(q, r Rot) Rot

Transpose multiply two rotations: qT * r

func (Rot) GetAngle

func (r Rot) GetAngle() float64

Get the angle in radians

func (Rot) GetXAxis

func (r Rot) GetXAxis() Vec2

Get the x-axis

func (Rot) GetYAxis

func (r Rot) GetYAxis() Vec2

Get the u-axis

func (*Rot) Set

func (r *Rot) Set(anglerad float64)

Set using an angle in radians.

func (*Rot) SetIdentity

func (r *Rot) SetIdentity()

Set to the identity rotation

type SeparationFunction

type SeparationFunction struct {
	M_proxyA           *DistanceProxy
	M_proxyB           *DistanceProxy
	M_sweepA, M_sweepB Sweep
	M_type             uint8
	M_localPoint       Vec2
	M_axis             Vec2
}

func (*SeparationFunction) Evaluate

func (sepfunc *SeparationFunction) Evaluate(indexA int, indexB int, t float64) float64

func (*SeparationFunction) FindMinSeparation

func (sepfunc *SeparationFunction) FindMinSeparation(indexA *int, indexB *int, t float64) float64

func (*SeparationFunction) Initialize

func (sepfunc *SeparationFunction) Initialize(cache *simplexCache, proxyA *DistanceProxy, sweepA Sweep, proxyB *DistanceProxy, sweepB Sweep, t1 float64) float64

TODO_ERIN might not need to return the separation

type Shape

type Shape struct {
	ShapeType ShapeType
	// Radius of a shape. For polygonal shapes this must be b2_polygonRadius. There is no support for
	// making rounded polygons.
	Radius float64
}

func (Shape) GetRadius

func (shape Shape) GetRadius() float64

func (Shape) GetType

func (shape Shape) GetType() ShapeType

func (*Shape) SetRadius

func (shape *Shape) SetRadius(r float64)

@addedgo

type ShapeCastInput

type ShapeCastInput struct {
	ProxyA       DistanceProxy
	ProxyB       DistanceProxy
	TransformA   Transform
	TransformB   Transform
	TranslationB Vec2
}

Input parameters for b2ShapeCast

func MakeShapeCastInput

func MakeShapeCastInput() ShapeCastInput

type ShapeCastOutput

type ShapeCastOutput struct {
	Point      Vec2
	Normal     Vec2
	Lambda     float64
	Iterations int
}

Output results for b2ShapeCast

type ShapeType

type ShapeType uint8
const (
	Circle ShapeType = iota
	Edge
	Polygon
	Chain
)

type Simplex

type Simplex struct {
	M_vs    [3]SimplexVertex
	M_count int
}

func MakeSimplex

func MakeSimplex() Simplex

func (Simplex) GetClosestPoint

func (simplex Simplex) GetClosestPoint() Vec2

func (Simplex) GetMetric

func (simplex Simplex) GetMetric() float64

func (Simplex) GetSearchDirection

func (simplex Simplex) GetSearchDirection() Vec2

func (Simplex) GetWitnessPoints

func (simplex Simplex) GetWitnessPoints(pA *Vec2, pB *Vec2)

func (*Simplex) ReadCache

func (simplex *Simplex) ReadCache(cache *simplexCache, proxyA *DistanceProxy, transformA Transform, proxyB *DistanceProxy, transformB Transform)

func (*Simplex) Solve2

func (simplex *Simplex) Solve2()

Solve a line segment using barycentric coordinates.

func (*Simplex) Solve3

func (simplex *Simplex) Solve3()

Possible regions: - points[2] - edge points[0]-points[2] - edge points[1]-points[2] - inside the triangle

func (Simplex) WriteCache

func (simplex Simplex) WriteCache(cache *simplexCache)

type SimplexVertex

type SimplexVertex struct {
	WA     Vec2    // support point in proxyA
	WB     Vec2    // support point in proxyB
	W      Vec2    // wB - wA
	A      float64 // barycentric coordinate for closest point
	IndexA int     // wA index
	IndexB int     // wB index
}

func MakeSimplexVertex

func MakeSimplexVertex() SimplexVertex

type SolverData

type SolverData struct {
	Step       TimeStep
	Positions  []position
	Velocities []velocity
}

Solver Data

type Sweep

type Sweep struct {
	LocalCenter Vec2    // local center of mass position
	C0, C       Vec2    // center world positions
	A0, A       float64 // world angles

	// Fraction of the current time step in the range [0,1]
	// c0 and a0 are the positions at alpha0.
	Alpha0 float64
}

func (*Sweep) Advance

func (sweep *Sweep) Advance(alpha float64)

func (*Sweep) Normalize

func (sweep *Sweep) Normalize()

Normalize an angle in radians to be between -pi and pi

type TOIInput

type TOIInput struct {
	ProxyA DistanceProxy
	ProxyB DistanceProxy
	SweepA Sweep
	SweepB Sweep
	TMax   float64 // defines sweep interval [0, tMax]
}

Input parameters for b2TimeOfImpact

func MakeTOIInput

func MakeTOIInput() TOIInput

type TOIOutput

type TOIOutput struct {
	State ToiOutputState
	T     float64
}

func MakeTOIOutput

func MakeTOIOutput() TOIOutput

type TimeStep

type TimeStep struct {
	Dt                 float64 // time step
	Inv_dt             float64 // inverse time step (0 if dt == 0).
	DtRatio            float64 // dt * inv_dt0
	VelocityIterations int
	PositionIterations int
	WarmStarting       bool
}

This is an internal structure.

func MakeTimeStep

func MakeTimeStep() TimeStep

type Timer

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

Timer for profiling. This has platform specific code and may not work on every platform.

func MakeTimer

func MakeTimer() Timer

func (Timer) GetMilliseconds

func (timer Timer) GetMilliseconds() float64

func (*Timer) Reset

func (timer *Timer) Reset()

type ToiOutputState

type ToiOutputState uint8

type Transform

type Transform struct {
	P Vec2
	Q Rot
}

A transform contains translation and rotation. It is used to represent the position and orientation of rigid frames.

func MakeTransform

func MakeTransform() Transform

The default constructor does nothing.

func MakeTransformByPositionAndRotation

func MakeTransformByPositionAndRotation(position Vec2, rotation Rot) Transform

Initialize using a position vector and a rotation.

func NewTransform

func NewTransform() *Transform

func NewTransformByPositionAndRotation

func NewTransformByPositionAndRotation(position Vec2, rotation Rot) *Transform

func TransformMul

func TransformMul(A, B Transform) Transform

func TransformMulT

func TransformMulT(A, B Transform) Transform

func (*Transform) Set

func (t *Transform) Set(position Vec2, anglerad float64)

Set this based on the position and angle.

func (*Transform) SetIdentity

func (t *Transform) SetIdentity()

Set this to the identity transform.

type TreeNode

type TreeNode struct {

	// Enlarged AABB
	Aabb AABB

	UserData any

	// union
	// {
	Parent int
	Next   int

	Child1 int
	Child2 int

	// leaf = 0, free node = -1
	Height int

	Moved bool
}

func (TreeNode) IsLeaf

func (node TreeNode) IsLeaf() bool

type TreeQueryCallback

type TreeQueryCallback func(nodeId int) bool

type TreeRayCastCallback

type TreeRayCastCallback func(input RayCastInput, nodeId int) float64

type Vec2

type Vec2 struct {
	X, Y float64
}

A 2D column vector.

func ComputeCentroid

func ComputeCentroid(vs []Vec2, count int) Vec2

func NewVec2

func NewVec2(xIn, yIn float64) *Vec2

Construct using coordinates.

func ProjectPointOnLine

func ProjectPointOnLine(v1 Vec2, v2 Vec2, p Vec2) Vec2

Get projected point p' of p on line v1,v2

func RotVec2Mul

func RotVec2Mul(q Rot, v Vec2) Vec2

Rotate a vector

func RotVec2MulT

func RotVec2MulT(q Rot, v Vec2) Vec2

Inverse rotate a vector

func TransformVec2Mul

func TransformVec2Mul(T Transform, v Vec2) Vec2

func TransformVec2MulT

func TransformVec2MulT(T Transform, v Vec2) Vec2

func Vec2Abs

func Vec2Abs(a Vec2) Vec2

func Vec2Add

func Vec2Add(a, b Vec2) Vec2

Add two vectors component-wise.

func Vec2Clamp

func Vec2Clamp(a, low, high Vec2) Vec2

func Vec2CrossScalarVector

func Vec2CrossScalarVector(s float64, a Vec2) Vec2

Perform the cross product on a scalar and a vector. In 2D this produces a vector.

func Vec2CrossVectorScalar

func Vec2CrossVectorScalar(a Vec2, s float64) Vec2

Perform the cross product on a vector and a scalar. In 2D this produces a vector.

func Vec2Mat22Mul

func Vec2Mat22Mul(A Mat22, v Vec2) Vec2

Multiply a matrix times a vector. If a rotation matrix is provided, then this transforms the vector from one frame to another.

func Vec2Mat22MulT

func Vec2Mat22MulT(A Mat22, v Vec2) Vec2

Multiply a matrix transpose times a vector. If a rotation matrix is provided, then this transforms the vector from one frame to another (inverse transform).

func Vec2Max

func Vec2Max(a, b Vec2) Vec2

func Vec2Min

func Vec2Min(a, b Vec2) Vec2

func Vec2Mul22

func Vec2Mul22(A Mat33, v Vec2) Vec2

Multiply a matrix times a vector.

func Vec2MulScalar

func Vec2MulScalar(s float64, a Vec2) Vec2

func Vec2Sub

func Vec2Sub(a, b Vec2) Vec2

Subtract two vectors component-wise.

func (Vec2) IsValid

func (v Vec2) IsValid() bool

Does this vector contain finite coordinates?

func (Vec2) Length

func (v Vec2) Length() float64

Get the length of this vector (the norm).

func (Vec2) LengthSquared

func (v Vec2) LengthSquared() float64

Get the length squared. For performance, use this instead of b2Vec2::Length (if possible).

func (*Vec2) Normalize

func (v *Vec2) Normalize() float64

Convert this vector into a unit vector. Returns the length.

func (Vec2) OperatorIndexGet

func (v Vec2) OperatorIndexGet(i int) float64

Read from and indexed element.

func (*Vec2) OperatorIndexSet

func (v *Vec2) OperatorIndexSet(i int, value float64)

Write to an indexed element.

func (*Vec2) OperatorMinusInplace

func (v *Vec2) OperatorMinusInplace(other Vec2)

Subtract a vector from this vector.

func (Vec2) OperatorNegate

func (v Vec2) OperatorNegate() Vec2

Negate this vector.

func (*Vec2) OperatorPlusInplace

func (v *Vec2) OperatorPlusInplace(other Vec2)

Add a vector to this vector.

func (*Vec2) OperatorScalarMulInplace

func (v *Vec2) OperatorScalarMulInplace(a float64)

Multiply this vector by a scalar.

func (*Vec2) Set

func (v *Vec2) Set(x, y float64)

Set this vector to some specified coordinates.

func (*Vec2) SetZero

func (v *Vec2) SetZero()

Set this vector to all zeros.

func (Vec2) Skew

func (v Vec2) Skew() Vec2

Get the skew vector such that dot(skew_vec, other) == cross(vec, other)

type Vec3

type Vec3 struct {
	X, Y, Z float64
}

A 2D column vector with 3 elements.

func MakeVec3

func MakeVec3(xIn, yIn, zIn float64) Vec3

Construct using coordinates.

func NewVec3

func NewVec3(xIn, yIn, zIn float64) *Vec3

func Vec3Add

func Vec3Add(a, b Vec3) Vec3

Add two vectors component-wise.

func Vec3Cross

func Vec3Cross(a, b Vec3) Vec3

Perform the cross product on two vectors.

func Vec3Mat33Mul

func Vec3Mat33Mul(A Mat33, v Vec3) Vec3

Multiply a matrix times a vector.

func Vec3MultScalar

func Vec3MultScalar(s float64, a Vec3) Vec3

func Vec3Sub

func Vec3Sub(a, b Vec3) Vec3

Subtract two vectors component-wise.

func (*Vec3) OperatorMinusInplace

func (v *Vec3) OperatorMinusInplace(other Vec3)

Subtract a vector from this vector.

func (Vec3) OperatorNegate

func (v Vec3) OperatorNegate() Vec3

Negate this vector.

func (*Vec3) OperatorPlusInplace

func (v *Vec3) OperatorPlusInplace(other Vec3)

Add a vector to this vector.

func (*Vec3) OperatorScalarMulInplace

func (v *Vec3) OperatorScalarMulInplace(a float64)

Multiply this vector by a scalar.

func (*Vec3) Set

func (v *Vec3) Set(x, y, z float64)

Set this vector to some specified coordinates.

func (*Vec3) SetZero

func (v *Vec3) SetZero()

Set this vector to all zeros.

type VelocityConstraintPoint

type VelocityConstraintPoint struct {
	RA             Vec2
	RB             Vec2
	NormalImpulse  float64
	TangentImpulse float64
	NormalMass     float64
	TangentMass    float64
	VelocityBias   float64
}

type WeldJoint

type WeldJoint struct {
	*Joint

	M_stiffness float64
	M_damping   float64
	M_bias      float64

	// Solver shared
	M_localAnchorA   Vec2
	M_localAnchorB   Vec2
	M_referenceAngle float64
	M_gamma          float64
	M_impulse        Vec3

	// Solver temp
	M_indexA       int
	M_indexB       int
	M_rA           Vec2
	M_rB           Vec2
	M_localCenterA Vec2
	M_localCenterB Vec2
	M_invMassA     float64
	M_invMassB     float64
	M_invIA        float64
	M_invIB        float64
	M_mass         Mat33
}

A weld joint essentially glues two bodies together. A weld joint may distort somewhat because the island constraint solver is approximate.

func MakeWeldJoint

func MakeWeldJoint(def *WeldJointDef) *WeldJoint

func (*WeldJoint) Dump

func (joint *WeldJoint) Dump()

func (WeldJoint) GetAnchorA

func (joint WeldJoint) GetAnchorA() Vec2

func (WeldJoint) GetAnchorB

func (joint WeldJoint) GetAnchorB() Vec2

func (WeldJoint) GetDamping

func (joint WeldJoint) GetDamping() float64

Get damping in N*m*s

func (WeldJoint) GetLocalAnchorA

func (joint WeldJoint) GetLocalAnchorA() Vec2

The local anchor point relative to bodyA's origin.

func (WeldJoint) GetLocalAnchorB

func (joint WeldJoint) GetLocalAnchorB() Vec2

The local anchor point relative to bodyB's origin.

func (WeldJoint) GetReactionForce

func (joint WeldJoint) GetReactionForce(inv_dt float64) Vec2

func (WeldJoint) GetReactionTorque

func (joint WeldJoint) GetReactionTorque(inv_dt float64) float64

func (WeldJoint) GetReferenceAngle

func (joint WeldJoint) GetReferenceAngle() float64

Get the reference angle.

func (WeldJoint) GetStiffness

func (joint WeldJoint) GetStiffness() float64

Get stiffness in N*m

func (*WeldJoint) InitVelocityConstraints

func (joint *WeldJoint) InitVelocityConstraints(data SolverData)

func (*WeldJoint) SetDamping

func (joint *WeldJoint) SetDamping(damping float64)

Set damping in N*m*s

func (*WeldJoint) SetStiffness

func (joint *WeldJoint) SetStiffness(stiffness float64)

Set stiffness in N*m

func (*WeldJoint) SolvePositionConstraints

func (joint *WeldJoint) SolvePositionConstraints(data SolverData) bool

func (*WeldJoint) SolveVelocityConstraints

func (joint *WeldJoint) SolveVelocityConstraints(data SolverData)

type WeldJointDef

type WeldJointDef struct {
	JointDef

	// The local anchor point relative to bodyA's origin.
	LocalAnchorA Vec2

	// The local anchor point relative to bodyB's origin.
	LocalAnchorB Vec2

	// The bodyB angle minus bodyA angle in the reference state (radians).
	ReferenceAngle float64

	// The rotational stiffness in N*m
	// Disable softness with a value of 0
	Stiffness float64

	// The rotational damping in N*m*s
	Damping float64
}

Weld joint definition. You need to specify local anchor points where they are attached and the relative body angle. The position of the anchor points is important for computing the reaction torque.

func MakeWeldJointDef

func MakeWeldJointDef() WeldJointDef

func (*WeldJointDef) Initialize

func (def *WeldJointDef) Initialize(bA *Body, bB *Body, anchor Vec2)

Initialize the bodies, anchors, reference angle, stiffness, and damping. @param bodyA the first body connected by this joint @param bodyB the second body connected by this joint @param anchor the point of connection in world coordinates

type WheelJoint

type WheelJoint struct {
	*Joint

	M_localAnchorA Vec2
	M_localAnchorB Vec2
	M_localXAxisA  Vec2
	M_localYAxisA  Vec2

	M_impulse       float64
	M_motorImpulse  float64
	M_springImpulse float64

	M_lowerImpulse     float64
	M_upperImpulse     float64
	M_translation      float64
	M_lowerTranslation float64
	M_upperTranslation float64

	M_maxMotorTorque float64
	M_motorSpeed     float64

	M_enableLimit bool
	M_enableMotor bool

	M_stiffness float64
	M_damping   float64

	// Solver temp
	M_indexA       int
	M_indexB       int
	M_localCenterA Vec2
	M_localCenterB Vec2
	M_invMassA     float64
	M_invMassB     float64
	M_invIA        float64
	M_invIB        float64

	M_ax  Vec2
	M_ay  Vec2
	M_sAx float64
	M_sBx float64
	M_sAy float64
	M_sBy float64

	M_mass       float64
	M_motorMass  float64
	M_axialMass  float64
	M_springMass float64

	M_bias  float64
	M_gamma float64
}

A wheel joint. This joint provides two degrees of freedom: translation along an axis fixed in bodyA and rotation in the plane. In other words, it is a point to line constraint with a rotational motor and a linear spring/damper. The spring/damper is initialized upon creation. This joint is designed for vehicle suspensions.

func MakeWheelJoint

func MakeWheelJoint(def *WheelJointDef) *WheelJoint

func (*WheelJoint) Dump

func (joint *WheelJoint) Dump()

func (WheelJoint) EnableLimit

func (joint WheelJoint) EnableLimit(flag bool)

Enable/disable the joint translation limit.

func (*WheelJoint) EnableMotor

func (joint *WheelJoint) EnableMotor(flag bool)

func (WheelJoint) GetAnchorA

func (joint WheelJoint) GetAnchorA() Vec2

func (WheelJoint) GetAnchorB

func (joint WheelJoint) GetAnchorB() Vec2

func (WheelJoint) GetDamping

func (joint WheelJoint) GetDamping() float64

Access damping

func (WheelJoint) GetJointAngle

func (joint WheelJoint) GetJointAngle() float64

func (WheelJoint) GetJointAngularSpeed

func (joint WheelJoint) GetJointAngularSpeed() float64

func (WheelJoint) GetJointLinearSpeed

func (joint WheelJoint) GetJointLinearSpeed() float64

func (WheelJoint) GetJointTranslation

func (joint WheelJoint) GetJointTranslation() float64

func (WheelJoint) GetLocalAnchorA

func (joint WheelJoint) GetLocalAnchorA() Vec2

The local anchor point relative to bodyA's origin.

func (WheelJoint) GetLocalAnchorB

func (joint WheelJoint) GetLocalAnchorB() Vec2

The local anchor point relative to bodyB's origin.

func (WheelJoint) GetLocalAxisA

func (joint WheelJoint) GetLocalAxisA() Vec2

The local joint axis relative to bodyA.

func (WheelJoint) GetLowerLimit

func (joint WheelJoint) GetLowerLimit() float64

Get the lower joint translation limit, usually in meters.

func (WheelJoint) GetMaxMotorTorque

func (joint WheelJoint) GetMaxMotorTorque() float64

func (WheelJoint) GetMotorSpeed

func (joint WheelJoint) GetMotorSpeed() float64

func (WheelJoint) GetMotorTorque

func (joint WheelJoint) GetMotorTorque(inv_dt float64) float64

func (WheelJoint) GetReactionForce

func (joint WheelJoint) GetReactionForce(inv_dt float64) Vec2

func (WheelJoint) GetReactionTorque

func (joint WheelJoint) GetReactionTorque(inv_dt float64) float64

func (WheelJoint) GetStiffness

func (joint WheelJoint) GetStiffness() float64

Access spring stiffness

func (WheelJoint) GetUpperLimit

func (joint WheelJoint) GetUpperLimit() float64

Get the upper joint translation limit, usually in meters.

func (*WheelJoint) InitVelocityConstraints

func (joint *WheelJoint) InitVelocityConstraints(data SolverData)

func (WheelJoint) IsLimitEnabled

func (joint WheelJoint) IsLimitEnabled() bool

Is the joint limit enabled?

func (WheelJoint) IsMotorEnabled

func (joint WheelJoint) IsMotorEnabled() bool

func (*WheelJoint) SetDamping

func (joint *WheelJoint) SetDamping(damping float64)

Access damping

func (WheelJoint) SetLimits

func (joint WheelJoint) SetLimits(lower float64, upper float64)

Set the joint translation limits, usually in meters.

func (*WheelJoint) SetMaxMotorTorque

func (joint *WheelJoint) SetMaxMotorTorque(torque float64)

func (*WheelJoint) SetMotorSpeed

func (joint *WheelJoint) SetMotorSpeed(speed float64)

func (*WheelJoint) SetStiffness

func (joint *WheelJoint) SetStiffness(stiffness float64)

Access spring stiffness

func (*WheelJoint) SolvePositionConstraints

func (joint *WheelJoint) SolvePositionConstraints(data SolverData) bool

func (*WheelJoint) SolveVelocityConstraints

func (joint *WheelJoint) SolveVelocityConstraints(data SolverData)

type WheelJointDef

type WheelJointDef struct {
	JointDef

	// The local anchor point relative to bodyA's origin.
	LocalAnchorA Vec2

	// The local anchor point relative to bodyB's origin.
	LocalAnchorB Vec2

	// The local translation axis in bodyA.
	LocalAxisA Vec2

	// Enable/disable the joint limit.
	EnableLimit bool

	// The lower translation limit, usually in meters.
	LowerTranslation float64

	// The upper translation limit, usually in meters.
	UpperTranslation float64

	// Enable/disable the joint motor.
	EnableMotor bool

	// The maximum motor torque, usually in N-m.
	MaxMotorTorque float64

	// The desired motor speed in radians per second.
	MotorSpeed float64

	// Suspension stiffness. Typically in units N/m.
	Stiffness float64

	// Suspension damping. Typically in units of N*s/m.
	Damping float64
}

Wheel joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game.

func MakeWheelJointDef

func MakeWheelJointDef() WheelJointDef

func (*WheelJointDef) Initialize

func (def *WheelJointDef) Initialize(bA *Body, bB *Body, anchor Vec2, axis Vec2)

type World

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

World struct manages all physics entities, dynamic simulation, and asynchronous queries. The world also contains efficient memory management facilities.

func MakeWorld

func MakeWorld(gravity Vec2) World

func (*World) ClearForces

func (world *World) ClearForces()

func (*World) CreateBody

func (world *World) CreateBody(def *BodyDef) *Body

func (*World) CreateJoint

func (world *World) CreateJoint(def IJointDef) IJoint

func (*World) Destroy

func (world *World) Destroy()

func (*World) DestroyBody

func (world *World) DestroyBody(b *Body)

func (*World) DestroyJoint

func (world *World) DestroyJoint(j IJoint)

func (*World) Dump

func (world *World) Dump()

func (World) GetAutoClearForces

func (world World) GetAutoClearForces() bool

Get the flag that controls automatic clearing of forces after each time step.

func (World) GetBodyCount

func (world World) GetBodyCount() int

func (World) GetBodyList

func (world World) GetBodyList() *Body

func (World) GetContactCount

func (world World) GetContactCount() int

func (World) GetContactList

func (world World) GetContactList() IContact

Get the world contact list. With the returned contact, use Contact.GetNext() to get the next contact in the world list. A nullptr contact indicates the end of the list.

func (World) GetContactManager

func (world World) GetContactManager() ContactManager

func (World) GetGravity

func (world World) GetGravity() Vec2

func (World) GetJointCount

func (world World) GetJointCount() int

func (World) GetJointList

func (world World) GetJointList() IJoint

func (World) GetProfile

func (world World) GetProfile() Profile

func (World) GetProxyCount

func (world World) GetProxyCount() int

func (World) GetTreeBalance

func (world World) GetTreeBalance() int

func (World) GetTreeHeight

func (world World) GetTreeHeight() int

func (World) GetTreeQuality

func (world World) GetTreeQuality() float64

func (World) IsLocked

func (world World) IsLocked() bool

func (*World) QueryAABB

func (world *World) QueryAABB(callback BroadPhaseQueryCallback, aabb AABB)

func (*World) RayCast

func (world *World) RayCast(callback RaycastCallback, point1 Vec2, point2 Vec2)

func (*World) SetAllowSleeping

func (world *World) SetAllowSleeping(flag bool)

func (*World) SetAutoClearForces

func (world *World) SetAutoClearForces(flag bool)

func (*World) SetContactFilter

func (world *World) SetContactFilter(filter IContactFilter)

func (*World) SetContactListener

func (world *World) SetContactListener(listener IContactListener)

func (*World) SetDestructionListener

func (world *World) SetDestructionListener(listener IDestructionListener)

func (*World) SetGravity

func (world *World) SetGravity(gravity Vec2)

func (*World) ShiftOrigin

func (world *World) ShiftOrigin(newOrigin Vec2)

func (*World) Solve

func (world *World) Solve(step TimeStep)

Find islands, integrate and solve constraints, solve position constraints

func (*World) SolveTOI

func (world *World) SolveTOI(step TimeStep)

Find TOI contacts and solve them.

func (*World) Step

func (world *World) Step(dt float64, velocityIterations int, positionIterations int)

type WorldManifold

type WorldManifold struct {
	Normal      Vec2                       // world vector pointing from A to B
	Points      [maxManifoldPoints]Vec2    // world contact point (point of intersection)
	Separations [maxManifoldPoints]float64 // a negative value indicates overlap, in meters
}

This is used to compute the current state of a contact manifold.

func (*WorldManifold) Initialize

func (wm *WorldManifold) Initialize(mf *Manifold, xfA Transform, radiusA float64, xfB Transform, radiusB float64)

type WorldQueryWrapper

type WorldQueryWrapper struct {
	BroadPhase *BroadPhase
	Callback   BroadPhaseQueryCallback
}

func MakeWorldQueryWrapper

func MakeWorldQueryWrapper() WorldQueryWrapper

func (*WorldQueryWrapper) QueryCallback

func (query *WorldQueryWrapper) QueryCallback(proxyId int) bool

Jump to

Keyboard shortcuts

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