Documentation
¶
Overview ¶
Package xmath is the float32 math a 2D game needs: Vec2 and Rect, scalar helpers (clamp, lerp, remap, wrap, snap), angles, frame-rate independent smoothing and springs, and the Penner easing curves.
Everything is pure, takes values, allocates nothing and never panics: degenerate input returns a documented value (the Vec2.Norm of a zero vector is zero, InvLerp with equal bounds is 0). Angles are radians, clockwise on screen (y points down), like gfx.Transform.Rot.
The package imports the standard library only, so tools and pure-ECS code can use it without the engine. The engine's gfx.Vec2 and gfx.Rect are aliases of the types here. Guide: doc/guide/engine/math.md.
Index ¶
- Constants
- Variables
- func Abs[T Number](x T) T
- func AngleDiff(from, to float32) float32
- func Approach[T Number](x, target, step T) T
- func ApproachAngle(a, target, step float32) float32
- func Atan2(y, x float32) float32
- func Barycentric(p, a, b, c Vec2) (u, v, w float32)
- func Ceil(x float32) float32
- func CircleRectOverlap(c Circle, r Rect) bool
- func CirclesOverlap(a, b Circle) bool
- func Clamp[T Number](x, lo, hi T) T
- func Clamp01(x float32) float32
- func ClampAbs(x, m float32) float32
- func Cos(x float32) float32
- func Damp(x, target, halfLife, dt float32) float32
- func DampAngle(a, target, halfLife, dt float32) float32
- func DampFactor(d, dt float32) float32
- func Decay(x, rate, dt float32) float32
- func Deg(rad float32) float32
- func EaseInBack(t float32) float32
- func EaseInBounce(t float32) float32
- func EaseInCubic(t float32) float32
- func EaseInElastic(t float32) float32
- func EaseInExpo(t float32) float32
- func EaseInOutBack(t float32) float32
- func EaseInOutCubic(t float32) float32
- func EaseInOutExpo(t float32) float32
- func EaseInOutQuad(t float32) float32
- func EaseInOutSine(t float32) float32
- func EaseInQuad(t float32) float32
- func EaseInSine(t float32) float32
- func EaseLinear(t float32) float32
- func EaseOutBack(t float32) float32
- func EaseOutBounce(t float32) float32
- func EaseOutCubic(t float32) float32
- func EaseOutElastic(t float32) float32
- func EaseOutExpo(t float32) float32
- func EaseOutQuad(t float32) float32
- func EaseOutSine(t float32) float32
- func Exp(x float32) float32
- func ExpFactor(dt, tau float32) float32
- func Floor(x float32) float32
- func FloorDiv(a, b int) int
- func Fract(x float32) float32
- func Hash32(x uint32) uint32
- func HashFloat(x uint32) float32
- func Hypot(x, y float32) float32
- func InvLerp(a, b, v float32) float32
- func IsFinite(x float32) bool
- func Lerp(a, b, t float32) float32
- func LerpAngle(a, b, t float32) float32
- func Mod(x, y float32) float32
- func ModInt(a, b int) int
- func NearlyEqual(a, b, eps float32) bool
- func Noise1(seed uint32, x float32) float32
- func Noise2(seed uint32, x, y float32) float32
- func Pick[T any](r *Rand, s []T) T
- func PingPong(t, length float32) float32
- func PointInPolygon(p Vec2, poly []Vec2) bool
- func PolygonArea(poly []Vec2) float32
- func Pow(x, y float32) float32
- func Rad(deg float32) float32
- func Remap(v, a0, a1, b0, b1 float32) float32
- func RemapClamped(v, a0, a1, b0, b1 float32) float32
- func Repeat(t, length float32) float32
- func Round(x float32) float32
- func SegmentDist(p, a, b Vec2) float32
- func Shuffle[T any](r *Rand, s []T)
- func Sign[T Number](x T) T
- func SignEps(x, eps float32) float32
- func Sin(x float32) float32
- func Sincos(x float32) (s, c float32)
- func SmoothDamp(x, target float32, vel *float32, smoothTime, maxSpeed, dt float32) float32
- func SmoothStep(e0, e1, x float32) float32
- func SmootherStep(e0, e1, x float32) float32
- func Snap(x, step float32) float32
- func SnapFloor(x, step float32) float32
- func SpringStep(x, v, target, dt, freq, zeta float32) (float32, float32)
- func Sq(x float32) float32
- func Sqrt(x float32) float32
- func Step(edge, x float32) float32
- func Trunc(x float32) float32
- func Wrap[T Number](x, lo, hi T) T
- func WrapAngle(a float32) float32
- type Circle
- type EaseFunc
- type Hit
- type Mat3
- type Number
- type Rand
- func (r *Rand) Angle() float32
- func (r *Rand) Chance(p float32) bool
- func (r *Rand) Float() float32
- func (r *Rand) Gauss(mean, stddev float32) float32
- func (r *Rand) InCircle(radius float32) Vec2
- func (r *Rand) InRect(rc Rect) Vec2
- func (r *Rand) IntRange(lo, hi int) int
- func (r *Rand) OnCircle(radius float32) Vec2
- func (r *Rand) Range(lo, hi float32) float32
- func (r *Rand) Seed(seed uint64)
- func (r *Rand) Sign() float32
- func (r *Rand) Spread(center, spread float32) float32
- func (r *Rand) UnitVec() Vec2
- func (r *Rand) Weighted(weights []float32) int
- type Rect
- func (r Rect) Center() Vec2
- func (r Rect) ClampCenter(c, half Vec2) Vec2
- func (r Rect) ClampPoint(p Vec2) Vec2
- func (r Rect) ClosestPoint(p Vec2) Vec2
- func (r Rect) Contains(p Vec2) bool
- func (r Rect) ContainsRect(o Rect) bool
- func (r Rect) Corners() [4]Vec2
- func (r Rect) Empty() bool
- func (r Rect) Extend(p Vec2) Rect
- func (r Rect) Grow(m float32) Rect
- func (r Rect) GrowV(m Vec2) Rect
- func (r Rect) H() float32
- func (r Rect) HalfSize() Vec2
- func (r Rect) Intersect(o Rect) Rect
- func (r Rect) Lerp(o Rect, t float32) Rect
- func (r Rect) Overlaps(o Rect) bool
- func (r Rect) Penetration(o Rect) Vec2
- func (r Rect) Size() Vec2
- func (r Rect) Translate(d Vec2) Rect
- func (r Rect) Union(o Rect) Rect
- func (r Rect) W() float32
- type Vec2
- func (v Vec2) Abs() Vec2
- func (v Vec2) Add(o Vec2) Vec2
- func (v Vec2) Angle() float32
- func (v Vec2) AngleTo(o Vec2) float32
- func (v Vec2) Approach(target Vec2, step float32) Vec2
- func (v Vec2) Clamp(lo, hi Vec2) Vec2
- func (v Vec2) ClampLen(limit float32) Vec2
- func (v Vec2) Cross(o Vec2) float32
- func (v Vec2) Damp(target Vec2, halfLife, dt float32) Vec2
- func (v Vec2) Dist(o Vec2) float32
- func (v Vec2) DistSq(o Vec2) float32
- func (v Vec2) Div(f float32) Vec2
- func (v Vec2) DivV(o Vec2) Vec2
- func (v Vec2) Dot(o Vec2) float32
- func (v Vec2) Floor() Vec2
- func (v Vec2) IsZero() bool
- func (v Vec2) Len() float32
- func (v Vec2) LenSq() float32
- func (v Vec2) Lerp(o Vec2, t float32) Vec2
- func (v Vec2) Max(o Vec2) Vec2
- func (v Vec2) Min(o Vec2) Vec2
- func (v Vec2) Mul(f float32) Vec2
- func (v Vec2) MulV(o Vec2) Vec2
- func (v Vec2) NearlyEqual(o Vec2, eps float32) bool
- func (v Vec2) Neg() Vec2
- func (v Vec2) Norm() Vec2
- func (v Vec2) NormOk() (Vec2, bool)
- func (v Vec2) Perp() Vec2
- func (v Vec2) Project(onto Vec2) Vec2
- func (v Vec2) Reflect(n Vec2) Vec2
- func (v Vec2) Reject(onto Vec2) Vec2
- func (v Vec2) Rotate(a float32) Vec2
- func (v Vec2) Round() Vec2
- func (v Vec2) Snap(step Vec2) Vec2
- func (v Vec2) Spring(vel *Vec2, target Vec2, dt, freq, zeta float32) Vec2
- func (v Vec2) Sub(o Vec2) Vec2
- func (v Vec2) WithLen(l float32) Vec2
- func (v Vec2) XY() (float32, float32)
Constants ¶
const ( // Pi is half a turn. Tau is Pi*2, one full turn: spin += Tau * dt turns // once per second. HalfPi is a quarter turn. Pi float32 = math.Pi Tau float32 = 2 * math.Pi HalfPi float32 = math.Pi / 2 )
Mathematical constants as float32.
const Epsilon float32 = 1e-6
Epsilon is the default tolerance of the *Ok functions, e.g. Vec2.NormOk.
Variables ¶
var ( Zero = Vec2{0, 0} One = Vec2{1, 1} Right = Vec2{1, 0} Down = Vec2{0, 1} Left = Vec2{-1, 0} Up = Vec2{0, -1} )
Common vectors. Screen space: Down is +Y and Up is -Y, e.g. vel = vel.Add(Down.Mul(gravity*dt)). Treat them as constants.
Functions ¶
func AngleDiff ¶
AngleDiff returns the shortest signed turn from one angle to another, in (-Pi, Pi], e.g. if Abs(AngleDiff(rot, aim)) < 0.1 { fire() }.
func Approach ¶
func Approach[T Number](x, target, step T) T
Approach moves x toward target by at most step without overshooting, e.g. vel.X = Approach(vel.X, 0, friction*dt). A negative step is treated as 0.
func ApproachAngle ¶
ApproachAngle turns a toward target by at most step along the shortest arc, e.g. rot = ApproachAngle(rot, aim, turnSpeed*dt).
func Atan2 ¶
Atan2 returns the angle of the point (x, y) in (-Pi, Pi], e.g. aim := Atan2(dy, dx) to turn a turret to the mouse.
func Barycentric ¶
Barycentric returns the weights (u, v, w), summing to 1, with p = u·a + v·b + w·c, e.g. to interpolate vertex colors in a custom mesh. The weights are all inside 0..1 when p lies inside the triangle. A degenerate triangle returns (1, 0, 0).
func CircleRectOverlap ¶
CircleRectOverlap reports whether c and r share an area (touching does not count), e.g. a round player against a spike tile.
func CirclesOverlap ¶
CirclesOverlap reports whether a and b share an area (touching circles do not), e.g. a bullet against an asteroid.
func Clamp ¶
func Clamp[T Number](x, lo, hi T) T
Clamp returns x limited to [lo, hi], e.g. hp = Clamp(hp+heal, 0, maxHP). If lo > hi, lo wins.
func ClampAbs ¶
ClampAbs returns x limited to [-m, m]; an m of 0 or less means no limit. E.g. vel.Y = ClampAbs(vel.Y, maxFall).
func Cos ¶
Cos returns the float32 cosine of x radians, e.g. x := Cos(a) * orbitRadius for a circling drone.
func Damp ¶
Damp moves x toward target, halving the remaining gap every halfLife seconds, whatever the frame rate, e.g. zoom = Damp(zoom, targetZoom, 0.15, dt). A halfLife of 0 or less snaps to target; a dt of 0 or less leaves x alone.
func DampAngle ¶
DampAngle is Damp along the shortest arc, e.g. a camera that rotates with the player.
func DampFactor ¶
DampFactor returns (1-d)^dt: the factor that keeps (1-d) of a value per second over dt seconds, e.g. vel = vel.Mul(DampFactor(airDrag, dt)). A d of 0 or less returns 1 (no loss), a d of 1 or more returns 0.
func Decay ¶
Decay returns x·e^(-rate·dt), fading x toward 0, e.g. shakeTrauma = Decay(shakeTrauma, 2, dt).
func EaseInBack ¶
EaseInBack pulls back below 0 before accelerating, e.g. a wind-up.
func EaseInOutCubic ¶
EaseInOutCubic is a steeper EaseInOutQuad.
func EaseInOutQuad ¶
EaseInOutQuad does both, e.g. a camera pan between two rooms.
func EaseInOutSine ¶
EaseInOutSine is both, e.g. a room transition fade.
func EaseInQuad ¶
EaseInQuad accelerates, e.g. an item that starts slowly as it is pulled to the player.
func EaseInSine ¶
EaseInSine is a gentle acceleration along a quarter cosine.
func EaseOutBack ¶
EaseOutBack overshoots 1 then settles, e.g. a popup that "pops".
func EaseOutBounce ¶
EaseOutBounce bounces at the end, e.g. a dropped coin landing.
func EaseOutElastic ¶
EaseOutElastic is a springy overshoot, e.g. a damage number that wobbles in.
func EaseOutQuad ¶
EaseOutQuad decelerates, e.g. a menu sliding in.
func EaseOutSine ¶
EaseOutSine is a gentle deceleration along a quarter sine.
func ExpFactor ¶
ExpFactor returns 1 - e^(-dt/tau), the share of the remaining gap that exponential smoothing with time constant tau closes in dt seconds. Two steps of dt close the same share as one step of 2*dt, so pos = Lerp(pos, goal, ExpFactor(dt, tau)) is the frame-rate independent replacement for "lerp by 0.1". A dt of 0 or less gives 0, a tau of 0 or less gives 1.
func FloorDiv ¶
FloorDiv divides a by b rounding down, so FloorDiv(-1, 16) is -1, e.g. chunk := FloorDiv(cellX, 32). A b of 0 panics like the / operator.
func Hash32 ¶
Hash32 is a well-mixed integer hash (the lowbias32 function by Chris Wellons): cheap, and neighboring inputs give unrelated outputs, e.g. a per-tile random variant: Hash32(uint32(x*73856093 ^ y)).
func HashFloat ¶
HashFloat returns Hash32(x) mapped to [0, 1), e.g. a stable random grass tint per cell.
func Hypot ¶
Hypot returns Sqrt(x*x + y*y) without intermediate overflow, e.g. the distance from two deltas.
func InvLerp ¶
InvLerp returns where v lies between a and b (0 at a, 1 at b), or 0 when a == b, e.g. t := InvLerp(minSpeed, maxSpeed, speed).
func IsFinite ¶
IsFinite reports whether x is neither NaN nor an infinity, e.g. to guard a physics step against a bad division.
func Lerp ¶
Lerp returns the value t of the way from a to b, extrapolating outside 0..1, e.g. width := Lerp(0, barW, hp/maxHP). It is exactly a at t = 0 and exactly b at t = 1.
func LerpAngle ¶
LerpAngle interpolates from a to b along the shortest arc, e.g. a ship turning smoothly across the ±Pi seam.
func Mod ¶
Mod returns the remainder of x/y that is never negative for y > 0 (Euclidean), e.g. scroll := Mod(offset, bgWidth). A y of 0 returns 0.
func ModInt ¶
ModInt returns the remainder of a/b with the sign of b (Euclidean for b > 0), e.g. frame := ModInt(i, len(frames)) also for negative i. A b of 0 panics like the % operator.
func NearlyEqual ¶
NearlyEqual reports whether |a-b| <= eps, e.g. to snap a tween's end value in tests or logic.
func Noise1 ¶
Noise1 is smooth 1D gradient (Perlin) noise in [-1, 1]: continuous in x, zero at every integer x, and the same for the same seed and x on every run. Each seed gives an unrelated curve, e.g. camera shake with one seed per axis, or a flickering torch.
func Noise2 ¶
Noise2 is smooth 2D gradient (Perlin) noise in [-1, 1]: continuous in x and y, zero at every integer point, and the same for the same seed on every run, e.g. clouds or the height of procedural terrain. Different seeds give unrelated fields.
func Pick ¶
Pick returns a random element of s, e.g. a footstep sound from a set. An empty s gives the zero value.
func PingPong ¶
PingPong bounces t between 0 and length and back, e.g. a patrol: x := left + PingPong(time*speed, width). A length of 0 or less returns 0.
func PointInPolygon ¶
PointInPolygon reports whether p lies inside the polygon with the given corners (even-odd rule, either winding), e.g. a Tiled polygon trigger zone. Fewer than three points contain nothing.
func PolygonArea ¶
PolygonArea returns the signed area of the polygon, positive when the corners run clockwise on screen, e.g. to check the winding of an imported shape. Fewer than three points have area 0.
func Remap ¶
Remap maps v from the range [a0, a1] to [b0, b1], e.g. pitch := Remap(speed, 0, 300, 0.8, 1.4). An empty source range maps to b0.
func RemapClamped ¶
RemapClamped is Remap with the fraction limited to 0..1, e.g. an engine volume that never exceeds its maximum.
func Repeat ¶
Repeat loops t into [0, length), e.g. a looping animation time. A length of 0 or less returns 0.
func Round ¶
Round rounds x to the nearest integer, halves away from zero, e.g. to pixel-snap a sprite: Round(pos.X).
func SegmentDist ¶
SegmentDist returns the distance from p to the segment a-b, e.g. to pick a gizmo arrow or to test a laser beam against the player.
func Sign ¶
func Sign[T Number](x T) T
Sign returns -1, 0 or 1 by the sign of x, e.g. facing := Sign(input.X).
func SignEps ¶
SignEps is Sign with a dead zone: it returns 0 when |x| <= eps, e.g. to ignore stick drift: SignEps(axis, 0.2).
func Sin ¶
Sin returns the float32 sine of x radians, e.g. bob := Sin(time*4) * 2 for a hovering pickup.
func Sincos ¶
Sincos returns the sine and cosine of x radians, e.g. to build the rotation of a spinning saw blade.
func SmoothDamp ¶
SmoothDamp moves x toward target like a critically damped spring that reaches it in about smoothTime seconds (Unity's SmoothDamp), keeping its speed in *vel between calls, e.g. a UI bar that eases to the new HP. A maxSpeed of 0 or less means no limit. A dt of 0 or less changes nothing.
func SmoothStep ¶
SmoothStep returns the Hermite ramp from 0 at e0 to 1 at e1, e.g. fog := SmoothStep(100, 200, dist). Equal edges give a hard step at e0.
func SmootherStep ¶
SmootherStep is SmoothStep with Perlin's quintic, flat in its first and second derivative at both ends, e.g. a softer vignette.
func Snap ¶
Snap returns the nearest multiple of step, e.g. an editor grid: Snap(mouse.X, 8). A step of 0 returns x.
func SnapFloor ¶
SnapFloor returns the multiple of step at or below x, e.g. the tile under a point: SnapFloor(p.X, 16). A step of 0 returns x.
func SpringStep ¶
SpringStep advances a damped spring pulling x (moving at speed v) toward target by dt seconds, with natural frequency freq (Hz) and damping ratio zeta, and returns the new position and speed. It uses the exact solution of x” + 2ζωx' + ω²x = 0 for a target that is constant during dt, so it is stable for any dt and two steps of dt equal one step of 2*dt. A zeta below 1 overshoots, 1 is critical, above 1 creeps in. A dt of 0 or less changes nothing. E.g. a squash-and-stretch scale that wobbles back to 1.
func Step ¶
Step returns 0 for x below edge and 1 from edge on, e.g. onGround := Step(groundY, feetY).
Types ¶
type Circle ¶
Circle is a circle with center C and radius R, e.g. a blast radius or a round trigger.
type EaseFunc ¶
EaseFunc maps a time fraction t in 0..1 to a progress fraction. Back and Elastic curves overshoot in between (below 0 or above 1). Every curve here is exactly 0 at 0 and exactly 1 at 1; inputs outside 0..1 are not clamped. The formulas are Robert Penner's. In curves start slowly, Out curves end slowly, InOut curves do both.
type Hit ¶
Hit is the result of a ray or sweep test. T is the fraction of the ray where it hit (0 to 1), Point the contact point and Normal the unit normal of the surface that was hit. A ray that starts inside the shape reports T 0, the ray's start as Point and a zero Normal.
func RayCircle ¶
RayCircle tests the ray from + t·d, t in 0..1, against c, e.g. a sniper shot against a round enemy. A ray that starts inside reports T 0. A circle with a radius of 0 or less is never hit.
func RayRect ¶
RayRect tests the ray from + t·d, t in 0..1, against r with the slab method, e.g. a grappling hook against crates. A ray that starts inside r reports T 0; one that only runs along an edge or touches a corner does not hit.
func RaySegment ¶
RaySegment tests the ray from + t·d, t in 0..1, against the segment a-b, e.g. a hitscan bullet against wall segments. The Normal faces the ray's origin. A ray parallel to the segment does not hit it.
func SweepRect ¶
SweepRect moves the box moving by d and reports where it first touches still, e.g. so fast bullets cannot tunnel through walls. Hit.T is the fraction of d travelled, Hit.Point the moving box's center at that moment and Hit.Normal the face of still that was hit. A box that already overlaps still reports T 0.
type Mat3 ¶
type Mat3 struct {
A, B, C, D, TX, TY float32
}
Mat3 is a 2D affine transform, a 3×3 matrix whose last row (0 0 1) is implied and so stored as 2×3:
x' = A·x + C·y + TX y' = B·x + D·y + TY
The zero value maps everything to the origin; start from Identity. Rotation is clockwise on screen, like Vec2.Rotate. Like the other types it has no MarshalJSON.
func Identity ¶
func Identity() Mat3
Identity returns the matrix that changes nothing, the start of a transform chain.
func Rotation ¶
Rotation returns the matrix that turns by a radians (clockwise on screen), e.g. a rotating turret's local frame.
func Scaling ¶
Scaling returns the matrix that scales per axis, e.g. Scaling(V(-1, 1)) flips a sprite horizontally.
func TRS ¶
TRS returns the matrix that scales, then rotates, then moves: a transform component as a matrix, e.g. the local-to-world matrix of an entity. It maps p to pos + Rotate(scale·p), the order the renderer draws sprites in.
func Translation ¶
Translation returns the matrix that moves by d, e.g. the parent offset of a child sprite.
func (Mat3) ApplyDir ¶
ApplyDir transforms the direction v, ignoring the translation, e.g. to rotate a local velocity into world space.
func (Mat3) ApplyRect ¶
ApplyRect returns the axis-aligned bounds of r after the transform, e.g. to cull a rotated sprite.
type Rand ¶
type Rand struct {
// contains filtered or unexported fields
}
Rand is a seeded random source for gameplay. There is no package-wide generator: a system owns a Rand, so the same seed replays the same game and tests are deterministic. A Rand is not safe for concurrent use.
func NewRand ¶
NewRand returns a generator that always produces the same sequence for the same seed, e.g. the same dungeon for the same seed.
func (*Rand) Angle ¶
Angle returns a uniform angle in [0, Tau), e.g. for debris flying in any direction.
func (*Rand) Chance ¶
Chance reports true with probability p, e.g. a 25 % crit: r.Chance(0.25). p <= 0 is never, p >= 1 always.
func (*Rand) Float ¶
Float returns a uniform number in [0, 1), e.g. if r.Float() < 0.1 { dropLoot() }.
func (*Rand) Gauss ¶
Gauss returns a normally distributed number, e.g. natural-looking damage rolls. A negative stddev behaves like its absolute value.
func (*Rand) InCircle ¶
InCircle returns a uniform point inside the disc of the given radius around the origin, e.g. an explosion's sparks. (The distance is radius·√u, so the points do not bunch up in the middle.)
func (*Rand) IntRange ¶
IntRange returns a uniform integer in [lo, hi] (both included), e.g. damage := r.IntRange(3, 6). If hi < lo it returns lo.
func (*Rand) OnCircle ¶
OnCircle returns a random point on the ring of the given radius around the origin, e.g. to spawn enemies around the player.
func (*Rand) Range ¶
Range returns a uniform number in [lo, hi), e.g. a spawn delay of r.Range(0.5, 1.5) seconds.
func (*Rand) Seed ¶
Seed restarts the sequence as if r was made by NewRand(seed). It does not allocate, so a pool can reseed per spawn.
func (*Rand) Spread ¶
Spread returns center ± spread, uniformly, e.g. Spread(aim, Rad(5)) for weapon spread.
type Rect ¶
type Rect struct {
Min, Max Vec2
}
Rect is an axis-aligned rectangle from Min (inclusive) to Max (exclusive). It serializes as {"Min": {..}, "Max": {..}}, like Vec2 without a MarshalJSON.
func PolygonBounds ¶
PolygonBounds returns the bounds of the points, e.g. the broadphase box of a polygon collider. No points give the zero Rect. Max is the largest corner, so a point on it lies outside the Rect (see Rect).
func RectCentered ¶
RectCentered returns the rectangle of the given size around c, e.g. a hitbox around the player's feet.
func RectPoints ¶
RectPoints returns the rectangle spanning two points in any order, e.g. a mouse drag selection.
func RectXYWH ¶
RectXYWH returns the rectangle with corner (x, y) and size (w, h), e.g. a Tiled object's box.
func (Rect) ClampCenter ¶
ClampCenter returns c moved so a box of half-size half around it stays inside r. On an axis where the box does not fit, it returns the center of r. E.g. camera bounds.
func (Rect) ClampPoint ¶
ClampPoint returns p clamped into r, e.g. to keep the player inside the arena. An empty r returns Min.
func (Rect) ClosestPoint ¶
ClosestPoint returns the point of r nearest to p, e.g. for a circle against a box or a magnet pull to a platform.
func (Rect) Contains ¶
Contains reports whether p lies inside r (Min in, Max out), e.g. a button hover test.
func (Rect) ContainsRect ¶
ContainsRect reports whether o lies fully inside r, e.g. "is the room fully on screen".
func (Rect) Corners ¶
Corners returns the corners in the order top-left, top-right, bottom-right, bottom-left on screen, e.g. to draw a debug outline.
func (Rect) Empty ¶
Empty reports whether r has no area (width or height of 0 or less), e.g. to skip drawing a collapsed panel.
func (Rect) Grow ¶
Grow returns r expanded by m on every side; a negative m shrinks it, e.g. a pickup radius margin.
func (Rect) GrowV ¶
GrowV returns r expanded by m.X left and right and m.Y above and below, e.g. a camera dead zone of 32×16.
func (Rect) Intersect ¶
Intersect returns the region r and o share, or the zero Rect when they do not overlap, e.g. to clip a sprite to the viewport.
func (Rect) Overlaps ¶
Overlaps reports whether r and o share an area; rectangles that only touch along an edge do not overlap. E.g. player against a coin box.
func (Rect) Penetration ¶
Penetration returns the smallest push that moves o out of r, or Zero when they do not overlap, e.g. a simple box collision response. It pushes along the axis of least overlap, away from r's center; ties go to X.
type Vec2 ¶
Vec2 is a 2D vector in world units or pixels, depending on context. It serializes as {"X": .., "Y": ..}; it deliberately has no MarshalJSON, so the Game Object generator keeps describing it as a plain object.
func CirclePenetration ¶
CirclePenetration returns the smallest move of b that separates it from a, e.g. for crowd units pushing each other apart. It reports false when the circles do not overlap. Circles with the same center are pushed along Right.
func ClosestOnSegment ¶
ClosestOnSegment returns the point of the segment a-b nearest to p, e.g. to snap a character to a rope. A degenerate segment (a == b) returns a.
func FromAngle ¶
FromAngle returns the unit vector at angle a, e.g. bullet.Vel = FromAngle(aim).Mul(speed).
func SegmentsIntersect ¶
SegmentsIntersect returns the crossing point of the segments a-b and c-d, e.g. line of sight across a wall edge. Parallel segments (including overlapping ones) do not intersect.
func (Vec2) Angle ¶
Angle returns the angle of v (Atan2), e.g. t.Rot = vel.Angle() so an arrow points where it flies.
func (Vec2) AngleTo ¶
AngleTo returns the signed angle from v to o in (-Pi, Pi], e.g. how far a homing missile must turn.
func (Vec2) Approach ¶
Approach moves v toward target by at most step, e.g. an elevator to the next floor.
func (Vec2) ClampLen ¶
ClampLen returns v with its length limited to limit (a limit below 0 counts as 0), e.g. vel = vel.ClampLen(maxSpeed) for top-down movement.
func (Vec2) Cross ¶
Cross returns the 2D cross product (the z of the 3D cross), e.g. which side of a wall: Sign(wall.Cross(p.Sub(a))).
func (Vec2) Damp ¶
Damp is Damp on both axes: a frame-rate independent follow that halves the gap to target every halfLife seconds, e.g. cam = cam.Damp(player, 0.1, dt).
func (Vec2) DistSq ¶
DistSq returns the squared distance to o, e.g. a nearest-enemy search without square roots.
func (Vec2) IsZero ¶
IsZero reports whether v is the zero vector, e.g. if input.IsZero() { anim = idle }.
func (Vec2) LenSq ¶
LenSq returns the squared length without a square root, e.g. d.LenSq() < Sq(aggroRadius).
func (Vec2) Lerp ¶
Lerp returns the point t of the way from v to o (t=0 is v, t=1 is o), e.g. a cutscene camera between two marks.
func (Vec2) NearlyEqual ¶
NearlyEqual reports whether both axes differ by at most eps, e.g. "arrived at the waypoint".
func (Vec2) Norm ¶
Norm returns the unit vector in v's direction; the zero vector stays zero, e.g. dir := input.Norm() so diagonals are not faster.
func (Vec2) NormOk ¶
NormOk is Vec2.Norm that also reports whether v was long enough (at least Epsilon) to have a direction; otherwise it returns Zero and false. E.g. a contact normal that may be degenerate.
func (Vec2) Perp ¶
Perp returns v turned 90° clockwise on screen, e.g. the strafe direction from a facing vector.
func (Vec2) Project ¶
Project returns the component of v along onto (zero if onto is the zero vector), e.g. speed along a slope.
func (Vec2) Reflect ¶
Reflect mirrors v off a surface with unit normal n, e.g. ball.Vel = ball.Vel.Reflect(hit.Normal).
func (Vec2) Reject ¶
Reject returns v minus its projection onto onto, e.g. to slide along a wall: vel.Reject(wallNormal).
func (Vec2) Rotate ¶
Rotate returns v turned by a radians, clockwise on screen, e.g. muzzle := t.Pos.Add(gunOffset.Rotate(t.Rot)).
func (Vec2) Round ¶
Round rounds each axis to the nearest integer, e.g. for crisp pixel-art sprite positions.
func (Vec2) Snap ¶
Snap snaps each axis to the nearest multiple of step's axis, e.g. to place a prefab on a 16×16 grid: p.Snap(Splat(16)).
func (Vec2) Spring ¶
Spring is SpringStep on both axes: it advances v toward target with the speed kept in *vel and returns the new position, e.g. a bouncy cursor or camera rig.