xmath

package
v0.0.0-...-94fff03 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: MIT Imports: 2 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

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

View Source
const Epsilon float32 = 1e-6

Epsilon is the default tolerance of the *Ok functions, e.g. Vec2.NormOk.

Variables

View Source
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 Abs

func Abs[T Number](x T) T

Abs returns |x|, e.g. if Abs(vel.X) < 1 { anim = idle }.

func AngleDiff

func AngleDiff(from, to float32) float32

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

func ApproachAngle(a, target, step float32) float32

ApproachAngle turns a toward target by at most step along the shortest arc, e.g. rot = ApproachAngle(rot, aim, turnSpeed*dt).

func Atan2

func Atan2(y, x float32) float32

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

func Barycentric(p, a, b, c Vec2) (u, v, w float32)

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 Ceil

func Ceil(x float32) float32

Ceil rounds x up, e.g. pages := Ceil(items / perPage).

func CircleRectOverlap

func CircleRectOverlap(c Circle, r Rect) bool

CircleRectOverlap reports whether c and r share an area (touching does not count), e.g. a round player against a spike tile.

func CirclesOverlap

func CirclesOverlap(a, b Circle) bool

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 Clamp01

func Clamp01(x float32) float32

Clamp01 returns x limited to [0, 1], e.g. alpha := Clamp01(timeLeft / fadeTime).

func ClampAbs

func ClampAbs(x, m float32) float32

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

func Cos(x float32) float32

Cos returns the float32 cosine of x radians, e.g. x := Cos(a) * orbitRadius for a circling drone.

func Damp

func Damp(x, target, halfLife, dt float32) float32

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

func DampAngle(a, target, halfLife, dt float32) float32

DampAngle is Damp along the shortest arc, e.g. a camera that rotates with the player.

func DampFactor

func DampFactor(d, dt float32) float32

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

func Decay(x, rate, dt float32) float32

Decay returns x·e^(-rate·dt), fading x toward 0, e.g. shakeTrauma = Decay(shakeTrauma, 2, dt).

func Deg

func Deg(rad float32) float32

Deg converts radians to degrees, e.g. to show a turret angle in a debug label.

func EaseInBack

func EaseInBack(t float32) float32

EaseInBack pulls back below 0 before accelerating, e.g. a wind-up.

func EaseInBounce

func EaseInBounce(t float32) float32

EaseInBounce bounces at the start.

func EaseInCubic

func EaseInCubic(t float32) float32

EaseInCubic is a steeper EaseInQuad.

func EaseInElastic

func EaseInElastic(t float32) float32

EaseInElastic is a springy wind-up.

func EaseInExpo

func EaseInExpo(t float32) float32

EaseInExpo accelerates exponentially.

func EaseInOutBack

func EaseInOutBack(t float32) float32

EaseInOutBack does both.

func EaseInOutCubic

func EaseInOutCubic(t float32) float32

EaseInOutCubic is a steeper EaseInOutQuad.

func EaseInOutExpo

func EaseInOutExpo(t float32) float32

EaseInOutExpo does both.

func EaseInOutQuad

func EaseInOutQuad(t float32) float32

EaseInOutQuad does both, e.g. a camera pan between two rooms.

func EaseInOutSine

func EaseInOutSine(t float32) float32

EaseInOutSine is both, e.g. a room transition fade.

func EaseInQuad

func EaseInQuad(t float32) float32

EaseInQuad accelerates, e.g. an item that starts slowly as it is pulled to the player.

func EaseInSine

func EaseInSine(t float32) float32

EaseInSine is a gentle acceleration along a quarter cosine.

func EaseLinear

func EaseLinear(t float32) float32

EaseLinear returns t.

func EaseOutBack

func EaseOutBack(t float32) float32

EaseOutBack overshoots 1 then settles, e.g. a popup that "pops".

func EaseOutBounce

func EaseOutBounce(t float32) float32

EaseOutBounce bounces at the end, e.g. a dropped coin landing.

func EaseOutCubic

func EaseOutCubic(t float32) float32

EaseOutCubic is a steeper EaseOutQuad.

func EaseOutElastic

func EaseOutElastic(t float32) float32

EaseOutElastic is a springy overshoot, e.g. a damage number that wobbles in.

func EaseOutExpo

func EaseOutExpo(t float32) float32

EaseOutExpo decelerates exponentially.

func EaseOutQuad

func EaseOutQuad(t float32) float32

EaseOutQuad decelerates, e.g. a menu sliding in.

func EaseOutSine

func EaseOutSine(t float32) float32

EaseOutSine is a gentle deceleration along a quarter sine.

func Exp

func Exp(x float32) float32

Exp returns e to the power x, e.g. for decay curves in custom smoothing.

func ExpFactor

func ExpFactor(dt, tau float32) float32

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 Floor

func Floor(x float32) float32

Floor rounds x down, e.g. tileX := Floor(px / 16).

func FloorDiv

func FloorDiv(a, b int) int

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 Fract

func Fract(x float32) float32

Fract returns x - Floor(x), in [0, 1), e.g. a looping phase for a blinking cursor.

func Hash32

func Hash32(x uint32) uint32

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

func HashFloat(x uint32) float32

HashFloat returns Hash32(x) mapped to [0, 1), e.g. a stable random grass tint per cell.

func Hypot

func Hypot(x, y float32) float32

Hypot returns Sqrt(x*x + y*y) without intermediate overflow, e.g. the distance from two deltas.

func InvLerp

func InvLerp(a, b, v float32) float32

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

func IsFinite(x float32) bool

IsFinite reports whether x is neither NaN nor an infinity, e.g. to guard a physics step against a bad division.

func Lerp

func Lerp(a, b, t float32) float32

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

func LerpAngle(a, b, t float32) float32

LerpAngle interpolates from a to b along the shortest arc, e.g. a ship turning smoothly across the ±Pi seam.

func Mod

func Mod(x, y float32) float32

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

func ModInt(a, b int) int

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

func NearlyEqual(a, b, eps float32) bool

NearlyEqual reports whether |a-b| <= eps, e.g. to snap a tween's end value in tests or logic.

func Noise1

func Noise1(seed uint32, x float32) float32

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

func Noise2(seed uint32, x, y float32) float32

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

func Pick[T any](r *Rand, s []T) T

Pick returns a random element of s, e.g. a footstep sound from a set. An empty s gives the zero value.

func PingPong

func PingPong(t, length float32) float32

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

func PointInPolygon(p Vec2, poly []Vec2) bool

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

func PolygonArea(poly []Vec2) float32

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 Pow

func Pow(x, y float32) float32

Pow returns x to the power y, e.g. falloff := Pow(1-d/r, 2) for explosion damage.

func Rad

func Rad(deg float32) float32

Rad converts degrees to radians, e.g. t.Rot = Rad(45) for a value typed in the editor.

func Remap

func Remap(v, a0, a1, b0, b1 float32) float32

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

func RemapClamped(v, a0, a1, b0, b1 float32) float32

RemapClamped is Remap with the fraction limited to 0..1, e.g. an engine volume that never exceeds its maximum.

func Repeat

func Repeat(t, length float32) float32

Repeat loops t into [0, length), e.g. a looping animation time. A length of 0 or less returns 0.

func Round

func Round(x float32) float32

Round rounds x to the nearest integer, halves away from zero, e.g. to pixel-snap a sprite: Round(pos.X).

func SegmentDist

func SegmentDist(p, a, b Vec2) float32

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 Shuffle

func Shuffle[T any](r *Rand, s []T)

Shuffle reorders s in place, e.g. a deck of cards or a bag of tetrominoes.

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

func SignEps(x, eps float32) float32

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

func Sin(x float32) float32

Sin returns the float32 sine of x radians, e.g. bob := Sin(time*4) * 2 for a hovering pickup.

func Sincos

func Sincos(x float32) (s, c float32)

Sincos returns the sine and cosine of x radians, e.g. to build the rotation of a spinning saw blade.

func SmoothDamp

func SmoothDamp(x, target float32, vel *float32, smoothTime, maxSpeed, dt float32) float32

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

func SmoothStep(e0, e1, x float32) float32

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

func SmootherStep(e0, e1, x float32) float32

SmootherStep is SmoothStep with Perlin's quintic, flat in its first and second derivative at both ends, e.g. a softer vignette.

func Snap

func Snap(x, step float32) float32

Snap returns the nearest multiple of step, e.g. an editor grid: Snap(mouse.X, 8). A step of 0 returns x.

func SnapFloor

func SnapFloor(x, step float32) float32

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

func SpringStep(x, v, target, dt, freq, zeta float32) (float32, float32)

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 Sq

func Sq(x float32) float32

Sq returns x*x, e.g. to compare distances without Sqrt: d2 < Sq(radius).

func Sqrt

func Sqrt(x float32) float32

Sqrt returns the float32 square root of x, e.g. speed := Sqrt(vx*vx + vy*vy).

func Step

func Step(edge, x float32) float32

Step returns 0 for x below edge and 1 from edge on, e.g. onGround := Step(groundY, feetY).

func Trunc

func Trunc(x float32) float32

Trunc drops the fraction of x, e.g. whole seconds shown on a timer.

func Wrap

func Wrap[T Number](x, lo, hi T) T

Wrap returns x wrapped into [lo, hi), e.g. pos.X = Wrap(pos.X, 0, screenW) for Asteroids-style screen edges. If hi <= lo it returns lo.

func WrapAngle

func WrapAngle(a float32) float32

WrapAngle returns a wrapped into (-Pi, Pi], e.g. to keep an accumulating rotation small.

Types

type Circle

type Circle struct {
	C Vec2
	R float32
}

Circle is a circle with center C and radius R, e.g. a blast radius or a round trigger.

type EaseFunc

type EaseFunc func(t float32) float32

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.

func Mirror

func Mirror(f EaseFunc) EaseFunc

Mirror returns an InOut curve from an In curve: f on the first half and its reverse on the second, e.g. a custom symmetric fade.

func Reverse

func Reverse(f EaseFunc) EaseFunc

Reverse returns the curve played backwards, 1 - f(1-t), e.g. an Out curve from a custom In curve.

type Hit

type Hit struct {
	T      float32
	Point  Vec2
	Normal Vec2
}

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

func RayCircle(from, d Vec2, c Circle) (Hit, bool)

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

func RayRect(from, d Vec2, r Rect) (Hit, bool)

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

func RaySegment(from, d, a, b Vec2) (Hit, bool)

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

func SweepRect(moving Rect, d Vec2, still Rect) (Hit, bool)

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

func Rotation(a float32) Mat3

Rotation returns the matrix that turns by a radians (clockwise on screen), e.g. a rotating turret's local frame.

func Scaling

func Scaling(s Vec2) Mat3

Scaling returns the matrix that scales per axis, e.g. Scaling(V(-1, 1)) flips a sprite horizontally.

func TRS

func TRS(pos Vec2, rot float32, scale Vec2) Mat3

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

func Translation(d Vec2) Mat3

Translation returns the matrix that moves by d, e.g. the parent offset of a child sprite.

func (Mat3) Apply

func (m Mat3) Apply(p Vec2) Vec2

Apply transforms the point p, e.g. the world position of a hand socket.

func (Mat3) ApplyDir

func (m Mat3) ApplyDir(v Vec2) Vec2

ApplyDir transforms the direction v, ignoring the translation, e.g. to rotate a local velocity into world space.

func (Mat3) ApplyRect

func (m Mat3) ApplyRect(r Rect) Rect

ApplyRect returns the axis-aligned bounds of r after the transform, e.g. to cull a rotated sprite.

func (Mat3) Inverse

func (m Mat3) Inverse() (Mat3, bool)

Inverse returns the matrix that undoes m, e.g. to put the mouse into an entity's local space. It reports false, with the identity, when m is singular (a scale of 0).

func (Mat3) Mul

func (m Mat3) Mul(n Mat3) Mat3

Mul returns the matrix that applies n first and then m, e.g. world := parent.Mul(local) for a weapon attached to its owner.

type Number

type Number interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~float32 | ~float64
}

Number is the set of signed numeric types the generic helpers accept.

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

func NewRand(seed uint64) *Rand

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

func (r *Rand) Angle() float32

Angle returns a uniform angle in [0, Tau), e.g. for debris flying in any direction.

func (*Rand) Chance

func (r *Rand) Chance(p float32) bool

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

func (r *Rand) Float() float32

Float returns a uniform number in [0, 1), e.g. if r.Float() < 0.1 { dropLoot() }.

func (*Rand) Gauss

func (r *Rand) Gauss(mean, stddev float32) float32

Gauss returns a normally distributed number, e.g. natural-looking damage rolls. A negative stddev behaves like its absolute value.

func (*Rand) InCircle

func (r *Rand) InCircle(radius float32) Vec2

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

func (r *Rand) InRect(rc Rect) Vec2

InRect returns a uniform point in rc, e.g. rain drops across the screen.

func (*Rand) IntRange

func (r *Rand) IntRange(lo, hi int) int

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

func (r *Rand) OnCircle(radius float32) Vec2

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

func (r *Rand) Range(lo, hi float32) float32

Range returns a uniform number in [lo, hi), e.g. a spawn delay of r.Range(0.5, 1.5) seconds.

func (*Rand) Seed

func (r *Rand) Seed(seed uint64)

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

func (r *Rand) Sign() float32

Sign returns -1 or 1, e.g. the random initial direction of a bat.

func (*Rand) Spread

func (r *Rand) Spread(center, spread float32) float32

Spread returns center ± spread, uniformly, e.g. Spread(aim, Rad(5)) for weapon spread.

func (*Rand) UnitVec

func (r *Rand) UnitVec() Vec2

UnitVec returns a random unit vector, e.g. a scattered shotgun pellet.

func (*Rand) Weighted

func (r *Rand) Weighted(weights []float32) int

Weighted returns an index chosen with probability proportional to its weight, e.g. a loot table of 70, 25 and 5. Negative weights count as 0. It returns -1 when no weight is positive.

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

func PolygonBounds(poly []Vec2) Rect

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

func RectCentered(c, size Vec2) Rect

RectCentered returns the rectangle of the given size around c, e.g. a hitbox around the player's feet.

func RectPoints

func RectPoints(a, b Vec2) Rect

RectPoints returns the rectangle spanning two points in any order, e.g. a mouse drag selection.

func RectXYWH

func RectXYWH(x, y, w, h float32) Rect

RectXYWH returns the rectangle with corner (x, y) and size (w, h), e.g. a Tiled object's box.

func (Rect) Center

func (r Rect) Center() Vec2

Center returns the middle point, e.g. to spawn loot at a chest's center.

func (Rect) ClampCenter

func (r Rect) ClampCenter(c, half Vec2) Vec2

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

func (r Rect) ClampPoint(p Vec2) Vec2

ClampPoint returns p clamped into r, e.g. to keep the player inside the arena. An empty r returns Min.

func (Rect) ClosestPoint

func (r Rect) ClosestPoint(p Vec2) Vec2

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

func (r Rect) Contains(p Vec2) bool

Contains reports whether p lies inside r (Min in, Max out), e.g. a button hover test.

func (Rect) ContainsRect

func (r Rect) ContainsRect(o Rect) bool

ContainsRect reports whether o lies fully inside r, e.g. "is the room fully on screen".

func (Rect) Corners

func (r Rect) Corners() [4]Vec2

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

func (r Rect) Empty() bool

Empty reports whether r has no area (width or height of 0 or less), e.g. to skip drawing a collapsed panel.

func (Rect) Extend

func (r Rect) Extend(p Vec2) Rect

Extend returns r grown to include p, e.g. to build level bounds from points.

func (Rect) Grow

func (r Rect) Grow(m float32) Rect

Grow returns r expanded by m on every side; a negative m shrinks it, e.g. a pickup radius margin.

func (Rect) GrowV

func (r Rect) GrowV(m Vec2) Rect

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

func (r Rect) H() float32

H returns the height.

func (Rect) HalfSize

func (r Rect) HalfSize() Vec2

HalfSize returns Size / 2, e.g. the extents for an AABB collision test.

func (Rect) Intersect

func (r Rect) Intersect(o Rect) Rect

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

func (r Rect) Lerp(o Rect, t float32) Rect

Lerp blends the corners of two rectangles, e.g. an animated selection frame.

func (Rect) Overlaps

func (r Rect) Overlaps(o Rect) bool

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

func (r Rect) Penetration(o Rect) Vec2

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.

func (Rect) Size

func (r Rect) Size() Vec2

Size returns Max - Min, e.g. to scale a background to fill r.

func (Rect) Translate

func (r Rect) Translate(d Vec2) Rect

Translate returns r moved by d, e.g. a hitbox that follows its entity.

func (Rect) Union

func (r Rect) Union(o Rect) Rect

Union returns the smallest rectangle holding both, e.g. the bounds of all selected objects.

func (Rect) W

func (r Rect) W() float32

W returns the width, e.g. to center text: x := r.Min.X + (r.W()-textW)/2.

type Vec2

type Vec2 struct {
	X float32
	Y float32
}

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

func CirclePenetration(a, b Circle) (Vec2, bool)

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

func ClosestOnSegment(p, a, b Vec2) Vec2

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

func FromAngle(a float32) Vec2

FromAngle returns the unit vector at angle a, e.g. bullet.Vel = FromAngle(aim).Mul(speed).

func FromPolar

func FromPolar(a, r float32) Vec2

FromPolar returns r·FromAngle(a), e.g. the offset of an orbiting shield orb.

func SegmentsIntersect

func SegmentsIntersect(a, b, c, d Vec2) (Vec2, bool)

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 Splat

func Splat(s float32) Vec2

Splat returns V(s, s), e.g. Scale = Splat(2) to double a sprite.

func V

func V(x, y float32) Vec2

V returns the vector (x, y), e.g. t.Pos = xmath.V(100, 40).

func (Vec2) Abs

func (v Vec2) Abs() Vec2

Abs returns the per-axis absolute value, e.g. half extents from a signed size.

func (Vec2) Add

func (v Vec2) Add(o Vec2) Vec2

Add returns v + o, e.g. pos = pos.Add(vel.Mul(dt)).

func (Vec2) Angle

func (v Vec2) Angle() float32

Angle returns the angle of v (Atan2), e.g. t.Rot = vel.Angle() so an arrow points where it flies.

func (Vec2) AngleTo

func (v Vec2) AngleTo(o Vec2) float32

AngleTo returns the signed angle from v to o in (-Pi, Pi], e.g. how far a homing missile must turn.

func (Vec2) Approach

func (v Vec2) Approach(target Vec2, step float32) Vec2

Approach moves v toward target by at most step, e.g. an elevator to the next floor.

func (Vec2) Clamp

func (v Vec2) Clamp(lo, hi Vec2) Vec2

Clamp limits each axis to [lo, hi], e.g. to keep the cursor inside the screen.

func (Vec2) ClampLen

func (v Vec2) ClampLen(limit float32) Vec2

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

func (v Vec2) Cross(o Vec2) float32

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

func (v Vec2) Damp(target Vec2, halfLife, dt float32) Vec2

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

func (v Vec2) Dist(o Vec2) float32

Dist returns the distance to o, e.g. pickup when player.Dist(coin) < 8.

func (Vec2) DistSq

func (v Vec2) DistSq(o Vec2) float32

DistSq returns the squared distance to o, e.g. a nearest-enemy search without square roots.

func (Vec2) Div

func (v Vec2) Div(f float32) Vec2

Div returns v divided by f, e.g. the average of points: sum.Div(n).

func (Vec2) DivV

func (v Vec2) DivV(o Vec2) Vec2

DivV returns the per-axis quotient, e.g. world to cell: p.DivV(cellSize).

func (Vec2) Dot

func (v Vec2) Dot(o Vec2) float32

Dot returns the dot product, e.g. facing.Dot(toTarget) > 0 means in front.

func (Vec2) Floor

func (v Vec2) Floor() Vec2

Floor rounds each axis down, e.g. to pixel-snap the camera.

func (Vec2) IsZero

func (v Vec2) IsZero() bool

IsZero reports whether v is the zero vector, e.g. if input.IsZero() { anim = idle }.

func (Vec2) Len

func (v Vec2) Len() float32

Len returns the length, e.g. if vel.Len() > maxSpeed { ... }.

func (Vec2) LenSq

func (v Vec2) LenSq() float32

LenSq returns the squared length without a square root, e.g. d.LenSq() < Sq(aggroRadius).

func (Vec2) Lerp

func (v Vec2) Lerp(o Vec2, t float32) Vec2

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

func (v Vec2) Max(o Vec2) Vec2

Max returns the per-axis maximum, e.g. the upper corner of a drag box.

func (Vec2) Min

func (v Vec2) Min(o Vec2) Vec2

Min returns the per-axis minimum, e.g. the lower corner of a drag box.

func (Vec2) Mul

func (v Vec2) Mul(f float32) Vec2

Mul returns v scaled by f, e.g. knockback := dir.Mul(200).

func (Vec2) MulV

func (v Vec2) MulV(o Vec2) Vec2

MulV returns the per-axis product, e.g. size.MulV(scale) for a scaled box.

func (Vec2) NearlyEqual

func (v Vec2) NearlyEqual(o Vec2, eps float32) bool

NearlyEqual reports whether both axes differ by at most eps, e.g. "arrived at the waypoint".

func (Vec2) Neg

func (v Vec2) Neg() Vec2

Neg returns -v, e.g. to bounce back: vel = vel.Neg().

func (Vec2) Norm

func (v Vec2) Norm() Vec2

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

func (v Vec2) NormOk() (Vec2, bool)

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

func (v Vec2) Perp() Vec2

Perp returns v turned 90° clockwise on screen, e.g. the strafe direction from a facing vector.

func (Vec2) Project

func (v Vec2) Project(onto Vec2) Vec2

Project returns the component of v along onto (zero if onto is the zero vector), e.g. speed along a slope.

func (Vec2) Reflect

func (v Vec2) Reflect(n Vec2) Vec2

Reflect mirrors v off a surface with unit normal n, e.g. ball.Vel = ball.Vel.Reflect(hit.Normal).

func (Vec2) Reject

func (v Vec2) Reject(onto Vec2) Vec2

Reject returns v minus its projection onto onto, e.g. to slide along a wall: vel.Reject(wallNormal).

func (Vec2) Rotate

func (v Vec2) Rotate(a float32) Vec2

Rotate returns v turned by a radians, clockwise on screen, e.g. muzzle := t.Pos.Add(gunOffset.Rotate(t.Rot)).

func (Vec2) Round

func (v Vec2) Round() Vec2

Round rounds each axis to the nearest integer, e.g. for crisp pixel-art sprite positions.

func (Vec2) Snap

func (v Vec2) Snap(step Vec2) Vec2

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

func (v Vec2) Spring(vel *Vec2, target Vec2, dt, freq, zeta float32) Vec2

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.

func (Vec2) Sub

func (v Vec2) Sub(o Vec2) Vec2

Sub returns v - o, e.g. toPlayer := player.Sub(enemy).

func (Vec2) WithLen

func (v Vec2) WithLen(l float32) Vec2

WithLen returns v's direction with length l; the zero vector stays zero, e.g. dash := input.WithLen(dashSpeed).

func (Vec2) XY

func (v Vec2) XY() (float32, float32)

XY returns both coordinates, e.g. x, y := p.XY() before an API that takes two numbers.

Jump to

Keyboard shortcuts

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