Documentation
¶
Overview ¶
Package dbox2d implements a deterministic 2D rigid body solver.
Equal inputs produce the same result bits on every supported architecture, on every run. A world therefore survives a snapshot, a replay and a rollback without drift.
The package builds in two scalar modes. The default is float32. The build tag dbox2d_fixed selects the Q32.32 fixed-point arithmetic of github.com/dhannyell/fixed, with the same determinism promise; see the README for the mode details and commands. ScalarMode reports the mode of a build.
The optional dbox2d_simd tag opts in to a SIMD contact solver in either mode. It produces the same result bits as the scalar solver.
Fidelity ¶
The package is a port of Box2D v3.1.1. It keeps the upstream file decomposition, the upstream names without the b2 prefix, and the upstream order of operations. The port preserves the upstream formulation, not its output bits. Box2D computes in floating point, so the two libraries produce different trajectories.
Fixed-point arithmetic forbids some upstream lines, such as an epsilon tuned for float or a stopping criterion that depends on it. Each such place is a recorded divergence with a reason and a test.
Angles ¶
An angle is a turn, not a radian, because a turn reduces without pi. The solver stores an orientation as a Rot sine and cosine pair, never as an angle.
IDs ¶
WorldId, BodyId, ShapeId, ChainId and JointId are opaque handles. Their zero values are null, and IDs of the same type can be compared with ==. Pass them by value and obtain them from package functions; constructing a packed value by hand may make it refer to whatever occupies that slot.
Accumulation ¶
Saturated addition is not associative near the range limits. The solver keeps a fixed accumulation order for that reason. The worker count never changes that order: TestStepIsWorkerCountIndependent pins the same checksum for one and for several workers.
Index ¶
- Constants
- Variables
- func AABBContains(a, b AABB) bool
- func AABBOverlaps(a, b AABB) bool
- func Checksum(worldId WorldId) uint64
- func ClampInt(a, lower, upper int) int
- func DestroyBody(bodyId BodyId)
- func DestroyChain(chainId ChainId)
- func DestroyJoint(jointId JointId)
- func DestroyShape(shapeId ShapeId, updateBodyMass bool)
- func DestroyWorld(worldId WorldId)
- func GetLengthAndNormalize(v Vec2) (Q, Vec2)
- func IsNormalized(a Vec2) bool
- func IsNormalizedRot(q Rot) bool
- func IsValidAABB(a AABB) bool
- func IsValidPlane(a Plane) bool
- func IsValidQ(a Q) bool
- func IsValidRay(input *RayCastInput) bool
- func IsValidRotation(q Rot) bool
- func IsValidVec2(v Vec2) bool
- func PointInCapsule(point Vec2, shape *Capsule) bool
- func PointInCircle(point Vec2, shape *Circle) bool
- func QToFloat64(q Q) float64
- func StoreBodyId(id BodyId) uint64
- func StoreChainId(id ChainId) uint64
- func StoreJointId(id JointId) uint64
- func StoreShapeId(id ShapeId) uint64
- func StoreWorldId(id WorldId) uint32
- func ValidateHull(hull *Hull) bool
- type AABB
- func AABBUnion(a, b AABB) AABB
- func ComputeCapsuleAABB(shape *Capsule, xf Transform) AABB
- func ComputeCircleAABB(shape *Circle, xf Transform) AABB
- func ComputePolygonAABB(shape *Polygon, xf Transform) AABB
- func ComputeSegmentAABB(shape *Segment, xf Transform) AABB
- func MakeAABB(points []Vec2, radius Q) AABB
- type BodyDef
- type BodyEvents
- type BodyId
- func (bodyId BodyId) ApplyAngularImpulse(impulse Q, wake bool)
- func (bodyId BodyId) ApplyForce(force, point Vec2, wake bool)
- func (bodyId BodyId) ApplyForceToCenter(force Vec2, wake bool)
- func (bodyId BodyId) ApplyLinearImpulse(impulse, point Vec2, wake bool)
- func (bodyId BodyId) ApplyLinearImpulseToCenter(impulse Vec2, wake bool)
- func (bodyId BodyId) ApplyMassFromShapes()
- func (bodyId BodyId) ApplyTorque(torque Q, wake bool)
- func (bodyId BodyId) ComputeAABB() AABB
- func (bodyId BodyId) Disable()
- func (bodyId BodyId) Enable()
- func (bodyId BodyId) EnableContactEvents(flag bool)
- func (bodyId BodyId) EnableHitEvents(flag bool)
- func (bodyId BodyId) EnableSleep(enableSleep bool)
- func (bodyId BodyId) GetAngularDamping() Q
- func (bodyId BodyId) GetAngularVelocity() Q
- func (bodyId BodyId) GetContactCapacity() int
- func (bodyId BodyId) GetContactData(data []ContactData) int
- func (bodyId BodyId) GetGravityScale() Q
- func (bodyId BodyId) GetJointCount() int
- func (bodyId BodyId) GetJoints(joints []JointId) int
- func (bodyId BodyId) GetLinearDamping() Q
- func (bodyId BodyId) GetLinearVelocity() Vec2
- func (bodyId BodyId) GetLocalCenterOfMass() Vec2
- func (bodyId BodyId) GetLocalPoint(worldPoint Vec2) Vec2
- func (bodyId BodyId) GetLocalPointVelocity(localPoint Vec2) Vec2
- func (bodyId BodyId) GetLocalVector(worldVector Vec2) Vec2
- func (bodyId BodyId) GetMass() Q
- func (bodyId BodyId) GetMassData() MassData
- func (bodyId BodyId) GetName() string
- func (bodyId BodyId) GetPosition() Vec2
- func (bodyId BodyId) GetRotation() Rot
- func (bodyId BodyId) GetRotationalInertia() Q
- func (bodyId BodyId) GetShapeCount() int
- func (bodyId BodyId) GetShapes(shapes []ShapeId) int
- func (bodyId BodyId) GetSleepThreshold() Q
- func (bodyId BodyId) GetTransform() Transform
- func (bodyId BodyId) GetType() BodyType
- func (bodyId BodyId) GetUserData() any
- func (bodyId BodyId) GetWorld() WorldId
- func (bodyId BodyId) GetWorldCenterOfMass() Vec2
- func (bodyId BodyId) GetWorldPoint(localPoint Vec2) Vec2
- func (bodyId BodyId) GetWorldPointVelocity(worldPoint Vec2) Vec2
- func (bodyId BodyId) GetWorldVector(localVector Vec2) Vec2
- func (bodyId BodyId) IsAwake() bool
- func (bodyId BodyId) IsBullet() bool
- func (bodyId BodyId) IsEnabled() bool
- func (bodyId BodyId) IsFixedRotation() bool
- func (id BodyId) IsNull() bool
- func (bodyId BodyId) IsSleepEnabled() bool
- func (id BodyId) IsValid() bool
- func (bodyId BodyId) SetAngularDamping(angularDamping Q)
- func (bodyId BodyId) SetAngularVelocity(angularVelocity Q)
- func (bodyId BodyId) SetAwake(awake bool)
- func (bodyId BodyId) SetBullet(flag bool)
- func (bodyId BodyId) SetFixedRotation(flag bool)
- func (bodyId BodyId) SetGravityScale(gravityScale Q)
- func (bodyId BodyId) SetLinearDamping(linearDamping Q)
- func (bodyId BodyId) SetLinearVelocity(linearVelocity Vec2)
- func (bodyId BodyId) SetMassData(massData MassData)
- func (bodyId BodyId) SetName(name string)
- func (bodyId BodyId) SetSleepThreshold(sleepThreshold Q)
- func (bodyId BodyId) SetTargetTransform(target Transform, timeStep Q)
- func (bodyId BodyId) SetTransform(position Vec2, rotation Rot)
- func (bodyId BodyId) SetType(bodyType BodyType)
- func (bodyId BodyId) SetUserData(userData any)
- type BodyMoveEvent
- type BodyType
- type Capsule
- type CastOutput
- func RayCastCapsule(input *RayCastInput, shape *Capsule) CastOutput
- func RayCastCircle(input *RayCastInput, shape *Circle) CastOutput
- func RayCastPolygon(input *RayCastInput, shape *Polygon) CastOutput
- func RayCastSegment(input *RayCastInput, shape *Segment, oneSided bool) CastOutput
- func ShapeCast(input *ShapeCastPairInput) CastOutput
- func ShapeCastCapsule(input *ShapeCastInput, shape *Capsule) CastOutput
- func ShapeCastCircle(input *ShapeCastInput, shape *Circle) CastOutput
- func ShapeCastPolygon(input *ShapeCastInput, shape *Polygon) CastOutput
- func ShapeCastSegment(input *ShapeCastInput, shape *Segment) CastOutput
- type CastResultFcn
- type ChainDef
- type ChainId
- func (chainId ChainId) GetFriction() Q
- func (chainId ChainId) GetMaterial() int
- func (chainId ChainId) GetRestitution() Q
- func (chainId ChainId) GetSegmentCount() int
- func (chainId ChainId) GetSegments(segments []ShapeId) int
- func (chainId ChainId) GetWorld() WorldId
- func (id ChainId) IsNull() bool
- func (chainId ChainId) IsValid() bool
- func (chainId ChainId) SetFriction(friction Q)
- func (chainId ChainId) SetMaterial(material int)
- func (chainId ChainId) SetRestitution(restitution Q)
- type ChainSegment
- type Circle
- type CollisionPlane
- type ContactBeginTouchEvent
- type ContactData
- type ContactEndTouchEvent
- type ContactEvents
- type ContactHitEvent
- type Counters
- type CustomFilterFcn
- type DebugDraw
- type DistanceInput
- type DistanceJointDef
- type DistanceOutput
- type DrawCircleFcn
- type DrawPointFcn
- type DrawPolygonFcn
- type DrawSegmentFcn
- type DrawSolidCapsuleFcn
- type DrawSolidCircleFcn
- type DrawSolidPolygonFcn
- type DrawStringFcn
- type DrawTransformFcn
- type DynamicTree
- func (t *DynamicTree) CreateProxy(aabb AABB, categoryBits uint64, userData uint64) int
- func (t *DynamicTree) Destroy()
- func (t *DynamicTree) DestroyProxy(proxyId int)
- func (t *DynamicTree) EnlargeProxy(proxyId int, aabb AABB)
- func (t *DynamicTree) GetAABB(proxyId int) AABB
- func (t *DynamicTree) GetAreaRatio() Q
- func (t *DynamicTree) GetCategoryBits(proxyId int) uint64
- func (t *DynamicTree) GetHeight() int
- func (t *DynamicTree) GetProxyCount() int
- func (t *DynamicTree) GetRootBounds() AABB
- func (t *DynamicTree) GetUserData(proxyId int) uint64
- func (t *DynamicTree) MoveProxy(proxyId int, aabb AABB)
- func (t *DynamicTree) Query(aabb AABB, maskBits uint64, fcn TreeQueryCallbackFcn) TreeStats
- func (t *DynamicTree) RayCast(input *RayCastInput, maskBits uint64, fcn TreeRayCastCallbackFcn) TreeStats
- func (t *DynamicTree) Rebuild(fullBuild bool) int
- func (t *DynamicTree) SetCategoryBits(proxyId int, categoryBits uint64)
- func (t *DynamicTree) ShapeCast(input *ShapeCastInput, maskBits uint64, fcn TreeShapeCastCallbackFcn) TreeStats
- func (t *DynamicTree) Validate()
- func (t *DynamicTree) ValidateNoEnlarged()
- type ExplosionDef
- type Filter
- type FilterJointDef
- type FrictionCallback
- type HexColor
- type Hull
- type JointId
- func CreateDistanceJoint(worldId WorldId, def *DistanceJointDef) JointId
- func CreateFilterJoint(worldId WorldId, def *FilterJointDef) JointId
- func CreateMotorJoint(worldId WorldId, def *MotorJointDef) JointId
- func CreateMouseJoint(worldId WorldId, def *MouseJointDef) JointId
- func CreatePrismaticJoint(worldId WorldId, def *PrismaticJointDef) JointId
- func CreateRevoluteJoint(worldId WorldId, def *RevoluteJointDef) JointId
- func CreateWeldJoint(worldId WorldId, def *WeldJointDef) JointId
- func CreateWheelJoint(worldId WorldId, def *WheelJointDef) JointId
- func LoadJointId(x uint64) JointId
- func (jointId JointId) EnableLimit(enableLimit bool)
- func (jointId JointId) EnableMotor(enableMotor bool)
- func (jointId JointId) EnableSpring(enableSpring bool)
- func (jointId JointId) GetAngle() Q
- func (jointId JointId) GetAngularDampingRatio() Q
- func (jointId JointId) GetAngularHertz() Q
- func (jointId JointId) GetAngularOffset() Q
- func (jointId JointId) GetAngularSeparation() Q
- func (jointId JointId) GetBodyA() BodyId
- func (jointId JointId) GetBodyB() BodyId
- func (jointId JointId) GetCollideConnected() bool
- func (jointId JointId) GetConstraintForce() Vec2
- func (jointId JointId) GetConstraintTorque() Q
- func (jointId JointId) GetConstraintTuning() (hertz, dampingRatio Q)
- func (jointId JointId) GetCorrectionFactor() Q
- func (jointId JointId) GetCurrentLength() Q
- func (jointId JointId) GetLength() Q
- func (jointId JointId) GetLinearDampingRatio() Q
- func (jointId JointId) GetLinearHertz() Q
- func (jointId JointId) GetLinearOffset() Vec2
- func (jointId JointId) GetLinearSeparation() Q
- func (jointId JointId) GetLocalAnchorA() Vec2
- func (jointId JointId) GetLocalAnchorB() Vec2
- func (jointId JointId) GetLocalAxisA() Vec2
- func (jointId JointId) GetLowerLimit() Q
- func (jointId JointId) GetMaxForce() Q
- func (jointId JointId) GetMaxLength() Q
- func (jointId JointId) GetMaxMotorForce() Q
- func (jointId JointId) GetMaxMotorTorque() Q
- func (jointId JointId) GetMaxTorque() Q
- func (jointId JointId) GetMinLength() Q
- func (jointId JointId) GetMotorForce() Q
- func (jointId JointId) GetMotorSpeed() Q
- func (jointId JointId) GetMotorTorque() Q
- func (jointId JointId) GetReferenceAngle() Q
- func (jointId JointId) GetSpeed() Q
- func (jointId JointId) GetSpringDampingRatio() Q
- func (jointId JointId) GetSpringHertz() Q
- func (jointId JointId) GetTarget() Vec2
- func (jointId JointId) GetTargetAngle() Q
- func (jointId JointId) GetTargetTranslation() Q
- func (jointId JointId) GetTranslation() Q
- func (jointId JointId) GetType() JointType
- func (jointId JointId) GetUpperLimit() Q
- func (jointId JointId) GetUserData() any
- func (jointId JointId) GetWorld() WorldId
- func (jointId JointId) IsLimitEnabled() bool
- func (jointId JointId) IsMotorEnabled() bool
- func (id JointId) IsNull() bool
- func (jointId JointId) IsSpringEnabled() bool
- func (jointId JointId) IsValid() bool
- func (jointId JointId) SetAngularDampingRatio(dampingRatio Q)
- func (jointId JointId) SetAngularHertz(hertz Q)
- func (jointId JointId) SetAngularOffset(angularOffset Q)
- func (jointId JointId) SetCollideConnected(shouldCollide bool)
- func (jointId JointId) SetConstraintTuning(hertz, dampingRatio Q)
- func (jointId JointId) SetCorrectionFactor(correctionFactor Q)
- func (jointId JointId) SetLength(length Q)
- func (jointId JointId) SetLengthRange(minLength, maxLength Q)
- func (jointId JointId) SetLimits(lower, upper Q)
- func (jointId JointId) SetLinearDampingRatio(dampingRatio Q)
- func (jointId JointId) SetLinearHertz(hertz Q)
- func (jointId JointId) SetLinearOffset(linearOffset Vec2)
- func (jointId JointId) SetLocalAnchorA(localAnchor Vec2)
- func (jointId JointId) SetLocalAnchorB(localAnchor Vec2)
- func (jointId JointId) SetLocalAxisA(axis Vec2)
- func (jointId JointId) SetMaxForce(maxForce Q)
- func (jointId JointId) SetMaxMotorForce(force Q)
- func (jointId JointId) SetMaxMotorTorque(torque Q)
- func (jointId JointId) SetMaxTorque(maxTorque Q)
- func (jointId JointId) SetMotorSpeed(motorSpeed Q)
- func (jointId JointId) SetReferenceAngle(angle Q)
- func (jointId JointId) SetSpringDampingRatio(dampingRatio Q)
- func (jointId JointId) SetSpringHertz(hertz Q)
- func (jointId JointId) SetTarget(target Vec2)
- func (jointId JointId) SetTargetAngle(angle Q)
- func (jointId JointId) SetTargetTranslation(translation Q)
- func (jointId JointId) SetUserData(userData any)
- func (jointId JointId) WakeBodies()
- type JointType
- type Manifold
- func CollideCapsuleAndCircle(capsuleA *Capsule, xfA Transform, circleB *Circle, xfB Transform) Manifold
- func CollideCapsules(capsuleA *Capsule, xfA Transform, capsuleB *Capsule, xfB Transform) Manifold
- func CollideChainSegmentAndCapsule(segmentA *ChainSegment, xfA Transform, capsuleB *Capsule, xfB Transform, ...) Manifold
- func CollideChainSegmentAndCircle(segmentA *ChainSegment, xfA Transform, circleB *Circle, xfB Transform) Manifold
- func CollideChainSegmentAndPolygon(segmentA *ChainSegment, xfA Transform, polygonB *Polygon, xfB Transform, ...) Manifold
- func CollideCircles(circleA *Circle, xfA Transform, circleB *Circle, xfB Transform) Manifold
- func CollidePolygonAndCapsule(polygonA *Polygon, xfA Transform, capsuleB *Capsule, xfB Transform) Manifold
- func CollidePolygonAndCircle(polygonA *Polygon, xfA Transform, circleB *Circle, xfB Transform) Manifold
- func CollidePolygons(polygonA *Polygon, xfA Transform, polygonB *Polygon, xfB Transform) Manifold
- func CollideSegmentAndCapsule(segmentA *Segment, xfA Transform, capsuleB *Capsule, xfB Transform) Manifold
- func CollideSegmentAndCircle(segmentA *Segment, xfA Transform, circleB *Circle, xfB Transform) Manifold
- func CollideSegmentAndPolygon(segmentA *Segment, xfA Transform, polygonB *Polygon, xfB Transform) Manifold
- type ManifoldPoint
- type MassData
- type Mat22
- type MotorJointDef
- type MouseJointDef
- type OverlapResultFcn
- type Plane
- type PlaneResult
- type PlaneResultFcn
- type PlaneSolverResult
- type Polygon
- func MakeBox(halfWidth, halfHeight Q) Polygon
- func MakeOffsetBox(halfWidth, halfHeight Q, center Vec2, rotation Rot) Polygon
- func MakeOffsetPolygon(hull *Hull, position Vec2, rotation Rot) Polygon
- func MakeOffsetRoundedBox(halfWidth, halfHeight Q, center Vec2, rotation Rot, radius Q) Polygon
- func MakeOffsetRoundedPolygon(hull *Hull, position Vec2, rotation Rot, radius Q) Polygon
- func MakePolygon(hull *Hull, radius Q) Polygon
- func MakeRoundedBox(halfWidth, halfHeight, radius Q) Polygon
- func MakeSquare(halfWidth Q) Polygon
- func TransformPolygon(transform Transform, polygon *Polygon) Polygon
- type PreSolveFcn
- type PrismaticJointDef
- type Profile
- type Q
- func AABBMargin() Q
- func ComputeAngularVelocity(q1, q2 Rot, invH Q) Q
- func Cross(a, b Vec2) Q
- func JointConstraintDampingRatio() Q
- func JointConstraintHertz() Q
- func LinearSlop() Q
- func MaxRotation() Q
- func Pi() Q
- func PlaneSeparation(plane Plane, point Vec2) Q
- func QFromFloat64(f float64) Q
- func QFromInt(i int) Q
- func QFromRatio(num, den int) Q
- func QHalf() Q
- func QMaxValue() Q
- func QMinValue() Q
- func QMustParse(s string) Q
- func QOne() Q
- func QZero() Q
- func RelativeAngle(b, a Rot) Q
- func RotGetAngle(q Rot) Q
- func SpeculativeDistance() Q
- func SpringDamper(hertz, dampingRatio, position, velocity, timeStep Q) Q
- func TimeToSleep() Q
- func UnwindAngle(t Q) Q
- func (q Q) Abs() Q
- func (q Q) Add(o Q) Q
- func (q Q) Clamp(lo, hi Q) Q
- func (q Q) Cmp(o Q) int
- func (q Q) Div(o Q) Q
- func (q Q) Eq(o Q) bool
- func (q Q) Greater(o Q) bool
- func (q Q) Int() int
- func (q Q) Less(o Q) bool
- func (q Q) Max(o Q) Q
- func (q Q) Min(o Q) Q
- func (q Q) Mul(o Q) Q
- func (q Q) Neg() Q
- func (q Q) Round() Q
- func (q Q) Sqrt() Q
- func (q Q) String() string
- func (q Q) Sub(o Q) Q
- type QueryFilter
- type RayCastInput
- type RayResult
- type RestitutionCallback
- type RevoluteJointDef
- type Rot
- type Segment
- type SegmentDistanceResult
- type SensorBeginTouchEvent
- type SensorEndTouchEvent
- type SensorEvents
- type ShapeCastInput
- type ShapeCastPairInput
- type ShapeDef
- type ShapeId
- func CreateCapsuleShape(bodyId BodyId, def *ShapeDef, capsule *Capsule) ShapeId
- func CreateCircleShape(bodyId BodyId, def *ShapeDef, circle *Circle) ShapeId
- func CreatePolygonShape(bodyId BodyId, def *ShapeDef, polygon *Polygon) ShapeId
- func CreateSegmentShape(bodyId BodyId, def *ShapeDef, segment *Segment) ShapeId
- func LoadShapeId(x uint64) ShapeId
- func (shapeId ShapeId) AreContactEventsEnabled() bool
- func (shapeId ShapeId) AreHitEventsEnabled() bool
- func (shapeId ShapeId) ArePreSolveEventsEnabled() bool
- func (shapeId ShapeId) AreSensorEventsEnabled() bool
- func (shapeId ShapeId) EnableContactEvents(flag bool)
- func (shapeId ShapeId) EnableHitEvents(flag bool)
- func (shapeId ShapeId) EnablePreSolveEvents(flag bool)
- func (shapeId ShapeId) EnableSensorEvents(flag bool)
- func (shapeId ShapeId) GetAABB() AABB
- func (shapeId ShapeId) GetBody() BodyId
- func (shapeId ShapeId) GetCapsule() Capsule
- func (shapeId ShapeId) GetChainSegment() ChainSegment
- func (shapeId ShapeId) GetCircle() Circle
- func (shapeId ShapeId) GetClosestPoint(target Vec2) Vec2
- func (shapeId ShapeId) GetContactCapacity() int
- func (shapeId ShapeId) GetContactData(data []ContactData) int
- func (shapeId ShapeId) GetDensity() Q
- func (shapeId ShapeId) GetFilter() Filter
- func (shapeId ShapeId) GetFriction() Q
- func (shapeId ShapeId) GetMassData() MassData
- func (shapeId ShapeId) GetMaterial() int
- func (shapeId ShapeId) GetParentChain() ChainId
- func (shapeId ShapeId) GetPolygon() Polygon
- func (shapeId ShapeId) GetRestitution() Q
- func (shapeId ShapeId) GetSegment() Segment
- func (shapeId ShapeId) GetSensorCapacity() int
- func (shapeId ShapeId) GetSensorOverlaps(overlaps []ShapeId) int
- func (shapeId ShapeId) GetSurfaceMaterial() SurfaceMaterial
- func (shapeId ShapeId) GetType() ShapeType
- func (shapeId ShapeId) GetUserData() any
- func (shapeId ShapeId) GetWorld() WorldId
- func (id ShapeId) IsNull() bool
- func (shapeId ShapeId) IsSensor() bool
- func (id ShapeId) IsValid() bool
- func (shapeId ShapeId) RayCast(input *RayCastInput) CastOutput
- func (shapeId ShapeId) SetCapsule(capsule *Capsule)
- func (shapeId ShapeId) SetCircle(circle *Circle)
- func (shapeId ShapeId) SetDensity(density Q, updateBodyMass bool)
- func (shapeId ShapeId) SetFilter(filter Filter)
- func (shapeId ShapeId) SetFriction(friction Q)
- func (shapeId ShapeId) SetMaterial(material int)
- func (shapeId ShapeId) SetPolygon(polygon *Polygon)
- func (shapeId ShapeId) SetRestitution(restitution Q)
- func (shapeId ShapeId) SetSegment(segment *Segment)
- func (shapeId ShapeId) SetSurfaceMaterial(material SurfaceMaterial)
- func (shapeId ShapeId) SetUserData(userData any)
- func (shapeId ShapeId) TestPoint(point Vec2) bool
- type ShapeProxy
- type ShapeType
- type Simplex
- type SimplexCache
- type SimplexVertex
- type SurfaceMaterial
- type Sweep
- type TOIInput
- type TOIOutput
- type TOIState
- type Transform
- type TreeQueryCallbackFcn
- type TreeRayCastCallbackFcn
- type TreeShapeCastCallbackFcn
- type TreeStats
- type Vec2
- func AABBCenter(a AABB) Vec2
- func AABBExtents(a AABB) Vec2
- func Abs(a Vec2) Vec2
- func Clamp(v, a, b Vec2) Vec2
- func ClipVector(vector Vec2, planes []CollisionPlane) Vec2
- func CrossSV(s Q, v Vec2) Vec2
- func CrossVS(v Vec2, s Q) Vec2
- func InvRotateVector(q Rot, v Vec2) Vec2
- func InvTransformPoint(t Transform, p Vec2) Vec2
- func LeftPerp(v Vec2) Vec2
- func Lerp(a, b Vec2, t Q) Vec2
- func Max(a, b Vec2) Vec2
- func Min(a, b Vec2) Vec2
- func Mul(a, b Vec2) Vec2
- func MulAdd(a Vec2, s Q, b Vec2) Vec2
- func MulMV(m Mat22, v Vec2) Vec2
- func MulSub(a Vec2, s Q, b Vec2) Vec2
- func Neg(a Vec2) Vec2
- func RightPerp(v Vec2) Vec2
- func RotGetXAxis(q Rot) Vec2
- func RotGetYAxis(q Rot) Vec2
- func RotateVector(q Rot, v Vec2) Vec2
- func Solve22(m Mat22, b Vec2) Vec2
- func TransformPoint(t Transform, p Vec2) Vec2
- func Vec2Zero() Vec2
- func (v Vec2) Add(o Vec2) Vec2
- func (v Vec2) Distance(o Vec2) Q
- func (v Vec2) DistanceSq(o Vec2) Q
- func (v Vec2) Div(s Q) Vec2
- func (v Vec2) Dot(o Vec2) Q
- func (v Vec2) Len() Q
- func (v Vec2) LenSq() Q
- func (v Vec2) Lerp(target Vec2, t Q) Vec2
- func (v Vec2) Mul(s Q) Vec2
- func (v Vec2) Normalize() Vec2
- func (v Vec2) Sub(o Vec2) Vec2
- type Version
- type WeldJointDef
- type WheelJointDef
- type WorldDef
- type WorldId
- func (worldId WorldId) CastMover(mover *Capsule, translation Vec2, filter QueryFilter) Q
- func (worldId WorldId) CastRay(origin, translation Vec2, filter QueryFilter, fcn CastResultFcn) TreeStats
- func (worldId WorldId) CastRayClosest(origin, translation Vec2, filter QueryFilter) RayResult
- func (worldId WorldId) CastShape(proxy *ShapeProxy, translation Vec2, filter QueryFilter, fcn CastResultFcn) TreeStats
- func (worldId WorldId) CollideMover(mover *Capsule, filter QueryFilter, fcn PlaneResultFcn)
- func (worldId WorldId) Draw(draw *DebugDraw)
- func (id WorldId) DumpMemoryStats(w io.Writer)
- func (worldId WorldId) EnableContinuous(flag bool)
- func (worldId WorldId) EnableSleeping(flag bool)
- func (worldId WorldId) EnableSpeculative(flag bool)
- func (worldId WorldId) EnableWarmStarting(flag bool)
- func (worldId WorldId) Explode(def *ExplosionDef)
- func (worldId WorldId) GetAwakeBodyCount() int
- func (worldId WorldId) GetBodyEvents() BodyEvents
- func (worldId WorldId) GetContactEvents() ContactEvents
- func (worldId WorldId) GetCounters() Counters
- func (worldId WorldId) GetGravity() Vec2
- func (worldId WorldId) GetHitEventThreshold() Q
- func (worldId WorldId) GetMaximumLinearSpeed() Q
- func (id WorldId) GetProfile() Profile
- func (worldId WorldId) GetRestitutionThreshold() Q
- func (worldId WorldId) GetSensorEvents() SensorEvents
- func (worldId WorldId) GetUserData() any
- func (worldId WorldId) IsContinuousEnabled() bool
- func (id WorldId) IsNull() bool
- func (worldId WorldId) IsSleepingEnabled() bool
- func (id WorldId) IsValid() bool
- func (worldId WorldId) IsWarmStartingEnabled() bool
- func (worldId WorldId) OverlapAABB(aabb AABB, filter QueryFilter, fcn OverlapResultFcn) TreeStats
- func (worldId WorldId) OverlapShape(proxy *ShapeProxy, filter QueryFilter, fcn OverlapResultFcn) TreeStats
- func (worldId WorldId) RebuildStaticTree()
- func (worldId WorldId) SetContactTuning(hertz, dampingRatio, pushSpeed Q)
- func (worldId WorldId) SetCustomFilterCallback(fcn CustomFilterFcn)
- func (worldId WorldId) SetFrictionCallback(callback FrictionCallback)
- func (worldId WorldId) SetGravity(gravity Vec2)
- func (worldId WorldId) SetHitEventThreshold(value Q)
- func (worldId WorldId) SetMaximumLinearSpeed(maximumLinearSpeed Q)
- func (worldId WorldId) SetPreSolveCallback(fcn PreSolveFcn)
- func (worldId WorldId) SetRestitutionCallback(callback RestitutionCallback)
- func (worldId WorldId) SetRestitutionThreshold(value Q)
- func (worldId WorldId) SetUserData(userData any)
- func (worldId WorldId) Step(timeStep Q, subStepCount int)
Examples ¶
- BodyId.Disable
- BodyId.GetContactData
- BodyId.SetTransform
- BodyId.SetType
- CreateChain
- CreateDistanceJoint
- CreateFilterJoint
- CreateMotorJoint
- CreateMouseJoint
- CreatePrismaticJoint
- CreateRevoluteJoint
- CreateWeldJoint
- CreateWheelJoint
- JointId.SetCollideConnected
- SolvePlanes
- WorldId.Draw
- WorldId.Explode
- WorldId.GetSensorEvents
- WorldId.SetCustomFilterCallback
- WorldId.SetFrictionCallback
- WorldId.SetPreSolveCallback
Constants ¶
const ( DefaultCategoryBits uint64 = 1 DefaultMaskBits uint64 = math.MaxUint64 )
Default filter bits. upstream B2_DEFAULT_CATEGORY_BITS, B2_DEFAULT_MASK_BITS
const MaxPolygonVertices = 8
MaxPolygonVertices is the vertex limit of a convex polygon. Raising it costs performance even for shapes that use fewer vertices.
const ScalarMode = "float"
ScalarMode names the scalar mode of this build: "float" or "fixed".
Variables ¶
var ( // Huge is the largest coordinate the world accepts and the rigid push // limit of a collision plane. It corresponds to B2_HUGE in // include/box2d/math_functions.h. It bounds a length that an // application supplies, so a wild input fails early. Huge = QFromInt(100000) )
A length is a meter. The reference lets an application rescale its tolerances; this package does not, because a world that rescales them stops matching a world that does not. See DIVERGENCES.md.
Functions ¶
func AABBContains ¶
AABBContains reports whether a fully contains b.
func Checksum ¶
Checksum folds the complete deterministic state of a world into one integer. Application data and internal ids are excluded because they do not affect simulation. Bodies, shapes, contacts and joints use commutative folds, so equivalent worlds do not depend on creation order.
func DestroyBody ¶
func DestroyBody(bodyId BodyId)
DestroyBody destroys a body. Every shape attached to it goes away too.
func DestroyChain ¶ added in v0.4.0
func DestroyChain(chainId ChainId)
DestroyChain ports b2DestroyChain.
func DestroyJoint ¶ added in v0.3.0
func DestroyJoint(jointId JointId)
DestroyJoint destroys a joint and wakes the two bodies.
func DestroyShape ¶
DestroyShape destroys a shape. Pass updateBodyMass true to recompute the mass of the body from the remaining shapes.
func DestroyWorld ¶
func DestroyWorld(worldId WorldId)
DestroyWorld destroys a world and every body and shape in it.
func GetLengthAndNormalize ¶
GetLengthAndNormalize returns the length of v and the unit vector with the same direction. The zero vector returns a zero length and the zero vector.
func IsNormalizedRot ¶
IsNormalizedRot reports whether q has unit length.
func IsValidAABB ¶
IsValidAABB reports whether a is usable and not inverted.
func IsValidPlane ¶
IsValidPlane reports whether a has a unit normal and a usable offset.
func IsValidRay ¶
func IsValidRay(input *RayCastInput) bool
IsValidRay reports whether a ray cast input is usable.
func IsValidRotation ¶
IsValidRotation reports whether q is a usable and normalized rotation.
func PointInCapsule ¶
PointInCapsule reports whether a point overlaps a capsule in local space.
func PointInCircle ¶
PointInCircle reports whether a point overlaps a circle in local space.
func QToFloat64 ¶ added in v0.6.0
QToFloat64 converts a scalar to a presentation value, such as a camera value. It must never be used by simulation code.
func StoreChainId ¶
StoreChainId packs a chain id into a uint64.
func StoreJointId ¶
StoreJointId packs a joint id into a uint64.
func StoreShapeId ¶
StoreShapeId packs a shape id into a uint64.
func StoreWorldId ¶
StoreWorldId packs a world id into a uint32.
func ValidateHull ¶
ValidateHull reports whether a hull is convex and free of collinear points. It is expensive, so it does not belong in a running simulation.
Types ¶
type AABB ¶
AABB is an axis-aligned bounding box.
func ComputeCapsuleAABB ¶
ComputeCapsuleAABB returns the bounding box of a transformed capsule.
func ComputeCircleAABB ¶
ComputeCircleAABB returns the bounding box of a transformed circle.
func ComputePolygonAABB ¶
ComputePolygonAABB returns the bounding box of a transformed polygon.
func ComputeSegmentAABB ¶
ComputeSegmentAABB returns the bounding box of a transformed segment.
type BodyDef ¶
type BodyDef struct {
// The body type: static, kinematic or dynamic.
Type BodyType
// The initial world position. Create a body at its final position:
// creating it at the origin and moving it costs nearly twice as much.
Position Vec2
// The initial world rotation. Use MakeRot for an angle in turns.
Rotation Rot
// The initial linear velocity of the body origin, usually in meters per
// second.
LinearVelocity Vec2
// The initial angular velocity, in turns per second. The reference uses
// radians per second; an angle is a turn in this package.
AngularVelocity Q
// Linear damping reduces the linear velocity. A value larger than 1 is
// valid but grows sensitive to the time step. Usually undesirable,
// because it makes bodies move as if they float.
LinearDamping Q
// Angular damping reduces the angular velocity. A value larger than 1 is
// valid but grows sensitive to the time step.
AngularDamping Q
// Scale of the gravity on this body, non-dimensional.
GravityScale Q
// Sleep speed threshold, default 0.05 meters per second.
SleepThreshold Q
// Optional body name for debugging, up to 31 bytes.
Name string
// Application data attached to the body.
UserData any
// Set this to false if the body must never fall asleep.
EnableSleep bool
// Whether the body starts awake.
IsAwake bool
// Prevent the body from rotating. Useful for characters.
FixedRotation bool
// Treat the body as a high speed object that performs continuous
// collision against dynamic and kinematic bodies, but not against other
// bullets. Use sparingly: bullets solve no general dynamic-versus-dynamic
// case and may interfere with joints.
IsBullet bool
// A disabled body does not move and does not collide.
IsEnabled bool
// Let the body bypass the rotational speed limit. Only for circular
// bodies, like wheels.
AllowFastRotation bool
// contains filtered or unexported fields
}
BodyDef holds the data to construct a rigid body. It is a temporary bundle of creation parameters; shapes come after construction. Initialize it with DefaultBodyDef.
func DefaultBodyDef ¶
func DefaultBodyDef() BodyDef
DefaultBodyDef returns the default body definition.
type BodyEvents ¶ added in v0.3.0
type BodyEvents struct {
MoveEvents []BodyMoveEvent
}
BodyEvents holds the body events of the last step. The slice stays valid until the next step; a body destroy makes its entry stale.
type BodyId ¶
type BodyId struct {
// contains filtered or unexported fields
}
BodyId identifies a body. Its zero value is null.
func CreateBody ¶
CreateBody creates a rigid body from a definition. The definition must come from DefaultBodyDef and is not retained.
func (BodyId) ApplyAngularImpulse ¶ added in v0.4.0
ApplyAngularImpulse applies an angular impulse and receives the impulse in the reference's angular units. It corresponds to b2Body_ApplyAngularImpulse.
func (BodyId) ApplyForce ¶ added in v0.4.0
ApplyForce applies a force at a world point. It corresponds to b2Body_ApplyForce.
func (BodyId) ApplyForceToCenter ¶ added in v0.4.0
ApplyForceToCenter applies a force at the center of mass. It corresponds to b2Body_ApplyForceToCenter.
func (BodyId) ApplyLinearImpulse ¶ added in v0.4.0
ApplyLinearImpulse applies a linear impulse at a world point. It corresponds to b2Body_ApplyLinearImpulse.
func (BodyId) ApplyLinearImpulseToCenter ¶ added in v0.4.0
ApplyLinearImpulseToCenter applies a linear impulse at the center of mass. It corresponds to b2Body_ApplyLinearImpulseToCenter.
func (BodyId) ApplyMassFromShapes ¶ added in v0.4.0
func (bodyId BodyId) ApplyMassFromShapes()
ApplyMassFromShapes recomputes mass data from the body's shapes. It corresponds to b2Body_ApplyMassFromShapes.
func (BodyId) ApplyTorque ¶ added in v0.4.0
ApplyTorque applies a torque. It corresponds to b2Body_ApplyTorque.
func (BodyId) ComputeAABB ¶ added in v0.4.0
ComputeAABB returns the union of the body's shape bounds. It corresponds to b2Body_ComputeAABB.
func (BodyId) Disable ¶ added in v0.4.0
func (bodyId BodyId) Disable()
Disable removes the body from simulation. It corresponds to b2Body_Disable.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, _, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
boxId.Disable()
fmt.Println(boxId.IsEnabled())
boxId.Enable()
fmt.Println(boxId.IsEnabled())
}
Output: false true
func (BodyId) Enable ¶ added in v0.4.0
func (bodyId BodyId) Enable()
Enable returns the body to simulation. It corresponds to b2Body_Enable.
func (BodyId) EnableContactEvents ¶ added in v0.4.0
EnableContactEvents enables contact events on every body shape. It corresponds to b2Body_EnableContactEvents.
func (BodyId) EnableHitEvents ¶ added in v0.4.0
EnableHitEvents enables hit events on every body shape. It corresponds to b2Body_EnableHitEvents.
func (BodyId) EnableSleep ¶ added in v0.4.0
EnableSleep enables or disables sleeping. It corresponds to b2Body_EnableSleep.
func (BodyId) GetAngularDamping ¶ added in v0.4.0
GetAngularDamping returns angular damping. It corresponds to b2Body_GetAngularDamping.
func (BodyId) GetAngularVelocity ¶ added in v0.4.0
GetAngularVelocity returns the body's angular velocity in turns per second. It corresponds to b2Body_GetAngularVelocity.
func (BodyId) GetContactCapacity ¶ added in v0.4.0
GetContactCapacity returns the body's conservative contact capacity. It corresponds to b2Body_GetContactCapacity.
func (BodyId) GetContactData ¶ added in v0.4.0
func (bodyId BodyId) GetContactData(data []ContactData) int
GetContactData fills touching contact data in body-list order. It corresponds to b2Body_GetContactData.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
func main() {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
defer dbox2d.DestroyWorld(worldId)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
groundShapeDef := dbox2d.DefaultShapeDef()
groundBox := dbox2d.MakeBox(dbox2d.QFromInt(5), dbox2d.QHalf())
dbox2d.CreatePolygonShape(groundId, &groundShapeDef, &groundBox)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QOne()}
boxId := dbox2d.CreateBody(worldId, &boxDef)
boxShapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &boxShapeDef, &box)
dt := dbox2d.QOne().Div(dbox2d.QFromInt(60))
for range 60 {
worldId.Step(dt, 4)
}
data := make([]dbox2d.ContactData, boxId.GetContactCapacity())
count := boxId.GetContactData(data)
fmt.Println(count)
fmt.Println(data[0].ShapeIdA.GetBody() == groundId || data[0].ShapeIdB.GetBody() == groundId)
}
Output: 1 true
func (BodyId) GetGravityScale ¶ added in v0.4.0
GetGravityScale returns the body's gravity scale. It corresponds to b2Body_GetGravityScale.
func (BodyId) GetJointCount ¶ added in v0.4.0
GetJointCount returns the number of joints on the body. It corresponds to b2Body_GetJointCount.
func (BodyId) GetJoints ¶ added in v0.4.0
GetJoints fills joints in body-list order. It corresponds to b2Body_GetJoints.
func (BodyId) GetLinearDamping ¶ added in v0.4.0
GetLinearDamping returns linear damping. It corresponds to b2Body_GetLinearDamping.
func (BodyId) GetLinearVelocity ¶ added in v0.4.0
GetLinearVelocity returns the body's linear velocity. It corresponds to b2Body_GetLinearVelocity.
func (BodyId) GetLocalCenterOfMass ¶ added in v0.4.0
GetLocalCenterOfMass returns the center of mass in local coordinates. It corresponds to b2Body_GetLocalCenterOfMass.
func (BodyId) GetLocalPoint ¶ added in v0.4.0
GetLocalPoint converts a world point to the body's local frame. It corresponds to b2Body_GetLocalPoint.
func (BodyId) GetLocalPointVelocity ¶ added in v0.4.0
GetLocalPointVelocity returns the velocity at a local point. It corresponds to b2Body_GetLocalPointVelocity.
func (BodyId) GetLocalVector ¶ added in v0.4.0
GetLocalVector converts a world vector to the body's local frame. It corresponds to b2Body_GetLocalVector.
func (BodyId) GetMass ¶ added in v0.4.0
GetMass returns the mass of the body, usually in kilograms. It corresponds to b2Body_GetMass.
func (BodyId) GetMassData ¶ added in v0.4.0
GetMassData returns the body's mass, local center and rotational inertia. It corresponds to b2Body_GetMassData.
func (BodyId) GetName ¶ added in v0.4.0
GetName returns the stored body name. It corresponds to b2Body_GetName.
func (BodyId) GetPosition ¶ added in v0.4.0
GetPosition returns the world position of the body origin. It corresponds to b2Body_GetPosition.
func (BodyId) GetRotation ¶ added in v0.4.0
GetRotation returns the world rotation of the body. It corresponds to b2Body_GetRotation.
func (BodyId) GetRotationalInertia ¶ added in v0.4.0
GetRotationalInertia returns the inertia about the center of mass. It corresponds to b2Body_GetRotationalInertia.
func (BodyId) GetShapeCount ¶ added in v0.4.0
GetShapeCount returns the number of shapes on the body. It corresponds to b2Body_GetShapeCount.
func (BodyId) GetShapes ¶ added in v0.4.0
GetShapes fills shapes in body-list order. It corresponds to b2Body_GetShapes.
func (BodyId) GetSleepThreshold ¶ added in v0.4.0
GetSleepThreshold returns the body's sleep threshold. It corresponds to b2Body_GetSleepThreshold.
func (BodyId) GetTransform ¶ added in v0.4.0
GetTransform returns the world transform of the body. It corresponds to b2Body_GetTransform.
func (BodyId) GetType ¶ added in v0.4.0
GetType returns the body type. It corresponds to b2Body_GetType.
func (BodyId) GetUserData ¶ added in v0.4.0
GetUserData returns the data attached to the body. It corresponds to b2Body_GetUserData.
func (BodyId) GetWorld ¶ added in v0.4.0
GetWorld returns the world containing the body. It corresponds to b2Body_GetWorld.
func (BodyId) GetWorldCenterOfMass ¶ added in v0.4.0
GetWorldCenterOfMass returns the center of mass in world coordinates. It corresponds to b2Body_GetWorldCenterOfMass.
func (BodyId) GetWorldPoint ¶ added in v0.4.0
GetWorldPoint converts a local point to the world frame. It corresponds to b2Body_GetWorldPoint.
func (BodyId) GetWorldPointVelocity ¶ added in v0.4.0
GetWorldPointVelocity returns the velocity at a world point. It corresponds to b2Body_GetWorldPointVelocity.
func (BodyId) GetWorldVector ¶ added in v0.4.0
GetWorldVector converts a local vector to the world frame. It corresponds to b2Body_GetWorldVector.
func (BodyId) IsAwake ¶ added in v0.4.0
IsAwake reports whether the body is in the awake set. It corresponds to b2Body_IsAwake.
func (BodyId) IsBullet ¶ added in v0.4.0
IsBullet reports whether the body is treated as a bullet. It corresponds to b2Body_IsBullet.
func (BodyId) IsEnabled ¶ added in v0.4.0
IsEnabled reports whether the body is enabled. It corresponds to b2Body_IsEnabled.
func (BodyId) IsFixedRotation ¶ added in v0.4.0
IsFixedRotation reports whether body rotation is fixed. It corresponds to b2Body_IsFixedRotation.
func (BodyId) IsSleepEnabled ¶ added in v0.4.0
IsSleepEnabled reports whether the body may sleep. It corresponds to b2Body_IsSleepEnabled.
func (BodyId) SetAngularDamping ¶ added in v0.4.0
SetAngularDamping changes angular damping. It corresponds to b2Body_SetAngularDamping.
func (BodyId) SetAngularVelocity ¶ added in v0.4.0
SetAngularVelocity changes the body's angular velocity in turns per second. It corresponds to b2Body_SetAngularVelocity.
func (BodyId) SetAwake ¶ added in v0.4.0
SetAwake wakes or sleeps the body's island. It corresponds to b2Body_SetAwake.
func (BodyId) SetBullet ¶ added in v0.4.0
SetBullet changes whether the body is treated as a bullet. It corresponds to b2Body_SetBullet.
func (BodyId) SetFixedRotation ¶ added in v0.4.0
SetFixedRotation enables or disables body rotation. It corresponds to b2Body_SetFixedRotation.
func (BodyId) SetGravityScale ¶ added in v0.4.0
SetGravityScale changes the body's gravity scale. It corresponds to b2Body_SetGravityScale.
func (BodyId) SetLinearDamping ¶ added in v0.4.0
SetLinearDamping changes linear damping. It corresponds to b2Body_SetLinearDamping.
func (BodyId) SetLinearVelocity ¶ added in v0.4.0
SetLinearVelocity changes the body's linear velocity. It corresponds to b2Body_SetLinearVelocity.
func (BodyId) SetMassData ¶ added in v0.4.0
SetMassData overrides the body's mass, center and rotational inertia. It corresponds to b2Body_SetMassData.
func (BodyId) SetName ¶ added in v0.4.0
SetName stores up to 31 bytes of the body name. It corresponds to b2Body_SetName.
func (BodyId) SetSleepThreshold ¶ added in v0.4.0
SetSleepThreshold changes the body's sleep threshold. It corresponds to b2Body_SetSleepThreshold.
func (BodyId) SetTargetTransform ¶ added in v0.4.0
SetTargetTransform sets the velocity needed to reach a target transform. It corresponds to b2Body_SetTargetTransform.
func (BodyId) SetTransform ¶ added in v0.4.0
SetTransform changes the body's world transform. It corresponds to b2Body_SetTransform.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, _, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
boxId.SetTransform(dbox2d.Vec2{X: dbox2d.QOne(), Y: dbox2d.QFromInt(3)}, dbox2d.RotIdentity())
fmt.Println(boxId.GetPosition())
}
Output: {1 3}
func (BodyId) SetType ¶ added in v0.4.0
SetType changes the body type. It corresponds to b2Body_SetType.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, _, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
// A dynamic box turned static stops falling.
boxId.SetType(dbox2d.StaticBody)
fmt.Println(boxId.GetType() == dbox2d.StaticBody)
}
Output: true
func (BodyId) SetUserData ¶ added in v0.4.0
SetUserData attaches application data to the body. It corresponds to b2Body_SetUserData.
type BodyMoveEvent ¶ added in v0.3.0
BodyMoveEvent reports a body that the simulation moved. A body that the user moves does not report one. FellAsleep tells the application that it can sleep the object of the body. With sleep disabled, every dynamic and kinematic body reports on every step.
type BodyType ¶
type BodyType int
BodyType selects how the solver treats a body.
const ( // StaticBody has zero mass and zero velocity. An application may move it // manually. StaticBody BodyType = 0 // KinematicBody has zero mass. The application sets the velocity and the // solver moves it. KinematicBody BodyType = 1 // DynamicBody has positive mass. Forces determine the velocity and the // solver moves it. DynamicBody BodyType = 2 // BodyTypeCount is the number of body types. BodyTypeCount = 3 )
type Capsule ¶
type Capsule struct {
// Center1 is the local center of the first semicircle.
Center1 Vec2
// Center2 is the local center of the second semicircle.
Center2 Vec2
// Radius is the radius of both semicircles.
Radius Q
}
Capsule is a solid capsule: two semicircles joined by a rectangle.
type CastOutput ¶
type CastOutput struct {
// Normal is the surface normal at the hit point.
Normal Vec2
// Point is the surface hit point.
Point Vec2
// Fraction is the part of the input translation at the collision.
Fraction Q
// Iterations is the number of iterations the cast used.
Iterations int
// Hit reports whether the cast hit.
Hit bool
}
CastOutput is the output of a ray cast or of a shape cast. An initial overlap returns a zero fraction and a zero normal.
func RayCastCapsule ¶
func RayCastCapsule(input *RayCastInput, shape *Capsule) CastOutput
RayCastCapsule casts a ray against a capsule in local space. An initial overlap reports a hit at the ray origin with a zero fraction.
func RayCastCircle ¶
func RayCastCircle(input *RayCastInput, shape *Circle) CastOutput
RayCastCircle casts a ray against a circle in local space. An initial overlap reports a hit at the ray origin with a zero fraction.
func RayCastPolygon ¶
func RayCastPolygon(input *RayCastInput, shape *Polygon) CastOutput
RayCastPolygon casts a ray against a convex polygon in local space. An initial overlap reports a hit at the ray origin with a zero fraction.
A rounded polygon needs the shape cast, which arrives with the distance stage, so this function accepts only a polygon with a zero radius.
func RayCastSegment ¶
func RayCastSegment(input *RayCastInput, shape *Segment, oneSided bool) CastOutput
RayCastSegment casts a ray against a segment in local space. A one-sided segment reports a miss for a ray that arrives from the left.
func ShapeCast ¶ added in v0.3.0
func ShapeCast(input *ShapeCastPairInput) CastOutput
ShapeCast casts shape B against a fixed shape A by conservative advancement and reports the hit point, the normal and the fraction of the translation. Shapes that start in contact report a hit at a zero fraction unless the input allows an encroach. It corresponds to b2ShapeCast in src/distance.c.
func ShapeCastCapsule ¶ added in v0.3.0
func ShapeCastCapsule(input *ShapeCastInput, shape *Capsule) CastOutput
ShapeCastCapsule casts a proxy against a capsule in the local frame of the capsule. It corresponds to b2ShapeCastCapsule in src/geometry.c.
func ShapeCastCircle ¶ added in v0.3.0
func ShapeCastCircle(input *ShapeCastInput, shape *Circle) CastOutput
ShapeCastCircle casts a proxy against a circle in the local frame of the circle. It corresponds to b2ShapeCastCircle in src/geometry.c.
func ShapeCastPolygon ¶ added in v0.3.0
func ShapeCastPolygon(input *ShapeCastInput, shape *Polygon) CastOutput
ShapeCastPolygon casts a proxy against a polygon in the local frame of the polygon. It corresponds to b2ShapeCastPolygon in src/geometry.c.
func ShapeCastSegment ¶ added in v0.3.0
func ShapeCastSegment(input *ShapeCastInput, shape *Segment) CastOutput
ShapeCastSegment casts a proxy against a segment in the local frame of the segment. It corresponds to b2ShapeCastSegment in src/geometry.c.
type CastResultFcn ¶ added in v0.3.0
CastResultFcn receives each hit of a ray cast. Return -1 to skip the shape, 0 to stop, the fraction to clip the ray for the closest hit, or 1 to continue. It corresponds to b2CastResultFcn in include/box2d/types.h; the closure carries the context.
type ChainDef ¶ added in v0.4.0
type ChainDef struct {
// Application data attached to the chain's segments.
UserData any
// An array of at least four points. The points are copied during creation.
Points []Vec2
// One material for every segment, or one material shared by all segments.
Materials []SurfaceMaterial
// Collision filtering data.
Filter Filter
// Enable sensors to detect this chain.
EnableSensorEvents bool
// Connect the last point back to the first point.
IsLoop bool
// contains filtered or unexported fields
}
ChainDef configures a chain shape. It corresponds to b2ChainDef.
func DefaultChainDef ¶ added in v0.4.0
func DefaultChainDef() ChainDef
DefaultChainDef returns the default chain definition. It corresponds to b2DefaultChainDef.
type ChainId ¶
type ChainId struct {
// contains filtered or unexported fields
}
ChainId identifies a chain. Its zero value is null.
func CreateChain ¶ added in v0.4.0
CreateChain ports b2CreateChain.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, groundId, _ := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
// An open chain of four points builds two segments; the two end
// segments extend with ghost vertices for smooth rolling contact.
def := dbox2d.DefaultChainDef()
def.Points = []dbox2d.Vec2{
{X: dbox2d.QFromInt(0)},
{X: dbox2d.QFromInt(1)},
{X: dbox2d.QFromInt(2)},
{X: dbox2d.QFromInt(3)},
{X: dbox2d.QFromInt(4)},
}
chainId := dbox2d.CreateChain(groundId, &def)
fmt.Println(chainId.GetSegmentCount())
}
Output: 2
func (ChainId) GetFriction ¶ added in v0.4.0
GetFriction returns the first segment's friction. It corresponds to b2Chain_GetFriction.
func (ChainId) GetMaterial ¶ added in v0.4.0
GetMaterial returns the first segment's user material id. It corresponds to b2Chain_GetMaterial.
func (ChainId) GetRestitution ¶ added in v0.4.0
GetRestitution returns the first segment's restitution. It corresponds to b2Chain_GetRestitution.
func (ChainId) GetSegmentCount ¶ added in v0.4.0
GetSegmentCount returns the number of segments in the chain. It corresponds to b2Chain_GetSegmentCount.
func (ChainId) GetSegments ¶ added in v0.4.0
GetSegments fills segments with the chain's segment shapes. It corresponds to b2Chain_GetSegments.
func (ChainId) GetWorld ¶ added in v0.4.0
GetWorld returns the world containing the chain. It corresponds to b2Chain_GetWorld.
func (ChainId) SetFriction ¶ added in v0.4.0
SetFriction changes the friction of every chain segment. It corresponds to b2Chain_SetFriction.
func (ChainId) SetMaterial ¶ added in v0.4.0
SetMaterial changes the user material id of every chain segment. It corresponds to b2Chain_SetMaterial.
func (ChainId) SetRestitution ¶ added in v0.4.0
SetRestitution changes the restitution of every chain segment. It corresponds to b2Chain_SetRestitution.
type ChainSegment ¶
type ChainSegment struct {
// Ghost1 is the tail ghost vertex.
Ghost1 Vec2
// Segment is the colliding part.
Segment Segment
// Ghost2 is the head ghost vertex.
Ghost2 Vec2
// ChainId is the owning chain shape. It is internal bookkeeping.
ChainId int
}
ChainSegment is a line segment with one-sided collision. It collides only on the right side. A chain shape generates several of them, in the order ghost1, point1, point2, ghost2.
type CollisionPlane ¶ added in v0.4.0
CollisionPlane is a plane constraint for the mover plane solver.
type ContactBeginTouchEvent ¶ added in v0.3.0
type ContactBeginTouchEvent struct {
// ShapeIdA is the first shape.
ShapeIdA ShapeId
// ShapeIdB is the second shape.
ShapeIdB ShapeId
// Manifold is the initial contact manifold. The world records it
// before the solver runs, so every impulse is zero.
Manifold Manifold
}
ContactBeginTouchEvent reports that two shapes started to touch.
type ContactData ¶ added in v0.4.0
type ContactData struct {
// ShapeIdA is the first shape in the contact.
ShapeIdA ShapeId
// ShapeIdB is the second shape in the contact.
ShapeIdB ShapeId
// Manifold is the current contact manifold.
Manifold Manifold
}
ContactData reports the manifold of a touching contact on a body. It corresponds to b2ContactData in include/box2d/types.h.
type ContactEndTouchEvent ¶ added in v0.3.0
type ContactEndTouchEvent struct {
// ShapeIdA is the first shape. It may be destroyed; see IsValid.
ShapeIdA ShapeId
// ShapeIdB is the second shape. It may be destroyed; see IsValid.
ShapeIdB ShapeId
}
ContactEndTouchEvent reports that two shapes stopped touching. Any action that destroys a contact between steps also reports one, such as a transform change, a body or shape destroy, or a body type change.
type ContactEvents ¶ added in v0.3.0
type ContactEvents struct {
BeginEvents []ContactBeginTouchEvent
EndEvents []ContactEndTouchEvent
HitEvents []ContactHitEvent
}
ContactEvents holds the contact events of the last step. The slices stay valid until the next step; a body or shape destroy may make an id in them stale.
type ContactHitEvent ¶ added in v0.3.0
type ContactHitEvent struct {
// ShapeIdA is the first shape.
ShapeIdA ShapeId
// ShapeIdB is the second shape.
ShapeIdB ShapeId
// Point is where the shapes hit at the start of the step. It is the
// mid-point between the two surfaces.
Point Vec2
// Normal points from shape A to shape B.
Normal Vec2
// ApproachSpeed is the closing speed of the shapes. It is positive.
ApproachSpeed Q
}
ContactHitEvent reports that two shapes collided faster than the hit event threshold. A speculative contact with a confirmed impulse also reports one.
type Counters ¶ added in v0.4.0
type Counters struct {
BodyCount, ShapeCount, ContactCount, JointCount, IslandCount, StackUsed, StaticTreeHeight, TreeHeight int
TaskCount int
ColorCounts [graphColorCount]int
}
Counters reports world sizes and solver storage usage for diagnostics.
type CustomFilterFcn ¶ added in v0.4.0
CustomFilterFcn decides whether two shapes may collide. It corresponds to b2CustomFilterFcn; return false to reject the pair. With several workers it runs on worker goroutines while the step mutates the world: it must not call the world API or query it, must not panic, and must be safe to call concurrently.
type DebugDraw ¶ added in v0.4.0
type DebugDraw struct {
// DrawPolygon draws a closed polygon provided in CCW order.
DrawPolygon DrawPolygonFcn
// DrawSolidPolygon draws a solid closed polygon provided in CCW order.
DrawSolidPolygon DrawSolidPolygonFcn
// DrawCircle draws a circle.
DrawCircle DrawCircleFcn
// DrawSolidCircle draws a solid circle.
DrawSolidCircle DrawSolidCircleFcn
// DrawSolidCapsule draws a solid capsule.
DrawSolidCapsule DrawSolidCapsuleFcn
// DrawSegment draws a line segment.
DrawSegment DrawSegmentFcn
// DrawTransform draws a transform at a host-chosen length scale.
DrawTransform DrawTransformFcn
// DrawPoint draws a point.
DrawPoint DrawPointFcn
// DrawString draws a string in world space.
DrawString DrawStringFcn
// DrawingBounds is the region used when UseDrawingBounds restricts drawing.
DrawingBounds AABB
// UseDrawingBounds restricts drawing to DrawingBounds; depth sorting may be unstable.
UseDrawingBounds bool
// DrawShapes draws shapes.
DrawShapes bool
// DrawJoints draws joints.
DrawJoints bool
// DrawJointExtras draws additional information for joints.
DrawJointExtras bool
// DrawBounds draws the bounding boxes for shapes.
DrawBounds bool
// DrawMass draws the mass and center of mass of dynamic bodies.
DrawMass bool
// DrawBodyNames draws body names.
DrawBodyNames bool
// DrawContacts draws contact points.
DrawContacts bool
// DrawGraphColors visualizes the graph coloring used for contacts and joints.
DrawGraphColors bool
// DrawContactNormals draws contact normals.
DrawContactNormals bool
// DrawContactImpulses draws contact normal impulses.
DrawContactImpulses bool
// DrawContactFeatures draws contact feature ids.
DrawContactFeatures bool
// DrawFrictionImpulses draws contact friction impulses.
DrawFrictionImpulses bool
// DrawIslands draws islands as bounding boxes.
DrawIslands bool
}
DebugDraw holds the callbacks and options used by WorldId.Draw. Set the option fields to choose what the callbacks receive.
func DefaultDebugDraw ¶ added in v0.4.0
func DefaultDebugDraw() DebugDraw
DefaultDebugDraw returns a debug drawer whose callbacks are safe no-ops.
type DistanceInput ¶ added in v0.3.0
type DistanceInput struct {
// ProxyA is the proxy of shape A.
ProxyA ShapeProxy
// ProxyB is the proxy of shape B.
ProxyB ShapeProxy
// TransformA is the world transform of shape A.
TransformA Transform
// TransformB is the world transform of shape B.
TransformB Transform
// UseRadii asks the solver to subtract the proxy radii.
UseRadii bool
}
DistanceInput is the input of ShapeDistance. It corresponds to b2DistanceInput in include/box2d/collision.h.
type DistanceJointDef ¶ added in v0.3.0
type DistanceJointDef struct {
// The first attached body.
BodyIdA BodyId
// The second attached body.
BodyIdB BodyId
// The local anchor point relative to the origin of body A.
LocalAnchorA Vec2
// The local anchor point relative to the origin of body B.
LocalAnchorB Vec2
// The rest length of the joint. Clamped to a stable minimum value.
Length Q
// Enable the distance constraint to behave like a spring. If false the
// distance joint is rigid, otherwise the limit and the motor apply.
EnableSpring bool
// The spring linear stiffness in cycles per second.
Hertz Q
// The spring linear damping ratio, non-dimensional.
DampingRatio Q
// Enable and disable the joint limit.
EnableLimit bool
// The minimum length. Clamped to a stable minimum value.
MinLength Q
// The maximum length. Must be greater than or equal to the minimum
// length.
MaxLength Q
// Enable and disable the joint motor.
EnableMotor bool
// The maximum motor force, usually in newtons.
MaxMotorForce Q
// The desired motor speed, usually in meters per second.
MotorSpeed Q
// Set this flag to true if the attached bodies should collide.
CollideConnected bool
// Application data attached to the joint.
UserData any
// contains filtered or unexported fields
}
DistanceJointDef configures a distance joint: a point on each body kept at a fixed length, or within a length range. Initialize it with DefaultDistanceJointDef.
func DefaultDistanceJointDef ¶ added in v0.3.0
func DefaultDistanceJointDef() DistanceJointDef
DefaultDistanceJointDef returns the default distance joint definition.
type DistanceOutput ¶ added in v0.3.0
type DistanceOutput struct {
// PointA is the closest point on shape A.
PointA Vec2
// PointB is the closest point on shape B.
PointB Vec2
// Normal points from A to B. It is invalid when the distance is zero.
Normal Vec2
// Distance is the final distance, zero when the shapes overlap.
Distance Q
// Iterations counts the GJK iterations used.
Iterations int
// SimplexCount is the number of simplexes stored in the debug slice.
SimplexCount int
}
DistanceOutput is the output of ShapeDistance. It corresponds to b2DistanceOutput in include/box2d/collision.h.
func ShapeDistance ¶ added in v0.3.0
func ShapeDistance(input *DistanceInput, cache *SimplexCache, simplexes []Simplex) DistanceOutput
ShapeDistance computes the closest points between two convex proxies with GJK. The cache is input and output; start with the zero value. The simplexes slice receives the simplex of each iteration for debugging; pass nil to skip it. It corresponds to b2ShapeDistance in src/distance.c, https://box2d.org/files/ErinCatto_GJK_GDC2010.pdf.
The reference stops on a search direction shorter than FLT_EPSILON; the port stops on a squared length of exactly zero (D-012).
type DrawCircleFcn ¶ added in v0.4.0
DrawCircleFcn draws a circle outline.
type DrawPointFcn ¶ added in v0.4.0
DrawPointFcn draws a point of the requested size.
type DrawPolygonFcn ¶ added in v0.4.0
DrawPolygonFcn draws a closed polygon in counter-clockwise order.
type DrawSegmentFcn ¶ added in v0.4.0
DrawSegmentFcn draws a line segment.
type DrawSolidCapsuleFcn ¶ added in v0.4.0
DrawSolidCapsuleFcn draws a solid capsule.
type DrawSolidCircleFcn ¶ added in v0.4.0
DrawSolidCircleFcn draws a solid circle.
type DrawSolidPolygonFcn ¶ added in v0.4.0
DrawSolidPolygonFcn draws a solid polygon with a rounded radius.
type DrawStringFcn ¶ added in v0.4.0
DrawStringFcn draws a world-space string.
type DrawTransformFcn ¶ added in v0.4.0
type DrawTransformFcn func(transform Transform)
DrawTransformFcn draws a transform with a host-selected scale.
type DynamicTree ¶ added in v0.7.0
type DynamicTree struct {
// contains filtered or unexported fields
}
DynamicTree is a standalone bounding volume hierarchy over proxies. The world keeps its own trees; this type serves user code that wants the tree as a spatial structure. It corresponds to b2DynamicTree and the b2DynamicTree_* functions of include/box2d/collision.h.
func NewDynamicTree ¶ added in v0.7.0
func NewDynamicTree() *DynamicTree
NewDynamicTree returns an empty tree. It corresponds to b2DynamicTree_Create.
func (*DynamicTree) CreateProxy ¶ added in v0.7.0
func (t *DynamicTree) CreateProxy(aabb AABB, categoryBits uint64, userData uint64) int
CreateProxy inserts a proxy with a fat box and returns its id. It corresponds to b2DynamicTree_CreateProxy.
func (*DynamicTree) Destroy ¶ added in v0.7.0
func (t *DynamicTree) Destroy()
Destroy releases the node pool. It corresponds to b2DynamicTree_Destroy.
func (*DynamicTree) DestroyProxy ¶ added in v0.7.0
func (t *DynamicTree) DestroyProxy(proxyId int)
DestroyProxy removes a proxy. It corresponds to b2DynamicTree_DestroyProxy.
func (*DynamicTree) EnlargeProxy ¶ added in v0.7.0
func (t *DynamicTree) EnlargeProxy(proxyId int, aabb AABB)
EnlargeProxy grows a proxy in place; a later Rebuild repairs the tree. The new box must not fit in the old one. It corresponds to b2DynamicTree_EnlargeProxy.
func (*DynamicTree) GetAABB ¶ added in v0.7.0
func (t *DynamicTree) GetAABB(proxyId int) AABB
GetAABB returns the box of a proxy. It corresponds to b2DynamicTree_GetAABB.
func (*DynamicTree) GetAreaRatio ¶ added in v0.7.0
func (t *DynamicTree) GetAreaRatio() Q
GetAreaRatio returns the summed perimeter of the internal nodes over the perimeter of the root. It corresponds to b2DynamicTree_GetAreaRatio.
func (*DynamicTree) GetCategoryBits ¶ added in v0.7.0
func (t *DynamicTree) GetCategoryBits(proxyId int) uint64
GetCategoryBits returns the category bits of a proxy. It corresponds to b2DynamicTree_GetCategoryBits.
func (*DynamicTree) GetHeight ¶ added in v0.7.0
func (t *DynamicTree) GetHeight() int
GetHeight returns the height of the tree. It corresponds to b2DynamicTree_GetHeight.
func (*DynamicTree) GetProxyCount ¶ added in v0.7.0
func (t *DynamicTree) GetProxyCount() int
GetProxyCount returns the number of proxies. It corresponds to b2DynamicTree_GetProxyCount.
func (*DynamicTree) GetRootBounds ¶ added in v0.7.0
func (t *DynamicTree) GetRootBounds() AABB
GetRootBounds returns the box of the root, or the empty box for an empty tree. It corresponds to b2DynamicTree_GetRootBounds.
func (*DynamicTree) GetUserData ¶ added in v0.7.0
func (t *DynamicTree) GetUserData(proxyId int) uint64
GetUserData returns the user data of a proxy. It corresponds to b2DynamicTree_GetUserData.
func (*DynamicTree) MoveProxy ¶ added in v0.7.0
func (t *DynamicTree) MoveProxy(proxyId int, aabb AABB)
MoveProxy reinserts a proxy with a new box. It corresponds to b2DynamicTree_MoveProxy.
func (*DynamicTree) Query ¶ added in v0.7.0
func (t *DynamicTree) Query(aabb AABB, maskBits uint64, fcn TreeQueryCallbackFcn) TreeStats
Query calls back every proxy that overlaps the box and passes the mask. It corresponds to b2DynamicTree_Query.
func (*DynamicTree) RayCast ¶ added in v0.7.0
func (t *DynamicTree) RayCast(input *RayCastInput, maskBits uint64, fcn TreeRayCastCallbackFcn) TreeStats
RayCast calls back every proxy whose box the ray reaches. It corresponds to b2DynamicTree_RayCast.
func (*DynamicTree) Rebuild ¶ added in v0.7.0
func (t *DynamicTree) Rebuild(fullBuild bool) int
Rebuild rebuilds the enlarged part of the tree, or the whole tree when fullBuild is set. It returns the leaf count of the build. It corresponds to b2DynamicTree_Rebuild.
func (*DynamicTree) SetCategoryBits ¶ added in v0.7.0
func (t *DynamicTree) SetCategoryBits(proxyId int, categoryBits uint64)
SetCategoryBits changes the category bits of a proxy. It corresponds to b2DynamicTree_SetCategoryBits.
func (*DynamicTree) ShapeCast ¶ added in v0.7.0
func (t *DynamicTree) ShapeCast(input *ShapeCastInput, maskBits uint64, fcn TreeShapeCastCallbackFcn) TreeStats
ShapeCast calls back every proxy whose box the swept proxy may reach. It corresponds to b2DynamicTree_ShapeCast.
func (*DynamicTree) Validate ¶ added in v0.7.0
func (t *DynamicTree) Validate()
Validate checks the tree. Like the reference, it does nothing unless the build enables validation (-tags dbox2d_validate). It corresponds to b2DynamicTree_Validate.
func (*DynamicTree) ValidateNoEnlarged ¶ added in v0.7.0
func (t *DynamicTree) ValidateNoEnlarged()
ValidateNoEnlarged checks that no proxy is left enlarged. Like Validate, it does nothing unless the build enables validation. It corresponds to b2DynamicTree_ValidateNoEnlarged.
type ExplosionDef ¶ added in v0.4.0
type ExplosionDef struct {
// MaskBits filters the shapes the explosion reaches.
MaskBits uint64
// Position is the center of the explosion in world space.
Position Vec2
// Radius is the full-impulse radius of the explosion.
Radius Q
// Falloff is the distance beyond Radius where the impulse fades to zero.
Falloff Q
// ImpulsePerLength scales the impulse by the perimeter facing the
// explosion. It may be negative for an implosion.
ImpulsePerLength Q
}
ExplosionDef configures an explosion. It corresponds to b2ExplosionDef in include/box2d/types.h.
func DefaultExplosionDef ¶ added in v0.4.0
func DefaultExplosionDef() ExplosionDef
DefaultExplosionDef returns an explosion definition with every mask bit set and every other field zero. It corresponds to b2DefaultExplosionDef.
type Filter ¶
type Filter struct {
// The collision category bits of this shape. Normally one bit per
// application object type.
CategoryBits uint64
// The categories that this shape accepts for collision.
MaskBits uint64
// Shapes in the same negative group never collide; in the same positive
// group they always collide. Zero has no effect. A non-zero group wins
// against the mask bits.
GroupIndex int
}
Filter controls collision between shapes, and between queries and shapes.
func DefaultFilter ¶
func DefaultFilter() Filter
DefaultFilter returns the default filter: category 1, every mask bit set, no group.
type FilterJointDef ¶ added in v0.3.0
type FilterJointDef struct {
// The first attached body.
BodyIdA BodyId
// The second attached body.
BodyIdB BodyId
// Application data attached to the joint.
UserData any
// contains filtered or unexported fields
}
FilterJointDef configures a filter joint: it only disables collision between two bodies. Initialize it with DefaultFilterJointDef.
func DefaultFilterJointDef ¶ added in v0.3.0
func DefaultFilterJointDef() FilterJointDef
DefaultFilterJointDef returns the default filter joint definition.
type FrictionCallback ¶ added in v0.4.0
FrictionCallback mixes the friction values of two shapes.
type HexColor ¶ added in v0.4.0
type HexColor uint32
HexColor is an RGB color encoded as 0xRRGGBB.
const ( // ColorAliceBlue is RGB 0xF0F8FF. ColorAliceBlue HexColor = 0xF0F8FF // ColorAntiqueWhite is RGB 0xFAEBD7. ColorAntiqueWhite HexColor = 0xFAEBD7 // ColorAqua is RGB 0x00FFFF. ColorAqua HexColor = 0x00FFFF // ColorAquamarine is RGB 0x7FFFD4. ColorAquamarine HexColor = 0x7FFFD4 // ColorAzure is RGB 0xF0FFFF. ColorAzure HexColor = 0xF0FFFF // ColorBeige is RGB 0xF5F5DC. ColorBeige HexColor = 0xF5F5DC // ColorBisque is RGB 0xFFE4C4. ColorBisque HexColor = 0xFFE4C4 // ColorBlack is RGB 0x000000. ColorBlack HexColor = 0x000000 // ColorBlanchedAlmond is RGB 0xFFEBCD. ColorBlanchedAlmond HexColor = 0xFFEBCD // ColorBlue is RGB 0x0000FF. ColorBlue HexColor = 0x0000FF // ColorBlueViolet is RGB 0x8A2BE2. ColorBlueViolet HexColor = 0x8A2BE2 // ColorBrown is RGB 0xA52A2A. ColorBrown HexColor = 0xA52A2A // ColorBurlywood is RGB 0xDEB887. ColorBurlywood HexColor = 0xDEB887 // ColorCadetBlue is RGB 0x5F9EA0. ColorCadetBlue HexColor = 0x5F9EA0 // ColorChartreuse is RGB 0x7FFF00. ColorChartreuse HexColor = 0x7FFF00 // ColorChocolate is RGB 0xD2691E. ColorChocolate HexColor = 0xD2691E // ColorCoral is RGB 0xFF7F50. ColorCoral HexColor = 0xFF7F50 // ColorCornflowerBlue is RGB 0x6495ED. ColorCornflowerBlue HexColor = 0x6495ED // ColorCornsilk is RGB 0xFFF8DC. ColorCornsilk HexColor = 0xFFF8DC // ColorCrimson is RGB 0xDC143C. ColorCrimson HexColor = 0xDC143C // ColorCyan is RGB 0x00FFFF. ColorCyan HexColor = 0x00FFFF // ColorDarkBlue is RGB 0x00008B. ColorDarkBlue HexColor = 0x00008B // ColorDarkCyan is RGB 0x008B8B. ColorDarkCyan HexColor = 0x008B8B // ColorDarkGoldenRod is RGB 0xB8860B. ColorDarkGoldenRod HexColor = 0xB8860B // ColorDarkGray is RGB 0xA9A9A9. ColorDarkGray HexColor = 0xA9A9A9 // ColorDarkGreen is RGB 0x006400. ColorDarkGreen HexColor = 0x006400 // ColorDarkKhaki is RGB 0xBDB76B. ColorDarkKhaki HexColor = 0xBDB76B // ColorDarkMagenta is RGB 0x8B008B. ColorDarkMagenta HexColor = 0x8B008B // ColorDarkOliveGreen is RGB 0x556B2F. ColorDarkOliveGreen HexColor = 0x556B2F // ColorDarkOrange is RGB 0xFF8C00. ColorDarkOrange HexColor = 0xFF8C00 // ColorDarkOrchid is RGB 0x9932CC. ColorDarkOrchid HexColor = 0x9932CC // ColorDarkRed is RGB 0x8B0000. ColorDarkRed HexColor = 0x8B0000 // ColorDarkSalmon is RGB 0xE9967A. ColorDarkSalmon HexColor = 0xE9967A // ColorDarkSeaGreen is RGB 0x8FBC8F. ColorDarkSeaGreen HexColor = 0x8FBC8F // ColorDarkSlateBlue is RGB 0x483D8B. ColorDarkSlateBlue HexColor = 0x483D8B // ColorDarkSlateGray is RGB 0x2F4F4F. ColorDarkSlateGray HexColor = 0x2F4F4F // ColorDarkTurquoise is RGB 0x00CED1. ColorDarkTurquoise HexColor = 0x00CED1 // ColorDarkViolet is RGB 0x9400D3. ColorDarkViolet HexColor = 0x9400D3 // ColorDeepPink is RGB 0xFF1493. ColorDeepPink HexColor = 0xFF1493 // ColorDeepSkyBlue is RGB 0x00BFFF. ColorDeepSkyBlue HexColor = 0x00BFFF // ColorDimGray is RGB 0x696969. ColorDimGray HexColor = 0x696969 // ColorDodgerBlue is RGB 0x1E90FF. ColorDodgerBlue HexColor = 0x1E90FF // ColorFireBrick is RGB 0xB22222. ColorFireBrick HexColor = 0xB22222 // ColorFloralWhite is RGB 0xFFFAF0. ColorFloralWhite HexColor = 0xFFFAF0 // ColorForestGreen is RGB 0x228B22. ColorForestGreen HexColor = 0x228B22 // ColorFuchsia is RGB 0xFF00FF. ColorFuchsia HexColor = 0xFF00FF // ColorGainsboro is RGB 0xDCDCDC. ColorGainsboro HexColor = 0xDCDCDC // ColorGhostWhite is RGB 0xF8F8FF. ColorGhostWhite HexColor = 0xF8F8FF // ColorGold is RGB 0xFFD700. ColorGold HexColor = 0xFFD700 // ColorGoldenRod is RGB 0xDAA520. ColorGoldenRod HexColor = 0xDAA520 // ColorGray is RGB 0x808080. ColorGray HexColor = 0x808080 // ColorGreen is RGB 0x008000. ColorGreen HexColor = 0x008000 // ColorGreenYellow is RGB 0xADFF2F. ColorGreenYellow HexColor = 0xADFF2F // ColorHoneyDew is RGB 0xF0FFF0. ColorHoneyDew HexColor = 0xF0FFF0 // ColorHotPink is RGB 0xFF69B4. ColorHotPink HexColor = 0xFF69B4 // ColorIndianRed is RGB 0xCD5C5C. ColorIndianRed HexColor = 0xCD5C5C // ColorIndigo is RGB 0x4B0082. ColorIndigo HexColor = 0x4B0082 // ColorIvory is RGB 0xFFFFF0. ColorIvory HexColor = 0xFFFFF0 // ColorKhaki is RGB 0xF0E68C. ColorKhaki HexColor = 0xF0E68C // ColorLavender is RGB 0xE6E6FA. ColorLavender HexColor = 0xE6E6FA // ColorLavenderBlush is RGB 0xFFF0F5. ColorLavenderBlush HexColor = 0xFFF0F5 // ColorLawnGreen is RGB 0x7CFC00. ColorLawnGreen HexColor = 0x7CFC00 // ColorLemonChiffon is RGB 0xFFFACD. ColorLemonChiffon HexColor = 0xFFFACD // ColorLightBlue is RGB 0xADD8E6. ColorLightBlue HexColor = 0xADD8E6 // ColorLightCoral is RGB 0xF08080. ColorLightCoral HexColor = 0xF08080 // ColorLightCyan is RGB 0xE0FFFF. ColorLightCyan HexColor = 0xE0FFFF // ColorLightGoldenRodYellow is RGB 0xFAFAD2. ColorLightGoldenRodYellow HexColor = 0xFAFAD2 // ColorLightGray is RGB 0xD3D3D3. ColorLightGray HexColor = 0xD3D3D3 // ColorLightGreen is RGB 0x90EE90. ColorLightGreen HexColor = 0x90EE90 // ColorLightPink is RGB 0xFFB6C1. ColorLightPink HexColor = 0xFFB6C1 // ColorLightSalmon is RGB 0xFFA07A. ColorLightSalmon HexColor = 0xFFA07A // ColorLightSeaGreen is RGB 0x20B2AA. ColorLightSeaGreen HexColor = 0x20B2AA // ColorLightSkyBlue is RGB 0x87CEFA. ColorLightSkyBlue HexColor = 0x87CEFA // ColorLightSlateGray is RGB 0x778899. ColorLightSlateGray HexColor = 0x778899 // ColorLightSteelBlue is RGB 0xB0C4DE. ColorLightSteelBlue HexColor = 0xB0C4DE // ColorLightYellow is RGB 0xFFFFE0. ColorLightYellow HexColor = 0xFFFFE0 // ColorLime is RGB 0x00FF00. ColorLime HexColor = 0x00FF00 // ColorLimeGreen is RGB 0x32CD32. ColorLimeGreen HexColor = 0x32CD32 // ColorLinen is RGB 0xFAF0E6. ColorLinen HexColor = 0xFAF0E6 // ColorMagenta is RGB 0xFF00FF. ColorMagenta HexColor = 0xFF00FF // ColorMaroon is RGB 0x800000. ColorMaroon HexColor = 0x800000 // ColorMediumAquaMarine is RGB 0x66CDAA. ColorMediumAquaMarine HexColor = 0x66CDAA // ColorMediumBlue is RGB 0x0000CD. ColorMediumBlue HexColor = 0x0000CD // ColorMediumOrchid is RGB 0xBA55D3. ColorMediumOrchid HexColor = 0xBA55D3 // ColorMediumPurple is RGB 0x9370DB. ColorMediumPurple HexColor = 0x9370DB // ColorMediumSeaGreen is RGB 0x3CB371. ColorMediumSeaGreen HexColor = 0x3CB371 // ColorMediumSlateBlue is RGB 0x7B68EE. ColorMediumSlateBlue HexColor = 0x7B68EE // ColorMediumSpringGreen is RGB 0x00FA9A. ColorMediumSpringGreen HexColor = 0x00FA9A // ColorMediumTurquoise is RGB 0x48D1CC. ColorMediumTurquoise HexColor = 0x48D1CC // ColorMediumVioletRed is RGB 0xC71585. ColorMediumVioletRed HexColor = 0xC71585 // ColorMidnightBlue is RGB 0x191970. ColorMidnightBlue HexColor = 0x191970 // ColorMintCream is RGB 0xF5FFFA. ColorMintCream HexColor = 0xF5FFFA // ColorMistyRose is RGB 0xFFE4E1. ColorMistyRose HexColor = 0xFFE4E1 // ColorMoccasin is RGB 0xFFE4B5. ColorMoccasin HexColor = 0xFFE4B5 ColorNavajoWhite HexColor = 0xFFDEAD ColorNavy HexColor = 0x000080 // ColorOldLace is RGB 0xFDF5E6. ColorOldLace HexColor = 0xFDF5E6 // ColorOlive is RGB 0x808000. ColorOlive HexColor = 0x808000 // ColorOliveDrab is RGB 0x6B8E23. ColorOliveDrab HexColor = 0x6B8E23 // ColorOrange is RGB 0xFFA500. ColorOrange HexColor = 0xFFA500 // ColorOrangeRed is RGB 0xFF4500. ColorOrangeRed HexColor = 0xFF4500 // ColorOrchid is RGB 0xDA70D6. ColorOrchid HexColor = 0xDA70D6 // ColorPaleGoldenRod is RGB 0xEEE8AA. ColorPaleGoldenRod HexColor = 0xEEE8AA // ColorPaleGreen is RGB 0x98FB98. ColorPaleGreen HexColor = 0x98FB98 // ColorPaleTurquoise is RGB 0xAFEEEE. ColorPaleTurquoise HexColor = 0xAFEEEE // ColorPaleVioletRed is RGB 0xDB7093. ColorPaleVioletRed HexColor = 0xDB7093 // ColorPapayaWhip is RGB 0xFFEFD5. ColorPapayaWhip HexColor = 0xFFEFD5 // ColorPeachPuff is RGB 0xFFDAB9. ColorPeachPuff HexColor = 0xFFDAB9 // ColorPeru is RGB 0xCD853F. ColorPeru HexColor = 0xCD853F // ColorPink is RGB 0xFFC0CB. ColorPink HexColor = 0xFFC0CB // ColorPlum is RGB 0xDDA0DD. ColorPlum HexColor = 0xDDA0DD // ColorPowderBlue is RGB 0xB0E0E6. ColorPowderBlue HexColor = 0xB0E0E6 // ColorPurple is RGB 0x800080. ColorPurple HexColor = 0x800080 // ColorRebeccaPurple is RGB 0x663399. ColorRebeccaPurple HexColor = 0x663399 // ColorRed is RGB 0xFF0000. ColorRed HexColor = 0xFF0000 // ColorRosyBrown is RGB 0xBC8F8F. ColorRosyBrown HexColor = 0xBC8F8F // ColorRoyalBlue is RGB 0x4169E1. ColorRoyalBlue HexColor = 0x4169E1 // ColorSaddleBrown is RGB 0x8B4513. ColorSaddleBrown HexColor = 0x8B4513 // ColorSalmon is RGB 0xFA8072. ColorSalmon HexColor = 0xFA8072 // ColorSandyBrown is RGB 0xF4A460. ColorSandyBrown HexColor = 0xF4A460 // ColorSeaGreen is RGB 0x2E8B57. ColorSeaGreen HexColor = 0x2E8B57 // ColorSeaShell is RGB 0xFFF5EE. ColorSeaShell HexColor = 0xFFF5EE // ColorSienna is RGB 0xA0522D. ColorSienna HexColor = 0xA0522D // ColorSilver is RGB 0xC0C0C0. ColorSilver HexColor = 0xC0C0C0 // ColorSkyBlue is RGB 0x87CEEB. ColorSkyBlue HexColor = 0x87CEEB // ColorSlateBlue is RGB 0x6A5ACD. ColorSlateBlue HexColor = 0x6A5ACD // ColorSlateGray is RGB 0x708090. ColorSlateGray HexColor = 0x708090 // ColorSnow is RGB 0xFFFAFA. ColorSnow HexColor = 0xFFFAFA // ColorSpringGreen is RGB 0x00FF7F. ColorSpringGreen HexColor = 0x00FF7F // ColorSteelBlue is RGB 0x4682B4. ColorSteelBlue HexColor = 0x4682B4 // ColorTan is RGB 0xD2B48C. ColorTan HexColor = 0xD2B48C // ColorTeal is RGB 0x008080. ColorTeal HexColor = 0x008080 // ColorThistle is RGB 0xD8BFD8. ColorThistle HexColor = 0xD8BFD8 // ColorTomato is RGB 0xFF6347. ColorTomato HexColor = 0xFF6347 // ColorTurquoise is RGB 0x40E0D0. ColorTurquoise HexColor = 0x40E0D0 // ColorViolet is RGB 0xEE82EE. ColorViolet HexColor = 0xEE82EE // ColorWheat is RGB 0xF5DEB3. ColorWheat HexColor = 0xF5DEB3 // ColorWhite is RGB 0xFFFFFF. ColorWhite HexColor = 0xFFFFFF // ColorWhiteSmoke is RGB 0xF5F5F5. ColorWhiteSmoke HexColor = 0xF5F5F5 // ColorYellow is RGB 0xFFFF00. ColorYellow HexColor = 0xFFFF00 // ColorYellowGreen is RGB 0x9ACD32. ColorYellowGreen HexColor = 0x9ACD32 // ColorBox2DRed is RGB 0xDC3132. ColorBox2DRed HexColor = 0xDC3132 // ColorBox2DBlue is RGB 0x30AEBF. ColorBox2DBlue HexColor = 0x30AEBF // ColorBox2DGreen is RGB 0x8CC924. ColorBox2DGreen HexColor = 0x8CC924 // ColorBox2DYellow is RGB 0xFFEE8C. ColorBox2DYellow HexColor = 0xFFEE8C )
type Hull ¶
type Hull struct {
// Points holds the hull corners. Only the first Count entries are valid.
Points [MaxPolygonVertices]Vec2
// Count is the number of points.
Count int
}
Hull is a convex hull. It feeds the polygon constructors. Build one with ComputeHull and do not modify it afterwards.
func ComputeHull ¶
ComputeHull returns the convex hull of a set of points. It welds points that are closer than four linear slops and it drops collinear points. It returns an empty hull on failure: fewer than three points, more than MaxPolygonVertices points, points all very close, or points all on a line.
type JointId ¶
type JointId struct {
// contains filtered or unexported fields
}
JointId identifies a joint. Its zero value is null.
func CreateDistanceJoint ¶ added in v0.3.0
func CreateDistanceJoint(worldId WorldId, def *DistanceJointDef) JointId
CreateDistanceJoint creates a distance joint. The definition must come from DefaultDistanceJointDef.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, groundId, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
// A rope of length two from the ground origin to the box center.
def := dbox2d.DefaultDistanceJointDef()
def.BodyIdA = groundId
def.BodyIdB = boxId
def.Length = dbox2d.QFromInt(2)
jointId := dbox2d.CreateDistanceJoint(worldId, &def)
fmt.Println(jointId.IsNull())
}
Output: false
func CreateFilterJoint ¶ added in v0.3.0
func CreateFilterJoint(worldId WorldId, def *FilterJointDef) JointId
CreateFilterJoint creates a filter joint. The joint only disables collision between the two bodies. The definition must come from DefaultFilterJointDef.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, groundId, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
// The box falls through the ground; the filter joint disables the
// collision between the two bodies.
def := dbox2d.DefaultFilterJointDef()
def.BodyIdA = groundId
def.BodyIdB = boxId
jointId := dbox2d.CreateFilterJoint(worldId, &def)
fmt.Println(jointId.IsNull())
}
Output: false
func CreateMotorJoint ¶ added in v0.3.0
func CreateMotorJoint(worldId WorldId, def *MotorJointDef) JointId
CreateMotorJoint creates a motor joint. The definition must come from DefaultMotorJointDef.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, groundId, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
// The motor drives the box toward an offset of (1, 2) from the ground.
def := dbox2d.DefaultMotorJointDef()
def.BodyIdA = groundId
def.BodyIdB = boxId
def.LinearOffset = dbox2d.Vec2{X: dbox2d.QOne(), Y: dbox2d.QFromInt(2)}
def.MaxForce = dbox2d.QFromInt(100)
jointId := dbox2d.CreateMotorJoint(worldId, &def)
fmt.Println(jointId.IsNull())
}
Output: false
func CreateMouseJoint ¶ added in v0.3.0
func CreateMouseJoint(worldId WorldId, def *MouseJointDef) JointId
CreateMouseJoint creates a mouse joint. The definition must come from DefaultMouseJointDef.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, groundId, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
// The target is a world point; the joint pulls the box toward it.
def := dbox2d.DefaultMouseJointDef()
def.BodyIdA = groundId
def.BodyIdB = boxId
def.Target = dbox2d.Vec2{X: dbox2d.QOne(), Y: dbox2d.QFromInt(2)}
def.MaxForce = dbox2d.QFromInt(500)
jointId := dbox2d.CreateMouseJoint(worldId, &def)
fmt.Println(jointId.IsNull())
}
Output: false
func CreatePrismaticJoint ¶ added in v0.3.0
func CreatePrismaticJoint(worldId WorldId, def *PrismaticJointDef) JointId
CreatePrismaticJoint creates a prismatic joint. The definition must come from DefaultPrismaticJointDef.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, groundId, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
// The box slides along the vertical axis of the ground, between
// zero and three units.
def := dbox2d.DefaultPrismaticJointDef()
def.BodyIdA = groundId
def.BodyIdB = boxId
def.LocalAxisA = dbox2d.Vec2{Y: dbox2d.QOne()}
def.EnableLimit = true
def.LowerTranslation = dbox2d.QZero()
def.UpperTranslation = dbox2d.QFromInt(3)
jointId := dbox2d.CreatePrismaticJoint(worldId, &def)
fmt.Println(jointId.IsNull())
}
Output: false
func CreateRevoluteJoint ¶ added in v0.3.0
func CreateRevoluteJoint(worldId WorldId, def *RevoluteJointDef) JointId
CreateRevoluteJoint creates a revolute joint. The definition must come from DefaultRevoluteJointDef. The angles are in turns.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, groundId, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
// A pendulum: the pivot is the ground origin, two units below the
// box center. The angles are in turns; a quarter turn is 0.25.
def := dbox2d.DefaultRevoluteJointDef()
def.BodyIdA = groundId
def.BodyIdB = boxId
def.LocalAnchorB = dbox2d.Vec2{Y: dbox2d.QFromInt(-2)}
def.EnableLimit = true
def.LowerAngle = dbox2d.QMustParse("-0.25")
def.UpperAngle = dbox2d.QMustParse("0.25")
jointId := dbox2d.CreateRevoluteJoint(worldId, &def)
fmt.Println(jointId.IsNull())
}
Output: false
func CreateWeldJoint ¶ added in v0.3.0
func CreateWeldJoint(worldId WorldId, def *WeldJointDef) JointId
CreateWeldJoint creates a weld joint. The definition must come from DefaultWeldJointDef.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, groundId, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
// A weld with a soft angular spring holds the box in place.
def := dbox2d.DefaultWeldJointDef()
def.BodyIdA = groundId
def.BodyIdB = boxId
def.LocalAnchorB = dbox2d.Vec2{Y: dbox2d.QFromInt(-2)}
def.AngularHertz = dbox2d.QFromInt(2)
def.AngularDampingRatio = dbox2d.QHalf()
jointId := dbox2d.CreateWeldJoint(worldId, &def)
fmt.Println(jointId.IsNull())
}
Output: false
func CreateWheelJoint ¶ added in v0.3.0
func CreateWheelJoint(worldId WorldId, def *WheelJointDef) JointId
CreateWheelJoint creates a wheel joint. The definition must come from DefaultWheelJointDef.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, groundId, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
// A suspension: the box rides the vertical axis on a spring and its
// motor spins it at one turn per second.
def := dbox2d.DefaultWheelJointDef()
def.BodyIdA = groundId
def.BodyIdB = boxId
def.EnableMotor = true
def.MotorSpeed = dbox2d.QOne()
def.MaxMotorTorque = dbox2d.QFromInt(10)
jointId := dbox2d.CreateWheelJoint(worldId, &def)
fmt.Println(jointId.IsNull())
}
Output: false
func (JointId) EnableLimit ¶ added in v0.4.0
EnableLimit enables or disables the joint limit.
func (JointId) EnableMotor ¶ added in v0.4.0
EnableMotor enables or disables the joint motor.
func (JointId) EnableSpring ¶ added in v0.4.0
EnableSpring enables or disables the spring on a distance, revolute, prismatic, or wheel joint.
func (JointId) GetAngle ¶ added in v0.4.0
GetAngle reports the revolute joint angle relative to its reference angle, in turns.
func (JointId) GetAngularDampingRatio ¶ added in v0.4.0
GetAngularDampingRatio reports the weld joint angular damping ratio (b2WeldJoint_GetAngularDampingRatio).
func (JointId) GetAngularHertz ¶ added in v0.4.0
GetAngularHertz reports the weld joint angular frequency (b2WeldJoint_GetAngularHertz).
func (JointId) GetAngularOffset ¶ added in v0.4.0
GetAngularOffset reports the motor joint's angular offset in turns (b2MotorJoint_GetAngularOffset).
func (JointId) GetAngularSeparation ¶ added in v0.4.0
GetAngularSeparation reports angular separation in turns (b2Joint_GetAngularSeparation).
func (JointId) GetBodyA ¶ added in v0.4.0
GetBodyA reports the first attached body (b2Joint_GetBodyA).
func (JointId) GetBodyB ¶ added in v0.4.0
GetBodyB reports the second attached body (b2Joint_GetBodyB).
func (JointId) GetCollideConnected ¶ added in v0.4.0
GetCollideConnected reports whether the attached bodies collide (b2Joint_GetCollideConnected).
func (JointId) GetConstraintForce ¶ added in v0.4.0
GetConstraintForce reports the constraint force from the last step (b2Joint_GetConstraintForce).
func (JointId) GetConstraintTorque ¶ added in v0.4.0
GetConstraintTorque reports the constraint torque from the last step (b2Joint_GetConstraintTorque).
func (JointId) GetConstraintTuning ¶ added in v0.4.0
GetConstraintTuning reports the joint constraint tuning (b2Joint_GetConstraintTuning).
func (JointId) GetCorrectionFactor ¶ added in v0.4.0
GetCorrectionFactor reports the motor joint's correction factor (b2MotorJoint_GetCorrectionFactor).
func (JointId) GetCurrentLength ¶ added in v0.4.0
GetCurrentLength reports the distance between the current world anchors.
func (JointId) GetLinearDampingRatio ¶ added in v0.4.0
GetLinearDampingRatio reports the weld joint linear damping ratio (b2WeldJoint_GetLinearDampingRatio).
func (JointId) GetLinearHertz ¶ added in v0.4.0
GetLinearHertz reports the weld joint linear frequency (b2WeldJoint_GetLinearHertz).
func (JointId) GetLinearOffset ¶ added in v0.4.0
GetLinearOffset reports the motor joint's linear offset (b2MotorJoint_GetLinearOffset).
func (JointId) GetLinearSeparation ¶ added in v0.4.0
GetLinearSeparation reports the joint's linear separation (b2Joint_GetLinearSeparation).
func (JointId) GetLocalAnchorA ¶ added in v0.4.0
GetLocalAnchorA reports the local anchor on body A (b2Joint_GetLocalAnchorA).
func (JointId) GetLocalAnchorB ¶ added in v0.4.0
GetLocalAnchorB reports the local anchor on body B (b2Joint_GetLocalAnchorB).
func (JointId) GetLocalAxisA ¶ added in v0.4.0
GetLocalAxisA reports the local axis on an applicable joint (b2Joint_GetLocalAxisA).
func (JointId) GetLowerLimit ¶ added in v0.4.0
GetLowerLimit reports the lower angular or linear joint limit.
func (JointId) GetMaxForce ¶ added in v0.4.0
GetMaxForce reports the maximum force of a motor or mouse joint (b2MotorJoint_GetMaxForce, b2MouseJoint_GetMaxForce).
func (JointId) GetMaxLength ¶ added in v0.4.0
GetMaxLength reports the upper distance limit.
func (JointId) GetMaxMotorForce ¶ added in v0.4.0
GetMaxMotorForce reports the maximum distance or prismatic motor force.
func (JointId) GetMaxMotorTorque ¶ added in v0.4.0
GetMaxMotorTorque reports the maximum revolute or wheel motor torque.
func (JointId) GetMaxTorque ¶ added in v0.4.0
GetMaxTorque reports the motor joint's maximum torque (b2MotorJoint_GetMaxTorque).
func (JointId) GetMinLength ¶ added in v0.4.0
GetMinLength reports the lower distance limit.
func (JointId) GetMotorForce ¶ added in v0.4.0
GetMotorForce reports the last distance or prismatic motor force.
func (JointId) GetMotorSpeed ¶ added in v0.4.0
GetMotorSpeed reports the joint motor speed.
func (JointId) GetMotorTorque ¶ added in v0.4.0
GetMotorTorque reports the last revolute or wheel motor torque.
func (JointId) GetReferenceAngle ¶ added in v0.4.0
GetReferenceAngle reports the reference angle in turns (b2Joint_GetReferenceAngle).
func (JointId) GetSpringDampingRatio ¶ added in v0.4.0
GetSpringDampingRatio reports the spring damping ratio.
func (JointId) GetSpringHertz ¶ added in v0.4.0
GetSpringHertz reports the spring frequency.
func (JointId) GetTarget ¶ added in v0.4.0
GetTarget reports the mouse joint target (b2MouseJoint_GetTarget).
func (JointId) GetTargetAngle ¶ added in v0.4.0
GetTargetAngle reports the revolute spring target angle in turns.
func (JointId) GetTargetTranslation ¶ added in v0.4.0
GetTargetTranslation reports the prismatic spring target translation.
func (JointId) GetTranslation ¶ added in v0.4.0
GetTranslation reports the current translation along the prismatic axis.
func (JointId) GetUpperLimit ¶ added in v0.4.0
GetUpperLimit reports the upper angular or linear joint limit.
func (JointId) GetUserData ¶ added in v0.4.0
GetUserData reports the data attached to the joint (b2Joint_GetUserData).
func (JointId) GetWorld ¶ added in v0.4.0
GetWorld reports the world containing the joint (b2Joint_GetWorld).
func (JointId) IsLimitEnabled ¶ added in v0.4.0
IsLimitEnabled reports whether the joint limit is enabled.
func (JointId) IsMotorEnabled ¶ added in v0.4.0
IsMotorEnabled reports whether the joint motor is enabled.
func (JointId) IsSpringEnabled ¶ added in v0.4.0
IsSpringEnabled reports whether the spring is enabled.
func (JointId) IsValid ¶ added in v0.4.0
IsValid reports whether the id references a live joint (b2Joint_IsValid).
func (JointId) SetAngularDampingRatio ¶ added in v0.4.0
SetAngularDampingRatio changes the weld joint angular damping ratio (b2WeldJoint_SetAngularDampingRatio).
func (JointId) SetAngularHertz ¶ added in v0.4.0
SetAngularHertz changes the weld joint angular frequency (b2WeldJoint_SetAngularHertz).
func (JointId) SetAngularOffset ¶ added in v0.4.0
SetAngularOffset changes the motor joint's angular offset in turns (b2MotorJoint_SetAngularOffset).
func (JointId) SetCollideConnected ¶ added in v0.4.0
SetCollideConnected changes whether the attached bodies collide (b2Joint_SetCollideConnected).
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, groundId, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
def := dbox2d.DefaultDistanceJointDef()
def.BodyIdA = groundId
def.BodyIdB = boxId
def.Length = dbox2d.QFromInt(2)
jointId := dbox2d.CreateDistanceJoint(worldId, &def)
jointId.SetCollideConnected(true)
fmt.Println(jointId.GetCollideConnected())
}
Output: true
func (JointId) SetConstraintTuning ¶ added in v0.4.0
SetConstraintTuning changes the joint constraint tuning (b2Joint_SetConstraintTuning).
func (JointId) SetCorrectionFactor ¶ added in v0.4.0
SetCorrectionFactor changes the motor joint's correction factor (b2MotorJoint_SetCorrectionFactor).
func (JointId) SetLengthRange ¶ added in v0.4.0
SetLengthRange changes the distance joint limits.
func (JointId) SetLinearDampingRatio ¶ added in v0.4.0
SetLinearDampingRatio changes the weld joint linear damping ratio (b2WeldJoint_SetLinearDampingRatio).
func (JointId) SetLinearHertz ¶ added in v0.4.0
SetLinearHertz changes the weld joint linear frequency (b2WeldJoint_SetLinearHertz).
func (JointId) SetLinearOffset ¶ added in v0.4.0
SetLinearOffset changes the motor joint's linear offset (b2MotorJoint_SetLinearOffset).
func (JointId) SetLocalAnchorA ¶ added in v0.4.0
SetLocalAnchorA changes the local anchor on body A (b2Joint_SetLocalAnchorA).
func (JointId) SetLocalAnchorB ¶ added in v0.4.0
SetLocalAnchorB changes the local anchor on body B (b2Joint_SetLocalAnchorB).
func (JointId) SetLocalAxisA ¶ added in v0.4.0
SetLocalAxisA changes the local axis on an applicable joint (b2Joint_SetLocalAxisA).
func (JointId) SetMaxForce ¶ added in v0.4.0
SetMaxForce changes the maximum force of a motor or mouse joint (b2MotorJoint_SetMaxForce, b2MouseJoint_SetMaxForce).
func (JointId) SetMaxMotorForce ¶ added in v0.4.0
SetMaxMotorForce changes the maximum distance or prismatic motor force.
func (JointId) SetMaxMotorTorque ¶ added in v0.4.0
SetMaxMotorTorque changes the maximum revolute or wheel motor torque.
func (JointId) SetMaxTorque ¶ added in v0.4.0
SetMaxTorque changes the motor joint's maximum torque (b2MotorJoint_SetMaxTorque).
func (JointId) SetMotorSpeed ¶ added in v0.4.0
SetMotorSpeed changes the joint motor speed. Revolute and wheel values are turns per second (D-004); distance and prismatic values are metres/second.
func (JointId) SetReferenceAngle ¶ added in v0.4.0
SetReferenceAngle changes the reference angle in turns (b2Joint_SetReferenceAngle).
func (JointId) SetSpringDampingRatio ¶ added in v0.4.0
SetSpringDampingRatio changes the spring damping ratio.
func (JointId) SetSpringHertz ¶ added in v0.4.0
SetSpringHertz changes the spring frequency.
func (JointId) SetTarget ¶ added in v0.4.0
SetTarget changes the mouse joint target (b2MouseJoint_SetTarget).
func (JointId) SetTargetAngle ¶ added in v0.4.0
SetTargetAngle changes the revolute spring target angle in turns.
func (JointId) SetTargetTranslation ¶ added in v0.4.0
SetTargetTranslation changes the prismatic spring target translation.
func (JointId) SetUserData ¶ added in v0.4.0
SetUserData attaches application data to the joint (b2Joint_SetUserData).
func (JointId) WakeBodies ¶ added in v0.4.0
func (jointId JointId) WakeBodies()
WakeBodies wakes both bodies attached to the joint (b2Joint_WakeBodies).
type JointType ¶ added in v0.3.0
type JointType int
JointType selects the joint of a joint definition.
type Manifold ¶
type Manifold struct {
// Normal is the unit normal in world space. It points from A to B.
Normal Vec2
// RollingImpulse is the angular impulse of the rolling resistance.
RollingImpulse Q
// Points holds the contact points. Two are possible in 2D.
Points [2]ManifoldPoint
// PointCount is zero, one or two.
PointCount int
}
Manifold describes the contact points between two colliding shapes. The solver uses speculative collision, so a point may still be separated.
func CollideCapsuleAndCircle ¶ added in v0.2.0
func CollideCapsuleAndCircle(capsuleA *Capsule, xfA Transform, circleB *Circle, xfB Transform) Manifold
CollideCapsuleAndCircle computes the contact manifold of a capsule and a circle. It corresponds to b2CollideCapsuleAndCircle in src/manifold.c.
func CollideCapsules ¶ added in v0.2.0
CollideCapsules computes the contact manifold of two capsules. It follows Ericson 5.1.9 with clipping for a second contact point and corresponds to b2CollideCapsules in src/manifold.c.
func CollideChainSegmentAndCapsule ¶ added in v0.3.0
func CollideChainSegmentAndCapsule(segmentA *ChainSegment, xfA Transform, capsuleB *Capsule, xfB Transform, cache *SimplexCache) Manifold
CollideChainSegmentAndCapsule treats the capsule as a rounded polygon and defers to the polygon routine. It corresponds to b2CollideChainSegmentAndCapsule in src/manifold.c.
func CollideChainSegmentAndCircle ¶ added in v0.2.0
func CollideChainSegmentAndCircle(segmentA *ChainSegment, xfA Transform, circleB *Circle, xfB Transform) Manifold
CollideChainSegmentAndCircle computes the contact manifold of a one-sided chain segment and a circle. It corresponds to b2CollideChainSegmentAndCircle in src/manifold.c.
func CollideChainSegmentAndPolygon ¶ added in v0.3.0
func CollideChainSegmentAndPolygon(segmentA *ChainSegment, xfA Transform, polygonB *Polygon, xfB Transform, cache *SimplexCache) Manifold
CollideChainSegmentAndPolygon computes the manifold between a chain segment and a polygon. The cache warm starts the distance solver between calls. It corresponds to b2CollideChainSegmentAndPolygon in src/manifold.c.
func CollideCircles ¶ added in v0.2.0
CollideCircles computes the contact manifold of two circles. It corresponds to b2CollideCircles in src/manifold.c.
func CollidePolygonAndCapsule ¶ added in v0.2.0
func CollidePolygonAndCapsule(polygonA *Polygon, xfA Transform, capsuleB *Capsule, xfB Transform) Manifold
CollidePolygonAndCapsule computes the contact manifold of a polygon and a capsule. It corresponds to b2CollidePolygonAndCapsule in src/manifold.c.
func CollidePolygonAndCircle ¶ added in v0.2.0
func CollidePolygonAndCircle(polygonA *Polygon, xfA Transform, circleB *Circle, xfB Transform) Manifold
CollidePolygonAndCircle computes the contact manifold of a polygon and a circle. It corresponds to b2CollidePolygonAndCircle in src/manifold.c.
func CollidePolygons ¶ added in v0.2.0
CollidePolygons computes the contact manifold of two rounded polygons with the separating axis test and edge clipping. It corresponds to b2CollidePolygons in src/manifold.c.
func CollideSegmentAndCapsule ¶ added in v0.2.0
func CollideSegmentAndCapsule(segmentA *Segment, xfA Transform, capsuleB *Capsule, xfB Transform) Manifold
CollideSegmentAndCapsule computes the contact manifold of a segment and a capsule. It corresponds to b2CollideSegmentAndCapsule in src/manifold.c.
func CollideSegmentAndCircle ¶ added in v0.2.0
func CollideSegmentAndCircle(segmentA *Segment, xfA Transform, circleB *Circle, xfB Transform) Manifold
CollideSegmentAndCircle computes the contact manifold of a segment and a circle. It corresponds to b2CollideSegmentAndCircle in src/manifold.c.
func CollideSegmentAndPolygon ¶ added in v0.2.0
func CollideSegmentAndPolygon(segmentA *Segment, xfA Transform, polygonB *Polygon, xfB Transform) Manifold
CollideSegmentAndPolygon computes the contact manifold of a segment and a polygon. It corresponds to b2CollideSegmentAndPolygon in src/manifold.c.
type ManifoldPoint ¶
type ManifoldPoint struct {
// Point is the contact point in world space. Use it for debugging only,
// because it loses precision far from the origin.
Point Vec2
// AnchorA is the contact point relative to the origin of shape A, in
// world space. Inside the solver it is relative to the center of mass.
AnchorA Vec2
// AnchorB is the contact point relative to the origin of shape B, in
// world space. Inside the solver it is relative to the center of mass.
AnchorB Vec2
// Separation is negative when the shapes penetrate.
Separation Q
// NormalImpulse is the impulse along the manifold normal.
NormalImpulse Q
// TangentImpulse is the friction impulse.
TangentImpulse Q
// TotalNormalImpulse accumulates over the substeps and the restitution
// pass. It tells a speculative point that acted from one that did not.
TotalNormalImpulse Q
// NormalVelocity is the relative normal velocity before the solve. It
// feeds the hit events. A negative value means the shapes approach.
NormalVelocity Q
// Id identifies the contact point between the two shapes.
Id uint16
// Persisted reports whether the point existed in the previous step.
Persisted bool
}
ManifoldPoint is one contact point of a contact manifold. The solver uses speculative collision, so a point may still be separated.
type MassData ¶
type MassData struct {
// Mass is the mass of the shape, usually in kilograms.
Mass Q
// Center is the centroid of the shape, relative to the shape origin.
Center Vec2
// RotationalInertia is measured about the local origin.
RotationalInertia Q
}
MassData holds the mass properties of a shape.
func ComputeCapsuleMass ¶
ComputeCapsuleMass returns the mass properties of a capsule.
func ComputeCircleMass ¶
ComputeCircleMass returns the mass properties of a circle.
func ComputePolygonMass ¶
ComputePolygonMass returns the mass properties of a convex polygon. It approximates a rounded polygon by pushing the vertices outward.
type Mat22 ¶
type Mat22 struct {
Cx, Cy Vec2
}
Mat22 is a 2-by-2 matrix, stored as its columns.
func GetInverse22 ¶
GetInverse22 returns the inverse of m. A singular matrix returns the zero matrix.
Each entry divides by the determinant, because a fixed-point reciprocal loses the precision that the division keeps. See DIVERGENCES.md.
type MotorJointDef ¶ added in v0.3.0
type MotorJointDef struct {
// The first attached body.
BodyIdA BodyId
// The second attached body.
BodyIdB BodyId
// Position of body B minus the position of body A, in the frame of
// body A, in meters.
LinearOffset Vec2
// The angle of body B minus the angle of body A, in turns.
AngularOffset Q
// The maximum motor force in newtons.
MaxForce Q
// The maximum motor torque in newton-meters.
MaxTorque Q
// Position correction factor in the range [0, 1].
CorrectionFactor Q
// Set this flag to true if the attached bodies should collide.
CollideConnected bool
// Application data attached to the joint.
UserData any
// contains filtered or unexported fields
}
MotorJointDef configures a motor joint: it drives the relative transform of two bodies toward an offset. Initialize it with DefaultMotorJointDef.
func DefaultMotorJointDef ¶ added in v0.3.0
func DefaultMotorJointDef() MotorJointDef
DefaultMotorJointDef returns the default motor joint definition.
type MouseJointDef ¶ added in v0.3.0
type MouseJointDef struct {
// The first attached body. It is unused here, but it plays a role in
// the solver order.
BodyIdA BodyId
// The second attached body.
BodyIdB BodyId
// The initial target point in world space.
Target Vec2
// Stiffness in cycles per second.
Hertz Q
// Damping ratio, non-dimensional.
DampingRatio Q
// Maximum force, usually in newtons.
MaxForce Q
// Set this flag to true if the attached bodies should collide.
CollideConnected bool
// Application data attached to the joint.
UserData any
// contains filtered or unexported fields
}
MouseJointDef configures a mouse joint: it drags a point on body B toward a world target with a spring. Body A is a ground reference and gets no reaction. Initialize it with DefaultMouseJointDef.
func DefaultMouseJointDef ¶ added in v0.3.0
func DefaultMouseJointDef() MouseJointDef
DefaultMouseJointDef returns the default mouse joint definition.
type OverlapResultFcn ¶ added in v0.3.0
OverlapResultFcn receives each shape that an overlap query finds. Return false to stop the walk of the current tree; the query goes on with the next body type, as the reference does. It corresponds to b2OverlapResultFcn in include/box2d/types.h; the closure carries the context.
type PlaneResult ¶ added in v0.4.0
PlaneResult is the collision plane and contact point for a mover collision.
func CollideMoverAndCapsule ¶ added in v0.4.0
func CollideMoverAndCapsule(mover *Capsule, shape *Capsule) PlaneResult
CollideMoverAndCapsule ports b2CollideMoverAndCapsule.
func CollideMoverAndCircle ¶ added in v0.4.0
func CollideMoverAndCircle(mover *Capsule, shape *Circle) PlaneResult
CollideMoverAndCircle ports b2CollideMoverAndCircle.
func CollideMoverAndPolygon ¶ added in v0.4.0
func CollideMoverAndPolygon(mover *Capsule, shape *Polygon) PlaneResult
CollideMoverAndPolygon ports b2CollideMoverAndPolygon.
func CollideMoverAndSegment ¶ added in v0.4.0
func CollideMoverAndSegment(mover *Capsule, shape *Segment) PlaneResult
CollideMoverAndSegment ports b2CollideMoverAndSegment.
type PlaneResultFcn ¶ added in v0.4.0
type PlaneResultFcn func(shapeId ShapeId, result *PlaneResult) bool
PlaneResultFcn receives each collision plane a mover query finds. Return true to keep gathering planes. It corresponds to b2PlaneResultFcn in include/box2d/types.h; the closure carries the context.
type PlaneSolverResult ¶ added in v0.4.0
PlaneSolverResult is the translation and iteration count from SolvePlanes.
func SolvePlanes ¶ added in v0.4.0
func SolvePlanes(targetDelta Vec2, planes []CollisionPlane) PlaneSolverResult
SolvePlanes ports b2SolvePlanes. Pass Huge as PushLimit for a rigid plane.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
func main() {
// A push limit of dbox2d.Huge (the engine's rigid-contact bound) makes
// the plane act as an unyielding wall: the tangential component of the
// move survives untouched, and the normal component is pushed back
// to just outside the plane, leaving a linear-slop margin.
planes := []dbox2d.CollisionPlane{{
Plane: dbox2d.Plane{Normal: dbox2d.Vec2{Y: dbox2d.QOne()}},
PushLimit: dbox2d.Huge,
}}
result := dbox2d.SolvePlanes(dbox2d.Vec2{X: dbox2d.QOne(), Y: dbox2d.QOne().Neg()}, planes)
fmt.Println(result.Translation.X)
fmt.Println(result.Translation.Y.Less(dbox2d.LinearSlop().Neg().Sub(dbox2d.LinearSlop())))
}
Output: 1 false
type Polygon ¶
type Polygon struct {
// Vertices holds the corners. Only the first Count entries are valid.
Vertices [MaxPolygonVertices]Vec2
// Normals holds the outward normal of each side.
Normals [MaxPolygonVertices]Vec2
// Centroid is the area centroid of the polygon.
Centroid Vec2
// Radius is the external radius of a rounded polygon.
Radius Q
// Count is the number of vertices.
Count int
}
Polygon is a solid convex polygon. The interior lies to the left of every edge. Build one with MakePolygon or MakeBox; never fill the fields by hand.
func MakeBox ¶
MakeBox returns a rectangle polygon of the given half-extents, without a hull. It panics on a half-extent that is not positive.
func MakeOffsetBox ¶
MakeOffsetBox returns a rectangle polygon placed at a center and a rotation, without a hull.
func MakeOffsetPolygon ¶
MakeOffsetPolygon returns a convex polygon built from a hull and placed at a position and a rotation.
func MakeOffsetRoundedBox ¶
MakeOffsetRoundedBox returns a rectangle polygon with rounded corners, placed at a center and a rotation, without a hull.
func MakeOffsetRoundedPolygon ¶
MakeOffsetRoundedPolygon returns a convex polygon built from a hull, placed at a position and a rotation, with rounded corners of the given radius.
func MakePolygon ¶
MakePolygon returns a convex polygon built from a hull. The radius rounds the corners. It panics on a hull that ValidateHull rejects.
func MakeRoundedBox ¶
MakeRoundedBox returns a rectangle polygon with rounded corners, without a hull.
func MakeSquare ¶
MakeSquare returns a square polygon of the given half-width, without a hull.
func TransformPolygon ¶
TransformPolygon returns the polygon moved by a transform. It moves a shape from one body to another.
type PreSolveFcn ¶ added in v0.4.0
PreSolveFcn inspects a contact manifold before the solver runs. It corresponds to b2PreSolveFcn; return false to disable the contact this step. With several workers it runs on worker goroutines while the step mutates the world: it must not call the world API or query it, must not panic, and must be safe to call concurrently.
type PrismaticJointDef ¶ added in v0.3.0
type PrismaticJointDef struct {
// The first attached body.
BodyIdA BodyId
// The second attached body.
BodyIdB BodyId
// The local anchor point relative to the origin of body A.
LocalAnchorA Vec2
// The local anchor point relative to the origin of body B.
LocalAnchorB Vec2
// The local translation unit axis in body A.
LocalAxisA Vec2
// The constrained angle between the bodies: angle of B minus angle of
// A, in turns.
ReferenceAngle Q
// The target translation for the joint in meters. The spring-damper
// pulls toward this translation.
TargetTranslation Q
// Enable a linear spring along the prismatic joint axis.
EnableSpring bool
// The spring stiffness in cycles per second.
Hertz Q
// The spring damping ratio, non-dimensional.
DampingRatio Q
// Enable and disable the joint limit.
EnableLimit bool
// The lower translation limit.
LowerTranslation Q
// The upper translation limit.
UpperTranslation Q
// Enable and disable the joint motor.
EnableMotor bool
// The maximum motor force, usually in newtons.
MaxMotorForce Q
// The desired motor speed, usually in meters per second.
MotorSpeed Q
// Set this flag to true if the attached bodies should collide.
CollideConnected bool
// Application data attached to the joint.
UserData any
// contains filtered or unexported fields
}
PrismaticJointDef configures a prismatic joint: body B translates along an axis fixed in body A, with no relative rotation. Initialize it with DefaultPrismaticJointDef.
func DefaultPrismaticJointDef ¶ added in v0.3.0
func DefaultPrismaticJointDef() PrismaticJointDef
DefaultPrismaticJointDef returns the default prismatic joint definition.
type Profile ¶ added in v0.5.0
type Profile struct {
Step float64
Pairs float64
Collide float64
Solve float64
MergeIslands float64
PrepareStages float64
SolveConstraints float64
PrepareConstraints float64
IntegrateVelocities float64
WarmStart float64
SolveImpulses float64
IntegratePositions float64
RelaxImpulses float64
ApplyRestitution float64
StoreImpulses float64
SplitIslands float64
Transforms float64
HitEvents float64
Refit float64
Bullets float64
SleepIslands float64
Sensors float64
}
Profile holds the wall-clock cost of the last Step, in milliseconds.
type Q ¶
type Q struct {
// contains filtered or unexported fields
}
Q is a float32 scalar. Only the constructors make one.
func AABBMargin ¶
func AABBMargin() Q
AABBMargin fattens the bounds in the dynamic tree, in meters. A proxy that moves less than the margin triggers no tree adjustment.
Changing it has a significant effect on performance.
func ComputeAngularVelocity ¶
ComputeAngularVelocity returns the angular velocity, in turns per second, that rotates q1 into q2 over one step. invH is the inverse time step.
func JointConstraintDampingRatio ¶
func JointConstraintDampingRatio() Q
JointConstraintDampingRatio is the default damping of a joint constraint.
func JointConstraintHertz ¶
func JointConstraintHertz() Q
JointConstraintHertz is the default stiffness of a joint constraint.
func LinearSlop ¶
func LinearSlop() Q
LinearSlop is the collision and constraint tolerance in meters. It is numerically significant and visually insignificant.
Changing it has a significant effect on stability.
func MaxRotation ¶
func MaxRotation() Q
MaxRotation is the largest rotation of a body in one time step, in turns. The limit prevents numerical problems.
Raising it to 0.25 turns or more breaks continuous collision.
func Pi ¶
func Pi() Q
Pi is the ratio of a circumference to its diameter. An angle is a turn in this package; Pi serves the formulas that the reference writes in radians.
func PlaneSeparation ¶
PlaneSeparation returns the signed distance of a point from a plane.
func QFromFloat64 ¶ added in v0.6.0
QFromFloat64 converts a presentation value, such as a camera value, to a scalar. It must never be used by simulation code.
func QFromRatio ¶ added in v0.5.0
QFromRatio returns num/den, rounded to float32.
func QMaxValue ¶ added in v0.5.0
func QMaxValue() Q
QMaxValue returns the largest finite float32 scalar.
func QMinValue ¶ added in v0.5.0
func QMinValue() Q
QMinValue returns the smallest finite float32 scalar.
func QMustParse ¶ added in v0.5.0
QMustParse returns the decimal literal s as a scalar. It panics when s is not a decimal number.
func RelativeAngle ¶
RelativeAngle returns the angle of b relative to a, in turns.
func RotGetAngle ¶
RotGetAngle returns the angle of q in turns, in the range [-0.5, 0.5].
func SpeculativeDistance ¶
func SpeculativeDistance() Q
SpeculativeDistance is the range of limited speculative collision, in meters. It reduces jitter.
Changing it has a significant effect on performance and stability.
func SpringDamper ¶
SpringDamper simulates a one-dimensional mass-spring-damper and returns the new velocity. The caller then computes the new position:
position += timeStep * newVelocity
It drives towards a zero position. Implicit integration makes the solution stable and free of transcendental functions.
func TimeToSleep ¶
func TimeToSleep() Q
TimeToSleep is how long a body must stay still before it sleeps, in seconds.
func UnwindAngle ¶
UnwindAngle reduces an angle in turns to the range [-0.5, 0.5]. One turn is one unit here, so the reduction is exact and needs no remainder of pi.
type QueryFilter ¶
type QueryFilter struct {
// The collision category bits of this query. Normally one bit.
CategoryBits uint64
// The shape categories that this query accepts for collision.
MaskBits uint64
}
QueryFilter controls collision between a query and the shapes it visits.
func DefaultQueryFilter ¶
func DefaultQueryFilter() QueryFilter
DefaultQueryFilter returns the default query filter: category 1, every mask bit set.
type RayCastInput ¶
type RayCastInput struct {
// Origin is the start point of the ray.
Origin Vec2
// Translation is the displacement of the ray.
Translation Vec2
// MaxFraction limits the translation to consider. It is usually one.
MaxFraction Q
}
RayCastInput is the input of a ray cast in the local frame of a shape.
type RayResult ¶ added in v0.3.0
type RayResult struct {
ShapeId ShapeId
Point Vec2
Normal Vec2
Fraction Q
NodeVisits int
LeafVisits int
Hit bool
}
RayResult is the answer of CastRayClosest. On an initial overlap the fraction and the normal are zero and the point is an arbitrary point of the overlap region. It corresponds to b2RayResult in include/box2d/types.h.
type RestitutionCallback ¶ added in v0.4.0
type RestitutionCallback func(restitutionA Q, userMaterialIdA int, restitutionB Q, userMaterialIdB int) Q
RestitutionCallback mixes the restitution values of two shapes.
type RevoluteJointDef ¶ added in v0.3.0
type RevoluteJointDef struct {
// The first attached body.
BodyIdA BodyId
// The second attached body.
BodyIdB BodyId
// The local anchor point relative to the origin of body A.
LocalAnchorA Vec2
// The local anchor point relative to the origin of body B.
LocalAnchorB Vec2
// The angle of body B minus the angle of body A in the reference
// state, in turns. It is clamped to [-0.5, 0.5] turns.
ReferenceAngle Q
// The target angle for the joint in turns. The spring-damper pulls
// toward this angle.
TargetAngle Q
// Enable a rotational spring on the revolute hinge axis.
EnableSpring bool
// The spring stiffness in cycles per second.
Hertz Q
// The spring damping ratio, non-dimensional.
DampingRatio Q
// Enable and disable the joint limit.
EnableLimit bool
// The lower angle for the joint limit in turns. Must be greater than
// -0.495 turns.
LowerAngle Q
// The upper angle for the joint limit in turns. Must be less than
// 0.495 turns.
UpperAngle Q
// Enable and disable the joint motor.
EnableMotor bool
// The maximum motor torque, usually in newton-meters.
MaxMotorTorque Q
// The desired motor speed in turns per second.
MotorSpeed Q
// DrawSize scales the debug draw of the joint.
DrawSize Q
// Set this flag to true if the attached bodies should collide.
CollideConnected bool
// Application data attached to the joint.
UserData any
// contains filtered or unexported fields
}
RevoluteJointDef configures a revolute joint: a shared anchor point with free relative rotation. Initialize it with DefaultRevoluteJointDef.
func DefaultRevoluteJointDef ¶ added in v0.3.0
func DefaultRevoluteJointDef() RevoluteJointDef
DefaultRevoluteJointDef returns the default revolute joint definition.
type Rot ¶
type Rot struct {
Sin, Cos Q
}
Rot is a 2D rotation, stored as a sine and cosine pair.
func ComputeRotationBetweenUnitVectors ¶
ComputeRotationBetweenUnitVectors returns the rotation that carries the unit vector v1 onto the unit vector v2. It panics when either vector is not a unit vector, because the result would be a rotation of the wrong scale.
func IntegrateRotation ¶
IntegrateRotation advances q1 by the angular displacement deltaAngle, in turns, and renormalizes. The first-order step below needs radians, so the displacement scales by one turn.
func InvMulRot ¶
InvMulRot returns the rotation transpose(q) * r.
[ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] s(q - r) = qc * rs - qs * rc c(q - r) = qc * rc + qs * rs
func MulRot ¶
MulRot returns the rotation q * r.
[qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] s(q + r) = qs * rc + qc * rs c(q + r) = qc * rc - qs * rs
func NormalizeRot ¶
NormalizeRot rescales q to unit length.
A zero q returns a zero rotation, as the reference does. The zero rotation is invalid, so IsValidRotation reports the bad state instead of hiding it behind the identity.
type SegmentDistanceResult ¶ added in v0.2.0
type SegmentDistanceResult struct {
// Closest1 is the closest point on the first segment.
Closest1 Vec2
// Closest2 is the closest point on the second segment.
Closest2 Vec2
// Fraction1 is the barycentric coordinate on the first segment.
Fraction1 Q
// Fraction2 is the barycentric coordinate on the second segment.
Fraction2 Q
// DistanceSquared is the squared distance between the closest points.
DistanceSquared Q
}
SegmentDistanceResult is the output of SegmentDistance. It corresponds to b2SegmentDistanceResult in include/box2d/collision.h.
func SegmentDistance ¶ added in v0.2.0
func SegmentDistance(p1, q1, p2, q2 Vec2) SegmentDistanceResult
SegmentDistance computes the closest points of two line segments, clamping at the end points when needed. It follows Ericson 5.1.9 and corresponds to b2SegmentDistance in src/distance.c.
type SensorBeginTouchEvent ¶ added in v0.4.0
type SensorBeginTouchEvent struct {
SensorShapeId, VisitorShapeId ShapeId
}
SensorBeginTouchEvent reports that a shape started to overlap a sensor. It corresponds to b2SensorBeginTouchEvent in include/box2d/types.h.
type SensorEndTouchEvent ¶ added in v0.4.0
type SensorEndTouchEvent struct {
SensorShapeId, VisitorShapeId ShapeId
}
SensorEndTouchEvent reports that a shape stopped overlapping a sensor. It corresponds to b2SensorEndTouchEvent in include/box2d/types.h.
type SensorEvents ¶ added in v0.4.0
type SensorEvents struct {
BeginEvents []SensorBeginTouchEvent
EndEvents []SensorEndTouchEvent
}
SensorEvents holds the sensor events of the last step. The slices stay valid until the next step. It corresponds to b2SensorEvents in include/box2d/types.h.
type ShapeCastInput ¶
type ShapeCastInput struct {
Proxy ShapeProxy
Translation Vec2
// MaxFraction limits the translation to consider. It is usually one.
MaxFraction Q
// CanEncroach lets a cast that starts in contact advance. It applies
// only when the radius is greater than zero.
CanEncroach bool
}
ShapeCastInput is the input of a shape cast in generic form.
type ShapeCastPairInput ¶ added in v0.3.0
type ShapeCastPairInput struct {
// ProxyA is the proxy of shape A.
ProxyA ShapeProxy
// ProxyB is the proxy of shape B.
ProxyB ShapeProxy
// TransformA is the world transform of shape A.
TransformA Transform
// TransformB is the world transform of shape B.
TransformB Transform
// TranslationB is the translation of shape B.
TranslationB Vec2
// MaxFraction is the fraction of the translation to consider. It is
// usually one.
MaxFraction Q
// CanEncroach lets shapes with a radius move a little closer when
// they already touch.
CanEncroach bool
}
ShapeCastPairInput is the input of ShapeCast. It corresponds to b2ShapeCastPairInput in include/box2d/collision.h.
type ShapeDef ¶
type ShapeDef struct {
// Application data attached to the shape.
UserData any
// The surface material of this shape.
Material SurfaceMaterial
// The density, usually in kg/m^2. It stays out of the material because
// it describes the interior, which may be hollow.
Density Q
// Collision filtering data.
Filter Filter
// A sensor generates overlap events and never a collision response.
IsSensor bool
// Enable sensor events for this shape. False by default, even for
// sensors.
EnableSensorEvents bool
// Enable contact events. Only for kinematic and dynamic bodies. Ignored
// for sensors.
EnableContactEvents bool
// Enable hit events. Only for kinematic and dynamic bodies. Ignored for
// sensors.
EnableHitEvents bool
// Enable pre-solve contact events. Only for dynamic bodies. Ignored for
// sensors.
EnablePreSolveEvents bool
// A new shape scans the environment for collision on the next step. This
// flag skips the scan on a static body, where the scan is the dominant
// creation cost. Dynamic and kinematic shapes ignore the flag.
InvokeContactCreation bool
// Update the mass of the body when this shape is created. Default true.
UpdateBodyMass bool
// contains filtered or unexported fields
}
ShapeDef holds the data to create a shape. It is a temporary bundle of creation parameters; one definition may create many shapes. Initialize it with DefaultShapeDef.
func DefaultShapeDef ¶
func DefaultShapeDef() ShapeDef
DefaultShapeDef returns the default shape definition.
type ShapeId ¶
type ShapeId struct {
// contains filtered or unexported fields
}
ShapeId identifies a shape. Its zero value is null.
func CreateCapsuleShape ¶
CreateCapsuleShape creates a capsule shape on a body. A capsule shorter than the linear slop becomes a circle at its midpoint.
func CreateCircleShape ¶
CreateCircleShape creates a circle shape on a body. The definition must come from DefaultShapeDef and is not retained.
func CreatePolygonShape ¶
CreatePolygonShape creates a polygon shape on a body. Build the polygon with MakePolygon or MakeBox.
func CreateSegmentShape ¶
CreateSegmentShape creates a segment shape on a body. It panics on a segment shorter than the linear slop.
func (ShapeId) AreContactEventsEnabled ¶ added in v0.4.0
AreContactEventsEnabled reports whether contact events are enabled. It corresponds to b2Shape_AreContactEventsEnabled.
func (ShapeId) AreHitEventsEnabled ¶ added in v0.4.0
AreHitEventsEnabled reports whether hit events are enabled. It corresponds to b2Shape_AreHitEventsEnabled.
func (ShapeId) ArePreSolveEventsEnabled ¶ added in v0.4.0
ArePreSolveEventsEnabled reports whether pre-solve events are enabled. It corresponds to b2Shape_ArePreSolveEventsEnabled.
func (ShapeId) AreSensorEventsEnabled ¶ added in v0.4.0
AreSensorEventsEnabled reports whether sensor events are enabled. It corresponds to b2Shape_AreSensorEventsEnabled.
func (ShapeId) EnableContactEvents ¶ added in v0.4.0
EnableContactEvents enables contact events on the shape. It corresponds to b2Shape_EnableContactEvents.
func (ShapeId) EnableHitEvents ¶ added in v0.4.0
EnableHitEvents enables hit events on the shape. It corresponds to b2Shape_EnableHitEvents.
func (ShapeId) EnablePreSolveEvents ¶ added in v0.4.0
EnablePreSolveEvents enables pre-solve events on the shape. It corresponds to b2Shape_EnablePreSolveEvents.
func (ShapeId) EnableSensorEvents ¶ added in v0.4.0
EnableSensorEvents enables sensor events on the shape. It corresponds to b2Shape_EnableSensorEvents.
func (ShapeId) GetAABB ¶ added in v0.4.0
GetAABB returns the shape's current axis-aligned bounds. It corresponds to b2Shape_GetAABB.
func (ShapeId) GetBody ¶ added in v0.4.0
GetBody returns the body that owns the shape. It corresponds to b2Shape_GetBody.
func (ShapeId) GetCapsule ¶ added in v0.4.0
GetCapsule returns the capsule geometry. It corresponds to b2Shape_GetCapsule.
func (ShapeId) GetChainSegment ¶ added in v0.4.0
func (shapeId ShapeId) GetChainSegment() ChainSegment
GetChainSegment returns the chain segment geometry. It corresponds to b2Shape_GetChainSegment.
func (ShapeId) GetCircle ¶ added in v0.4.0
GetCircle returns the circle geometry. It corresponds to b2Shape_GetCircle.
func (ShapeId) GetClosestPoint ¶ added in v0.4.0
GetClosestPoint returns the closest point on the shape to a world target. It corresponds to b2Shape_GetClosestPoint.
func (ShapeId) GetContactCapacity ¶ added in v0.4.0
GetContactCapacity returns the shape's conservative contact capacity. It corresponds to b2Shape_GetContactCapacity.
func (ShapeId) GetContactData ¶ added in v0.4.0
func (shapeId ShapeId) GetContactData(data []ContactData) int
GetContactData fills touching contact data in body-list order. It corresponds to b2Shape_GetContactData.
func (ShapeId) GetDensity ¶ added in v0.4.0
GetDensity returns the shape density. It corresponds to b2Shape_GetDensity.
func (ShapeId) GetFilter ¶ added in v0.4.0
GetFilter returns the shape collision filter. It corresponds to b2Shape_GetFilter.
func (ShapeId) GetFriction ¶ added in v0.4.0
GetFriction returns the shape friction. It corresponds to b2Shape_GetFriction.
func (ShapeId) GetMassData ¶ added in v0.4.0
GetMassData returns the shape mass, centroid and rotational inertia. It corresponds to b2Shape_GetMassData.
func (ShapeId) GetMaterial ¶ added in v0.4.0
GetMaterial returns the shape user material id. It corresponds to b2Shape_GetMaterial.
func (ShapeId) GetParentChain ¶ added in v0.4.0
GetParentChain returns the chain that owns the shape. It corresponds to b2Shape_GetParentChain.
func (ShapeId) GetPolygon ¶ added in v0.4.0
GetPolygon returns the polygon geometry. It corresponds to b2Shape_GetPolygon.
func (ShapeId) GetRestitution ¶ added in v0.4.0
GetRestitution returns the shape restitution. It corresponds to b2Shape_GetRestitution.
func (ShapeId) GetSegment ¶ added in v0.4.0
GetSegment returns the segment geometry. It corresponds to b2Shape_GetSegment.
func (ShapeId) GetSensorCapacity ¶ added in v0.4.0
GetSensorCapacity returns the number of current sensor overlaps. It corresponds to b2Shape_GetSensorCapacity in src/shape.c.
func (ShapeId) GetSensorOverlaps ¶ added in v0.4.0
GetSensorOverlaps fills overlaps with current sensor overlaps. It corresponds to b2Shape_GetSensorOverlaps in src/shape.c.
func (ShapeId) GetSurfaceMaterial ¶ added in v0.4.0
func (shapeId ShapeId) GetSurfaceMaterial() SurfaceMaterial
GetSurfaceMaterial returns the shape surface material. It corresponds to b2Shape_GetSurfaceMaterial.
func (ShapeId) GetType ¶ added in v0.4.0
GetType returns the shape geometry type. It corresponds to b2Shape_GetType.
func (ShapeId) GetUserData ¶ added in v0.4.0
GetUserData returns the data attached to the shape. It corresponds to b2Shape_GetUserData.
func (ShapeId) GetWorld ¶ added in v0.4.0
GetWorld returns the world containing the shape. It corresponds to b2Shape_GetWorld.
func (ShapeId) IsSensor ¶ added in v0.4.0
IsSensor reports whether the shape is a sensor. It corresponds to b2Shape_IsSensor.
func (ShapeId) RayCast ¶ added in v0.4.0
func (shapeId ShapeId) RayCast(input *RayCastInput) CastOutput
RayCast casts a world-space ray against the shape. It corresponds to b2Shape_RayCast.
func (ShapeId) SetCapsule ¶ added in v0.4.0
SetCapsule replaces the shape geometry with a capsule. It corresponds to b2Shape_SetCapsule.
func (ShapeId) SetCircle ¶ added in v0.4.0
SetCircle replaces the shape geometry with a circle. It corresponds to b2Shape_SetCircle.
func (ShapeId) SetDensity ¶ added in v0.4.0
SetDensity changes the shape density and optionally updates body mass. It corresponds to b2Shape_SetDensity.
func (ShapeId) SetFilter ¶ added in v0.4.0
SetFilter changes the shape collision filter. It corresponds to b2Shape_SetFilter.
func (ShapeId) SetFriction ¶ added in v0.4.0
SetFriction changes the shape friction. It corresponds to b2Shape_SetFriction.
func (ShapeId) SetMaterial ¶ added in v0.4.0
SetMaterial sets the shape user material id. It corresponds to b2Shape_SetMaterial.
func (ShapeId) SetPolygon ¶ added in v0.4.0
SetPolygon replaces the shape geometry with a polygon. It corresponds to b2Shape_SetPolygon.
func (ShapeId) SetRestitution ¶ added in v0.4.0
SetRestitution changes the shape restitution. It corresponds to b2Shape_SetRestitution.
func (ShapeId) SetSegment ¶ added in v0.4.0
SetSegment replaces the shape geometry with a segment. It corresponds to b2Shape_SetSegment.
func (ShapeId) SetSurfaceMaterial ¶ added in v0.4.0
func (shapeId ShapeId) SetSurfaceMaterial(material SurfaceMaterial)
SetSurfaceMaterial changes the shape surface material. It corresponds to b2Shape_SetSurfaceMaterial.
func (ShapeId) SetUserData ¶ added in v0.4.0
SetUserData attaches application data to the shape. It corresponds to b2Shape_SetUserData.
type ShapeProxy ¶
type ShapeProxy struct {
// Points holds the cloud. Only the first Count entries are valid.
Points [MaxPolygonVertices]Vec2
// Count is the number of points. It is greater than zero.
Count int
// Radius is the external radius of the cloud. It may be zero.
Radius Q
}
ShapeProxy is a point cloud with an external radius. It stands for any shape in the distance and cast routines.
func MakeOffsetProxy ¶ added in v0.3.0
func MakeOffsetProxy(points []Vec2, radius Q, position Vec2, rotation Rot) ShapeProxy
MakeOffsetProxy makes a proxy with the points transformed by a position and a rotation. The slice replaces the pointer and count pair of b2MakeOffsetProxy in src/distance.c.
func MakeProxy ¶ added in v0.2.0
func MakeProxy(points []Vec2, radius Q) ShapeProxy
MakeProxy makes a proxy for the overlap and distance routines. The slice replaces the pointer and count pair of b2MakeProxy in src/distance.c; extra points beyond the polygon limit do not enter.
type ShapeType ¶
type ShapeType int
ShapeType identifies the geometry of a shape.
const ( // CircleShape is a circle with an offset. CircleShape ShapeType = iota // CapsuleShape is an extruded circle. CapsuleShape // SegmentShape is a line segment. SegmentShape // PolygonShape is a convex polygon. PolygonShape // ChainSegmentShape is a line segment owned by a chain shape. ChainSegmentShape // ShapeTypeCount is the number of shape types. ShapeTypeCount )
type Simplex ¶ added in v0.3.0
type Simplex struct {
// V1, V2 and V3 are the vertices.
V1, V2, V3 SimplexVertex
// Count is the number of valid vertices.
Count int
}
Simplex is the simplex of the GJK algorithm. It corresponds to b2Simplex in include/box2d/collision.h.
type SimplexCache ¶ added in v0.2.0
type SimplexCache struct {
// Count is the number of stored simplex vertices.
Count uint16
// IndexA holds the vertices of shape A on the simplex.
IndexA [3]uint8
// IndexB holds the vertices of shape B on the simplex.
IndexB [3]uint8
}
SimplexCache warm starts the distance solver between two calls. The zero value is an empty cache; ShapeDistance fills it. It corresponds to b2SimplexCache in include/box2d/collision.h.
type SimplexVertex ¶ added in v0.3.0
type SimplexVertex struct {
// WA is the support point in proxy A.
WA Vec2
// WB is the support point in proxy B.
WB Vec2
// W is wA - wB.
W Vec2
// A is the barycentric coordinate of the closest point.
A Q
// IndexA is the index of WA.
IndexA int
// IndexB is the index of WB.
IndexB int
}
SimplexVertex is a vertex of the GJK simplex, kept for debugging. It corresponds to b2SimplexVertex in include/box2d/collision.h.
type SurfaceMaterial ¶
type SurfaceMaterial struct {
// The Coulomb friction coefficient, usually in the range [0, 1].
Friction Q
// The coefficient of restitution, usually in the range [0, 1].
Restitution Q
// The rolling resistance, usually in the range [0, 1].
RollingResistance Q
// The tangent speed, for conveyor belts.
TangentSpeed Q
// Application material identifier, returned with query results. The
// world does not use it.
UserMaterialId int
// Custom debug draw color.
CustomColor uint32
}
SurfaceMaterial holds the surface properties of a shape.
func DefaultSurfaceMaterial ¶
func DefaultSurfaceMaterial() SurfaceMaterial
DefaultSurfaceMaterial returns the default material: friction 0.6.
type Sweep ¶ added in v0.3.0
type Sweep struct {
// LocalCenter is the local center of mass.
LocalCenter Vec2
// C1 is the starting world center of mass.
C1 Vec2
// C2 is the ending world center of mass.
C2 Vec2
// Q1 is the starting world rotation.
Q1 Rot
// Q2 is the ending world rotation.
Q2 Rot
}
Sweep describes the motion of a body for the time of impact. Shapes are defined about the body origin, which may differ from the center of mass, so the sweep interpolates the center of mass. It corresponds to b2Sweep in include/box2d/collision.h.
type TOIInput ¶ added in v0.3.0
type TOIInput struct {
// ProxyA is the proxy for shape A.
ProxyA ShapeProxy
// ProxyB is the proxy for shape B.
ProxyB ShapeProxy
// SweepA is the movement of shape A.
SweepA Sweep
// SweepB is the movement of shape B.
SweepB Sweep
// MaxFraction defines the sweep interval [0, MaxFraction].
MaxFraction Q
}
TOIInput is the input of TimeOfImpact. It corresponds to b2TOIInput in include/box2d/collision.h.
type TOIOutput ¶ added in v0.3.0
type TOIOutput struct {
// State is the type of result.
State TOIState
// Fraction is the sweep time of the collision.
Fraction Q
}
TOIOutput is the output of TimeOfImpact. It corresponds to b2TOIOutput in include/box2d/collision.h.
func TimeOfImpact ¶ added in v0.3.0
TimeOfImpact computes the largest fraction of the sweeps at which the two proxies stay separated by the target. It uses the local separating axis method, so it may miss some intermediate, non-tunneling collisions. The reference counters under B2_SNOOP_TOI_COUNTERS are not ported. It corresponds to b2TimeOfImpact in src/distance.c.
type TOIState ¶ added in v0.3.0
type TOIState int
TOIState describes the result of TimeOfImpact. It corresponds to b2TOIState in include/box2d/collision.h.
const ( // TOIStateUnknown means the solver did not reach a conclusion. TOIStateUnknown TOIState = iota // TOIStateFailed means the root finder ran out of iterations. TOIStateFailed // TOIStateOverlapped means the shapes overlap at the start. TOIStateOverlapped // TOIStateHit means the shapes touch at the fraction. TOIStateHit // TOIStateSeparated means the shapes stay apart over the whole interval. TOIStateSeparated )
type Transform ¶
Transform is a 2D rigid transform.
func GetSweepTransform ¶ added in v0.3.0
GetSweepTransform evaluates the sweep at a time in [0, 1]. It corresponds to b2GetSweepTransform in src/distance.c.
func InvMulTransforms ¶
InvMulTransforms returns the transform that converts a point local to frame b into a point local to frame a.
v2 = inv(a.q) * (b.q * v1 + b.p - a.p) = inv(a.q) * b.q * v1 + inv(a.q) * (b.p - a.p)
func MulTransforms ¶
MulTransforms composes two transforms. Applied to a point local to frame b, the result converts it to a point local to frame a, then to a point in the world frame.
v2 = a.q.Rot(b.q.Rot(v1) + b.p) + a.p = (a.q * b.q).Rot(v1) + a.q.Rot(b.p) + a.p
func TransformIdentity ¶
func TransformIdentity() Transform
TransformIdentity returns the transform that moves and rotates nothing.
type TreeQueryCallbackFcn ¶ added in v0.7.0
TreeQueryCallbackFcn receives each proxy that overlaps the query box. It returns false to stop the query. It corresponds to b2TreeQueryCallbackFcn in include/box2d/collision.h. D-014: a closure replaces the context pointer.
type TreeRayCastCallbackFcn ¶ added in v0.7.0
type TreeRayCastCallbackFcn func(input *RayCastInput, proxyId int, userData uint64) Q
TreeRayCastCallbackFcn receives each proxy whose box the ray reaches. It returns zero to stop the cast, a fraction in (0, maxFraction] to clip the ray, or any other value to continue unchanged. It corresponds to b2TreeRayCastCallbackFcn in include/box2d/collision.h. D-014 applies.
type TreeShapeCastCallbackFcn ¶ added in v0.7.0
type TreeShapeCastCallbackFcn func(input *ShapeCastInput, proxyId int, userData uint64) Q
TreeShapeCastCallbackFcn receives each proxy whose box the swept proxy reaches. Its return value works like TreeRayCastCallbackFcn's. It corresponds to b2TreeShapeCastCallbackFcn in include/box2d/collision.h. D-014 applies.
type TreeStats ¶ added in v0.3.0
type TreeStats struct {
// NodeVisits counts every node the walk touched.
NodeVisits int
// LeafVisits counts the leaves the walk tested.
LeafVisits int
}
TreeStats counts the nodes a world query visited. It corresponds to b2TreeStats in include/box2d/collision.h.
type Vec2 ¶
type Vec2 struct {
X, Y Q
}
Vec2 is a 2D vector. It represents a point or a free vector.
func ClipVector ¶ added in v0.4.0
func ClipVector(vector Vec2, planes []CollisionPlane) Vec2
ClipVector ports b2ClipVector.
func InvRotateVector ¶
InvRotateVector rotates v by the inverse of q.
func InvTransformPoint ¶
InvTransformPoint carries the point p from the parent frame into the frame of t, for example from world space into local space.
func Lerp ¶
Lerp interpolates between a and b by t.
It weighs both ends, unlike the Lerp method of the fixed-point module, which adds a scaled difference. The two round differently.
func RightPerp ¶
RightPerp returns the right-pointing perpendicular of v. It equals CrossVS(v, one).
func Solve22 ¶
Solve22 solves m * x = b for the column vector b. It is cheaper than the inverse for a one-shot case. A singular matrix returns the zero vector.
func TransformPoint ¶
TransformPoint carries the point p from the frame of t into the parent frame, for example from local space into world space.
func (Vec2) DistanceSq ¶ added in v0.8.0
DistanceSq returns the squared distance between v and o.
type Version ¶
type Version struct {
// Major counts significant changes.
Major int
// Minor counts incremental changes.
Minor int
// Revision counts bug fixes.
Revision int
}
Version reports a three-part release number.
func ReferenceVersion ¶
func ReferenceVersion() Version
ReferenceVersion returns the Box2D release that this package ports. The module has its own version; this one identifies the reference source.
type WeldJointDef ¶ added in v0.3.0
type WeldJointDef struct {
// The first attached body.
BodyIdA BodyId
// The second attached body.
BodyIdB BodyId
// The local anchor point relative to the origin of body A.
LocalAnchorA Vec2
// The local anchor point relative to the origin of body B.
LocalAnchorB Vec2
// The angle of body B minus the angle of body A in the reference
// state, in turns.
ReferenceAngle Q
// Linear stiffness in cycles per second. Zero means rigid.
LinearHertz Q
// Angular stiffness in cycles per second. Zero means rigid.
AngularHertz Q
// Linear damping ratio, non-dimensional.
LinearDampingRatio Q
// Angular damping ratio, non-dimensional.
AngularDampingRatio Q
// Set this flag to true if the attached bodies should collide.
CollideConnected bool
// Application data attached to the joint.
UserData any
// contains filtered or unexported fields
}
WeldJointDef configures a weld joint: it holds the relative transform of two bodies, rigidly or with a spring. Initialize it with DefaultWeldJointDef.
func DefaultWeldJointDef ¶ added in v0.3.0
func DefaultWeldJointDef() WeldJointDef
DefaultWeldJointDef returns the default weld joint definition.
type WheelJointDef ¶ added in v0.3.0
type WheelJointDef struct {
// The first attached body.
BodyIdA BodyId
// The second attached body.
BodyIdB BodyId
// The local anchor point relative to the origin of body A.
LocalAnchorA Vec2
// The local anchor point relative to the origin of body B.
LocalAnchorB Vec2
// The local translation unit axis in body A.
LocalAxisA Vec2
// Enable a linear spring along the local axis.
EnableSpring bool
// The spring stiffness in cycles per second.
Hertz Q
// The spring damping ratio, non-dimensional.
DampingRatio Q
// Enable and disable the joint limit.
EnableLimit bool
// The lower translation limit.
LowerTranslation Q
// The upper translation limit.
UpperTranslation Q
// Enable and disable the joint rotational motor.
EnableMotor bool
// The maximum motor torque, usually in newton-meters.
MaxMotorTorque Q
// The desired motor speed in turns per second.
MotorSpeed Q
// Set this flag to true if the attached bodies should collide.
CollideConnected bool
// Application data attached to the joint.
UserData any
// contains filtered or unexported fields
}
WheelJointDef configures a wheel joint: body B rotates freely about a point on an axis fixed in body A, with a suspension spring along the axis. Initialize it with DefaultWheelJointDef.
func DefaultWheelJointDef ¶ added in v0.3.0
func DefaultWheelJointDef() WheelJointDef
DefaultWheelJointDef returns the default wheel joint definition.
type WorldDef ¶
type WorldDef struct {
// Gravity vector. The world has no up vector.
Gravity Vec2
// Restitution speed threshold, usually in meters per second. Collisions
// above this speed have restitution applied, so they bounce.
RestitutionThreshold Q
// Threshold speed for hit events, usually in meters per second.
HitEventThreshold Q
// Contact stiffness in cycles per second. Increasing this increases the
// speed of overlap recovery, but can introduce jitter.
ContactHertz Q
// Contact bounciness, non-dimensional. Decreasing this speeds up overlap
// recovery, with a more energetic resolution as the trade-off.
ContactDampingRatio Q
// A cap on the overlap resolution speed, usually in meters per second.
// The hertz and the damping ratio set the speed itself.
MaxContactPushSpeed Q
// Maximum linear speed, usually in meters per second.
MaximumLinearSpeed Q
// FrictionCallback customizes friction mixing for new contacts.
FrictionCallback FrictionCallback
// RestitutionCallback customizes restitution mixing for new contacts.
RestitutionCallback RestitutionCallback
// WorkerCount is the number of workers that step the world. 1 steps on
// the calling goroutine. 0 picks min(runtime.GOMAXPROCS(0), 64). Any N
// produces the same bits; WebAssembly always steps on one worker, and a
// step with few awake bodies runs on the caller whatever N says.
WorkerCount int
// Enable sleeping to improve performance.
EnableSleep bool
// Enable continuous collision.
EnableContinuous bool
// Application data attached to the world.
UserData any
// contains filtered or unexported fields
}
WorldDef configures the creation of a world. Initialize it with DefaultWorldDef.
func DefaultWorldDef ¶
func DefaultWorldDef() WorldDef
DefaultWorldDef returns the default world definition.
type WorldId ¶
type WorldId struct {
// contains filtered or unexported fields
}
WorldId identifies a world. Its zero value is null.
func CreateWorld ¶
CreateWorld creates a world from a definition. The definition must come from DefaultWorldDef and is not retained. It returns the null id when every slot of the registry is in use.
func (WorldId) CastMover ¶ added in v0.4.0
func (worldId WorldId) CastMover(mover *Capsule, translation Vec2, filter QueryFilter) Q
CastMover sweeps a capsule through the world and returns the fraction of the translation it may travel. Shapes it already overlaps do not stop it; a capsule that already touches may move a little closer. A locked world panics. It corresponds to b2World_CastMover in src/world.c.
func (WorldId) CastRay ¶ added in v0.4.0
func (worldId WorldId) CastRay(origin, translation Vec2, filter QueryFilter, fcn CastResultFcn) TreeStats
CastRay reports the shapes a ray hits, tree by tree. The callback clips the ray for the next tree; a zero return stops the cast. A locked world panics. It corresponds to b2World_CastRay in src/world.c.
func (WorldId) CastRayClosest ¶ added in v0.4.0
func (worldId WorldId) CastRayClosest(origin, translation Vec2, filter QueryFilter) RayResult
CastRayClosest reports the closest hit of a ray, the most common cast in games. An initial overlap does not count as a hit. A locked world panics. It corresponds to b2World_CastRayClosest in src/world.c; the closure replaces b2RayCastClosestFcn.
func (WorldId) CastShape ¶ added in v0.4.0
func (worldId WorldId) CastShape(proxy *ShapeProxy, translation Vec2, filter QueryFilter, fcn CastResultFcn) TreeStats
CastShape sweeps a proxy through the world and reports each hit, tree by tree. The callback returns as for CastRay. A locked world panics. It corresponds to b2World_CastShape in src/world.c.
func (WorldId) CollideMover ¶ added in v0.4.0
func (worldId WorldId) CollideMover(mover *Capsule, filter QueryFilter, fcn PlaneResultFcn)
CollideMover reports the collision plane of every shape the mover capsule touches, tree by tree. The callback returns false to stop the walk. A locked world panics. It corresponds to b2World_CollideMover in src/world.c.
func (WorldId) Draw ¶ added in v0.4.0
Draw walks the world and invokes the callbacks selected by draw's flags.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, _, _ := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
// Every callback defaults to a no-op; wire up only the shapes callbacks
// used here and count how many shapes the world hands back.
shapeCount := 0
draw := dbox2d.DefaultDebugDraw()
draw.DrawShapes = true
draw.DrawSolidPolygon = func(dbox2d.Transform, []dbox2d.Vec2, dbox2d.Q, dbox2d.HexColor) { shapeCount++ }
worldId.Draw(&draw)
fmt.Println(shapeCount)
}
Output: 1
func (WorldId) DumpMemoryStats ¶ added in v0.5.0
DumpMemoryStats writes the memory use of the world to w, one section per structure. It corresponds to b2World_DumpMemoryStats in src/world.c.
func (WorldId) EnableContinuous ¶ added in v0.4.0
EnableContinuous changes continuous collision detection. It corresponds to b2World_EnableContinuous in src/world.c.
func (WorldId) EnableSleeping ¶ added in v0.4.0
EnableSleeping changes sleeping and wakes sleeping sets when disabled. It corresponds to b2World_EnableSleeping in src/world.c.
func (WorldId) EnableSpeculative ¶ added in v0.4.0
EnableSpeculative changes speculative collision handling. It corresponds to b2World_EnableSpeculative in src/world.c.
func (WorldId) EnableWarmStarting ¶ added in v0.4.0
EnableWarmStarting changes impulse warm starting. It corresponds to b2World_EnableWarmStarting in src/world.c.
func (WorldId) Explode ¶ added in v0.4.0
func (worldId WorldId) Explode(def *ExplosionDef)
Explode applies an impulse to every dynamic body near an explosion center, scaled by distance and by the shape perimeter facing the center. A locked world is a no-op. It corresponds to b2World_Explode in src/world.c.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, _, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
def := dbox2d.DefaultExplosionDef()
def.Position = boxId.GetPosition()
def.Radius = dbox2d.QFromInt(4)
def.Falloff = dbox2d.QFromInt(2)
def.ImpulsePerLength = dbox2d.QFromInt(8)
worldId.Explode(&def)
// The box center coincides with the explosion center, so the
// direction is undefined; the engine falls back to (1, 0) rather
// than leaving the impulse with a zero direction.
fmt.Println(boxId.GetLinearVelocity())
}
Output: {8 0}
func (WorldId) GetAwakeBodyCount ¶ added in v0.4.0
GetAwakeBodyCount returns the number of bodies in the awake set. It corresponds to b2World_GetAwakeBodyCount in src/world.c.
func (WorldId) GetBodyEvents ¶ added in v0.4.0
func (worldId WorldId) GetBodyEvents() BodyEvents
GetBodyEvents returns the move events of the last step. It corresponds to b2World_GetBodyEvents in src/world.c.
func (WorldId) GetContactEvents ¶ added in v0.4.0
func (worldId WorldId) GetContactEvents() ContactEvents
GetContactEvents returns the contact events of the last step. It corresponds to b2World_GetContactEvents in src/world.c.
func (WorldId) GetCounters ¶ added in v0.4.0
GetCounters reports entity, tree, arena and graph counts. It corresponds to b2World_GetCounters in src/world.c.
func (WorldId) GetGravity ¶ added in v0.4.0
GetGravity returns the gravity vector. It corresponds to b2World_GetGravity.
func (WorldId) GetHitEventThreshold ¶ added in v0.4.0
GetHitEventThreshold returns the hit-event threshold. It corresponds to b2World_GetHitEventThreshold in src/world.c.
func (WorldId) GetMaximumLinearSpeed ¶ added in v0.4.0
GetMaximumLinearSpeed returns the velocity cap. It corresponds to b2World_GetMaximumLinearSpeed in src/world.c.
func (WorldId) GetProfile ¶ added in v0.5.0
GetProfile returns the timing of the last Step. It corresponds to b2World_GetProfile in src/world.c.
func (WorldId) GetRestitutionThreshold ¶ added in v0.4.0
GetRestitutionThreshold returns the restitution speed threshold. It corresponds to b2World_GetRestitutionThreshold in src/world.c.
func (WorldId) GetSensorEvents ¶ added in v0.4.0
func (worldId WorldId) GetSensorEvents() SensorEvents
GetSensorEvents returns the sensor events of the last step. It corresponds to b2World_GetSensorEvents in src/world.c.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
func main() {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
defer dbox2d.DestroyWorld(worldId)
sensorDef := dbox2d.DefaultBodyDef()
sensorBodyId := dbox2d.CreateBody(worldId, &sensorDef)
sensorShapeDef := dbox2d.DefaultShapeDef()
sensorShapeDef.IsSensor = true
sensorShapeDef.EnableSensorEvents = true
sensorBox := dbox2d.MakeBox(dbox2d.QFromInt(2), dbox2d.QFromInt(2))
dbox2d.CreatePolygonShape(sensorBodyId, &sensorShapeDef, &sensorBox)
visitorDef := dbox2d.DefaultBodyDef()
visitorDef.Type = dbox2d.DynamicBody
visitorBodyId := dbox2d.CreateBody(worldId, &visitorDef)
visitorShapeDef := dbox2d.DefaultShapeDef()
visitorShapeDef.EnableSensorEvents = true
visitorBox := dbox2d.MakeSquare(dbox2d.QHalf())
visitorShapeId := dbox2d.CreatePolygonShape(visitorBodyId, &visitorShapeDef, &visitorBox)
dt := dbox2d.QOne().Div(dbox2d.QFromInt(60))
worldId.Step(dt, 4)
begin := worldId.GetSensorEvents().BeginEvents
fmt.Println(len(begin) == 1 && begin[0].VisitorShapeId == visitorShapeId)
dbox2d.DestroyShape(visitorShapeId, false)
worldId.Step(dt, 4)
end := worldId.GetSensorEvents().EndEvents
fmt.Println(len(end) == 1 && end[0].VisitorShapeId == visitorShapeId)
}
Output: true true
func (WorldId) GetUserData ¶ added in v0.4.0
GetUserData returns the data attached to the world. It corresponds to b2World_GetUserData in src/world.c.
func (WorldId) IsContinuousEnabled ¶ added in v0.4.0
IsContinuousEnabled reports whether continuous collision is enabled. It corresponds to b2World_IsContinuousEnabled in src/world.c.
func (WorldId) IsSleepingEnabled ¶ added in v0.4.0
IsSleepingEnabled reports whether sleeping is enabled. It corresponds to b2World_IsSleepingEnabled in src/world.c.
func (WorldId) IsValid ¶
IsValid reports whether the id references a live world. It lets an application hold ids safely across destruction.
func (WorldId) IsWarmStartingEnabled ¶ added in v0.4.0
IsWarmStartingEnabled reports whether warm starting is enabled. It corresponds to b2World_IsWarmStartingEnabled in src/world.c.
func (WorldId) OverlapAABB ¶ added in v0.4.0
func (worldId WorldId) OverlapAABB(aabb AABB, filter QueryFilter, fcn OverlapResultFcn) TreeStats
OverlapAABB reports every shape whose fat bounds overlap the box and whose filter accepts the query. It walks the static, the kinematic and the dynamic tree in that order; a false result ends only the current tree, as in the reference. A locked world panics. It corresponds to b2World_OverlapAABB in src/world.c.
func (WorldId) OverlapShape ¶ added in v0.4.0
func (worldId WorldId) OverlapShape(proxy *ShapeProxy, filter QueryFilter, fcn OverlapResultFcn) TreeStats
OverlapShape reports every shape that overlaps the proxy and whose filter accepts the query, tree by tree; a false result ends only the current tree. The distance solver decides the overlap, so the report is exact, not a bounds test. A locked world panics. It corresponds to b2World_OverlapShape in src/world.c.
func (WorldId) RebuildStaticTree ¶ added in v0.4.0
func (worldId WorldId) RebuildStaticTree()
RebuildStaticTree rebuilds the static broad-phase tree. It corresponds to b2World_RebuildStaticTree in src/world.c.
func (WorldId) SetContactTuning ¶ added in v0.4.0
SetContactTuning changes contact softness and push speed. It corresponds to b2World_SetContactTuning in src/world.c.
func (WorldId) SetCustomFilterCallback ¶ added in v0.4.0
func (worldId WorldId) SetCustomFilterCallback(fcn CustomFilterFcn)
SetCustomFilterCallback sets the pair filter run during collision. It corresponds to b2World_SetCustomFilterCallback in src/world.c; the reference also stores a void* context, dropped here per D-014.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, groundId, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
// Rejecting every pair keeps the box from ever touching the ground.
worldId.SetCustomFilterCallback(func(dbox2d.ShapeId, dbox2d.ShapeId) bool {
return false
})
dt := dbox2d.QOne().Div(dbox2d.QFromInt(60))
for range 60 {
worldId.Step(dt, 4)
}
fmt.Println(len(worldId.GetContactEvents().BeginEvents))
fmt.Println(groundId.IsValid() && boxId.IsValid())
}
Output: 0 true
func (WorldId) SetFrictionCallback ¶ added in v0.4.0
func (worldId WorldId) SetFrictionCallback(callback FrictionCallback)
SetFrictionCallback changes friction mixing for future contacts. It corresponds to b2World_SetFrictionCallback in src/world.c.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
func main() {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
defer dbox2d.DestroyWorld(worldId)
worldId.SetFrictionCallback(func(frictionA dbox2d.Q, _ int, frictionB dbox2d.Q, _ int) dbox2d.Q {
return frictionA.Add(frictionB).Div(dbox2d.QFromInt(2))
})
fmt.Println(worldId.IsValid())
}
Output: true
func (WorldId) SetGravity ¶ added in v0.4.0
SetGravity changes the world gravity vector. It corresponds to b2World_SetGravity in src/world.c.
func (WorldId) SetHitEventThreshold ¶ added in v0.4.0
SetHitEventThreshold limits the hit-event threshold to the valid Q range. It corresponds to b2World_SetHitEventThreshold in src/world.c.
func (WorldId) SetMaximumLinearSpeed ¶ added in v0.4.0
SetMaximumLinearSpeed changes the velocity cap. It corresponds to b2World_SetMaximumLinearSpeed in src/world.c.
func (WorldId) SetPreSolveCallback ¶ added in v0.4.0
func (worldId WorldId) SetPreSolveCallback(fcn PreSolveFcn)
SetPreSolveCallback sets the callback run after a contact's manifold is updated, before the solver sees it. It corresponds to b2World_SetPreSolveCallback in src/world.c.
Example ¶
package main
import (
"fmt"
"github.com/dhannyell/dbox2d"
)
// exampleWorld builds a world with a static ground body and one dynamic
// box above it. The examples hang joints between the two.
func exampleWorld() (dbox2d.WorldId, dbox2d.BodyId, dbox2d.BodyId) {
worldDef := dbox2d.DefaultWorldDef()
worldId := dbox2d.CreateWorld(&worldDef)
groundDef := dbox2d.DefaultBodyDef()
groundId := dbox2d.CreateBody(worldId, &groundDef)
boxDef := dbox2d.DefaultBodyDef()
boxDef.Type = dbox2d.DynamicBody
boxDef.Position = dbox2d.Vec2{Y: dbox2d.QFromInt(2)}
boxId := dbox2d.CreateBody(worldId, &boxDef)
shapeDef := dbox2d.DefaultShapeDef()
box := dbox2d.MakeSquare(dbox2d.QHalf())
dbox2d.CreatePolygonShape(boxId, &shapeDef, &box)
return worldId, groundId, boxId
}
func main() {
worldId, _, boxId := exampleWorld()
defer dbox2d.DestroyWorld(worldId)
// Returning false disables the contact for the step, so the box
// keeps falling through the ground instead of resting on it.
worldId.SetPreSolveCallback(func(dbox2d.ShapeId, dbox2d.ShapeId, *dbox2d.Manifold) bool {
return false
})
startY := boxId.GetPosition().Y
dt := dbox2d.QOne().Div(dbox2d.QFromInt(60))
for range 60 {
worldId.Step(dt, 4)
}
fmt.Println(boxId.GetPosition().Y.Less(startY))
}
Output: true
func (WorldId) SetRestitutionCallback ¶ added in v0.4.0
func (worldId WorldId) SetRestitutionCallback(callback RestitutionCallback)
SetRestitutionCallback changes restitution mixing for future contacts. It corresponds to b2World_SetRestitutionCallback in src/world.c.
func (WorldId) SetRestitutionThreshold ¶ added in v0.4.0
SetRestitutionThreshold limits the speed threshold to the valid Q range. It corresponds to b2World_SetRestitutionThreshold in src/world.c.
func (WorldId) SetUserData ¶ added in v0.4.0
SetUserData attaches application data to the world. It corresponds to b2World_SetUserData in src/world.c.
Source Files
¶
- aabb.go
- arena.go
- array.go
- bitset.go
- body.go
- broad_phase.go
- checksum.go
- collision.go
- constants.go
- constraint_graph.go
- contact.go
- contact_solver.go
- core.go
- distance.go
- distance_joint.go
- doc.go
- dynamic_tree.go
- executor.go
- executor_pool.go
- geometry.go
- hull.go
- id.go
- id_pool.go
- island.go
- joint.go
- manifold.go
- math.go
- motor_joint.go
- mouse_joint.go
- mover.go
- prismatic_joint.go
- revolute_joint.go
- scalar_float.go
- sensor.go
- shape.go
- simd_off.go
- solver.go
- solver_set.go
- spin_asm.go
- step.go
- table.go
- types.go
- validate_release.go
- weld_joint.go
- wheel_joint.go
- world.go
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
q32gen
Package q32gen derives the Q32 contact solver from contact_solver.go.
|
Package q32gen derives the Q32 contact solver from contact_solver.go. |
|
tools
|
|
|
q32gen
command
Command q32gen writes contact_solver_q32.go from contact_solver.go.
|
Command q32gen writes contact_solver_q32.go from contact_solver.go. |
