math2d

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 2 Imported by: 6 modules, 5 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 math2d provides small, zero-allocation 2D value types shared by game packages: vectors (Vec2), axis-aligned rectangles (Rect), circles (Circle), and 3×2 affine transforms (Affine).

Coordinates use float32 to match NSGo's core geometry (core.Points, core.Point, core.Size, core.Bounds) and core.Drawing, with lossless conversions to and from core. Angles are in radians, turning from +X toward +Y (clockwise in NSGo's Y-down drawing coordinates).

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Affine

type Affine struct {
	A, B   float32
	C, D   float32
	Tx, Ty float32
}

Affine is a 2D 3×2 affine transform stored in the same column order as core.Drawing.Transform and core.Matrix3D.Affine (Canvas 2D / SVG matrix(a, b, c, d, e, f)):

[ A  C  Tx ] [ x ]   [ A*x + C*y + Tx ]
[ B  D  Ty ] [ y ] = [ B*x + D*y + Ty ]
[ 0  0  1  ] [ 1 ]   [ 1              ]

The zero value maps every point to (0, 0); use Identity for the no-op transform.

Example

An Affine composes translation, rotation and scale; Invert maps a world point back into the local space, as picking under a camera does.

package main

import (
	"fmt"
	"math"
	"strconv"

	"github.com/nsgo-dev/game/pkg/math2d"
)

// show prints v to two decimals, writing a rounded negative zero as 0.
func show(v math2d.Vec2) string {
	num := func(f float32) string {
		s := strconv.FormatFloat(float64(f), 'f', 2, 32)
		if s == "-0.00" {
			s = "0.00"
		}
		return s
	}
	return "(" + num(v.X) + ", " + num(v.Y) + ")"
}

func main() {
	m := math2d.TRS(math2d.V2(100, 50), math.Pi/2, math2d.V2(2, 2))
	world := m.TransformPoint(math2d.V2(10, 0))
	fmt.Println(show(world))
	inv, ok := m.Invert()
	fmt.Println(show(inv.TransformPoint(world)), ok)
}
Output:
(100.00, 70.00)
(10.00, 0.00) true

func FromCore

func FromCore(m core.Matrix3D) (Affine, bool)

FromCore extracts a 2D Affine from an NSGo core.Matrix3D. It returns (Affine{}, false) if m is not a pure 2D affine transform.

func Identity

func Identity() Affine

Identity returns the identity affine transform.

func Rotate

func Rotate(rad float32) Affine

Rotate returns a rotation transform by rad radians from +X toward +Y.

func RotateAround

func RotateAround(rad, cx, cy float32) Affine

RotateAround returns a rotation transform by rad radians about pivot (cx, cy).

func Scale

func Scale(sx, sy float32) Affine

Scale returns a pure scaling transform by (sx, sy).

func TRS

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

TRS returns a transform that scales by scale, rotates by rot radians, and translates by pos: Translate(pos.X, pos.Y).Mul(Rotate(rot)).Mul(Scale(scale.X, scale.Y)).

func Translate

func Translate(x, y float32) Affine

Translate returns a pure translation transform by (x, y).

func (Affine) ApproxEqual

func (m Affine) ApproxEqual(o Affine, eps float32) bool

ApproxEqual reports whether each element of m and o differs by at most eps. It returns false if eps < 0 or any value is NaN.

func (Affine) Invert

func (m Affine) Invert() (Affine, bool)

Invert returns the inverse of m, or (Affine{}, false) if m is singular, degenerate, or contains non-finite values.

func (Affine) Mul

func (m Affine) Mul(other Affine) Affine

Mul returns the matrix product m * other (other applied first, then m).

func (Affine) ToCore

func (m Affine) ToCore() core.Matrix3D

ToCore converts m to an NSGo core.Matrix3D losslessly.

func (Affine) TransformPoint

func (m Affine) TransformPoint(p Vec2) Vec2

TransformPoint applies m (including translation) to point p.

func (Affine) TransformRect

func (m Affine) TransformRect(r Rect) Rect

TransformRect transforms the four corners of r by m and returns the tightest axis-aligned bounding Rect enclosing them. It returns the zero Rect if r is empty.

func (Affine) TransformVector

func (m Affine) TransformVector(v Vec2) Vec2

TransformVector applies only the linear part of m (ignoring translation) to vector v.

type Circle

type Circle struct {
	Center Vec2
	Radius float32
}

Circle is a 2D circle defined by its Center and Radius.

A circle with Radius <= 0 (or NaN) is empty and contains or overlaps nothing.

Example

Circle tests overlaps with other circles and with rectangles.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/math2d"
)

func main() {
	bullet := math2d.Circle{Center: math2d.V2(5, 5), Radius: 1}
	enemy := math2d.Circle{Center: math2d.V2(6.5, 5), Radius: 1}
	wall := math2d.Rect{X: 10, Y: 0, W: 2, H: 10}
	fmt.Println(bullet.Overlaps(enemy), bullet.OverlapsRect(wall), bullet.Bounds())
}
Output:
true false {4 4 2 2}

func (Circle) ApproxEqual

func (c Circle) ApproxEqual(o Circle, eps float32) bool

ApproxEqual reports whether c and o have centers and radii within eps. It returns false if eps < 0 or any value is NaN.

func (Circle) Bounds

func (c Circle) Bounds() Rect

Bounds returns the axis-aligned bounding Rect of c, or the zero Rect if Radius < 0 or any component is NaN.

func (Circle) Contains

func (c Circle) Contains(p Vec2) bool

Contains reports whether p lies inside or on the boundary of c.

func (Circle) Overlaps

func (c Circle) Overlaps(o Circle) bool

Overlaps reports whether c and o intersect (including tangent contact).

func (Circle) OverlapsRect

func (c Circle) OverlapsRect(r Rect) bool

OverlapsRect reports whether c and non-empty rectangle r intersect (including boundary contact).

func (Circle) Translate

func (c Circle) Translate(v Vec2) Circle

Translate returns c shifted by v.

type Rect

type Rect struct {
	X, Y, W, H float32
}

Rect is an axis-aligned 2D rectangle given by its origin (X, Y) and size (W, H).

A rectangle with W <= 0 or H <= 0 (or any NaN field) is empty. Containment uses half-open intervals [X, X+W) × [Y, Y+H), matching NSGo's core.Bounds.

Example

Rect tests overlaps between axis-aligned boxes and clips one by another.

package main

import (
	"fmt"
	"strconv"

	"github.com/nsgo-dev/game/pkg/math2d"
)

// show prints v to two decimals, writing a rounded negative zero as 0.
func show(v math2d.Vec2) string {
	num := func(f float32) string {
		s := strconv.FormatFloat(float64(f), 'f', 2, 32)
		if s == "-0.00" {
			s = "0.00"
		}
		return s
	}
	return "(" + num(v.X) + ", " + num(v.Y) + ")"
}

func main() {
	player := math2d.Rect{X: 0, Y: 0, W: 10, H: 20}
	spike := math2d.FromCenter(math2d.V2(12, 10), math2d.V2(8, 8))
	fmt.Println(player.Overlaps(spike))
	hit, ok := player.Intersection(spike)
	fmt.Println(hit, ok)
	fmt.Println(show(player.ClosestPoint(math2d.V2(20, 25))))
}
Output:
true
{8 6 2 8} true
(10.00, 20.00)

func FromBounds

func FromBounds(b core.Bounds) Rect

FromBounds converts an NSGo core.Bounds to a Rect losslessly.

func FromCenter

func FromCenter(center, size Vec2) Rect

FromCenter returns a Rect centered at center with the given size.

func FromMinMax

func FromMinMax(lo, hi Vec2) Rect

FromMinMax returns a Rect spanning from lo to hi. If lo has a component greater than hi, the resulting Rect has negative W or H; call Normalized to flip negative extents.

func (Rect) ApproxEqual

func (r Rect) ApproxEqual(o Rect, eps float32) bool

ApproxEqual reports whether each field of r and o differs by at most eps. It returns false if eps < 0 or any value is NaN.

func (Rect) Bounds

func (r Rect) Bounds() core.Bounds

Bounds converts r to an NSGo core.Bounds losslessly.

func (Rect) Center

func (r Rect) Center() Vec2

Center returns the midpoint of r.

func (Rect) ClampPoint

func (r Rect) ClampPoint(p Vec2) Vec2

ClampPoint clamps p to the closed region spanned by r. Negative W or H is normalized before clamping.

func (Rect) ClosestPoint

func (r Rect) ClosestPoint(p Vec2) Vec2

ClosestPoint returns the point in the closed rectangle r closest to p. For points inside r, it returns p; for points outside, it returns the nearest point on r's perimeter.

func (Rect) Contains

func (r Rect) Contains(p Vec2) bool

Contains reports whether p lies within r's half-open bounds [X, X+W) × [Y, Y+H).

func (Rect) ContainsRect

func (r Rect) ContainsRect(o Rect) bool

ContainsRect reports whether non-empty rectangle o lies completely inside non-empty r. It returns false if either rectangle is empty.

func (Rect) Empty

func (r Rect) Empty() bool

Empty reports whether r has zero or negative area or contains any NaN component.

func (Rect) Expand

func (r Rect) Expand(margin float32) Rect

Expand returns r expanded outward by margin on all four sides (negative shrinks).

func (Rect) Intersection

func (r Rect) Intersection(o Rect) (Rect, bool)

Intersection returns the overlapping region of r and o, or (Rect{}, false) if they do not overlap or either is empty.

func (Rect) Max

func (r Rect) Max() Vec2

Max returns the far corner (X+W, Y+H) of r.

func (Rect) Min

func (r Rect) Min() Vec2

Min returns the origin corner (X, Y) of r.

func (Rect) Normalized

func (r Rect) Normalized() Rect

Normalized returns an equivalent Rect with non-negative W and H, shifting X or Y when W or H is negative.

func (Rect) Overlaps

func (r Rect) Overlaps(o Rect) bool

Overlaps reports whether r and o have a non-empty intersection. Rectangles that touch only along an edge or corner do not overlap.

func (Rect) Size

func (r Rect) Size() Vec2

Size returns the dimensions (W, H) of r.

func (Rect) Translate

func (r Rect) Translate(v Vec2) Rect

Translate returns r shifted by v.

func (Rect) Union

func (r Rect) Union(o Rect) Rect

Union returns the smallest Rect containing both r and o. An empty rectangle acts as the identity element.

type Vec2

type Vec2 struct {
	X, Y float32
}

Vec2 is a 2D vector or point in float32 coordinates.

Example

Vec2 is a 2D vector for positions, velocities and directions.

package main

import (
	"fmt"
	"math"
	"strconv"

	"github.com/nsgo-dev/game/pkg/math2d"
)

// show prints v to two decimals, writing a rounded negative zero as 0.
func show(v math2d.Vec2) string {
	num := func(f float32) string {
		s := strconv.FormatFloat(float64(f), 'f', 2, 32)
		if s == "-0.00" {
			s = "0.00"
		}
		return s
	}
	return "(" + num(v.X) + ", " + num(v.Y) + ")"
}

func main() {
	pos := math2d.V2(0, 0)
	target := math2d.V2(3, 4)
	fmt.Println(pos.Dist(target), show(target.Sub(pos).Normalize()))
	fmt.Println(show(pos.MoveTowards(target, 2)))
	fmt.Println(show(math2d.V2(1, -1).Reflect(math2d.UnitY())))
	fmt.Println(show(math2d.UnitX().Rotate(math.Pi / 2)))
}
Output:
5 (0.60, 0.80)
(1.20, 1.60)
(1.00, 1.00)
(0.00, 1.00)

func FromAngle

func FromAngle(rad float32) Vec2

FromAngle returns the unit vector at rad radians from +X toward +Y.

func FromPoint

func FromPoint(p core.Point) Vec2

FromPoint converts an NSGo core.Point to a Vec2 losslessly.

func FromSize

func FromSize(s core.Size) Vec2

FromSize converts an NSGo core.Size to a Vec2 losslessly.

func One

func One() Vec2

One returns the vector (1, 1).

func UnitX

func UnitX() Vec2

UnitX returns the positive X unit vector (1, 0).

func UnitY

func UnitY() Vec2

UnitY returns the positive Y unit vector (0, 1).

func V2

func V2(x, y float32) Vec2

V2 returns Vec2{X: x, Y: y}.

func Zero

func Zero() Vec2

Zero returns the zero vector (0, 0).

func (Vec2) Add

func (v Vec2) Add(o Vec2) Vec2

Add returns v + o.

func (Vec2) Angle

func (v Vec2) Angle() float32

Angle returns the angle of v in radians in [-π, π] from +X toward +Y.

func (Vec2) ApproxEqual

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

ApproxEqual reports whether each component of v and o differs by at most eps. It returns false if eps < 0 or any value is NaN.

func (Vec2) Clamp

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

Clamp clamps each component of v to [lo, hi].

func (Vec2) ClampLen

func (v Vec2) ClampLen(maxLen float32) Vec2

ClampLen returns v scaled down so its length does not exceed maxLen. If maxLen <= 0 or NaN, or v has NaN or infinite length, it returns the zero vector.

func (Vec2) Cross

func (v Vec2) Cross(o Vec2) float32

Cross returns the 2D scalar cross product (v.X*o.Y - v.Y*o.X).

func (Vec2) Dist

func (v Vec2) Dist(o Vec2) float32

Dist returns the Euclidean distance between v and o.

func (Vec2) DistSq

func (v Vec2) DistSq(o Vec2) float32

DistSq returns the squared distance between v and o.

func (Vec2) Div

func (v Vec2) Div(o Vec2) Vec2

Div returns the component-wise quotient of v divided by o.

func (Vec2) Dot

func (v Vec2) Dot(o Vec2) float32

Dot returns the dot product of v and o.

func (Vec2) Len

func (v Vec2) Len() float32

Len returns the Euclidean length of v.

func (Vec2) LenSq

func (v Vec2) LenSq() float32

LenSq returns the squared length of v.

func (Vec2) Lerp

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

Lerp linearly interpolates between v (at t=0) and o (at t=1).

func (Vec2) Max

func (v Vec2) Max(o Vec2) Vec2

Max returns the component-wise maximum of v and o.

func (Vec2) Min

func (v Vec2) Min(o Vec2) Vec2

Min returns the component-wise minimum of v and o.

func (Vec2) MoveTowards

func (v Vec2) MoveTowards(target Vec2, maxDelta float32) Vec2

MoveTowards moves v toward target by at most maxDelta without overshooting. If maxDelta <= 0 or NaN, or the distance is NaN, it returns v unchanged.

func (Vec2) Mul

func (v Vec2) Mul(o Vec2) Vec2

Mul returns the component-wise product of v and o.

func (Vec2) Neg

func (v Vec2) Neg() Vec2

Neg returns -v.

func (Vec2) Normalize

func (v Vec2) Normalize() Vec2

Normalize returns a unit vector in the direction of v. If v has zero length, NaN, or infinite length, it returns the zero vector.

func (Vec2) Perp

func (v Vec2) Perp() Vec2

Perp returns v rotated by +π/2 radians: (-v.Y, v.X).

func (Vec2) Point

func (v Vec2) Point() core.Point

Point converts v to an NSGo core.Point losslessly.

func (Vec2) Project

func (v Vec2) Project(onto Vec2) Vec2

Project returns the orthogonal projection of v onto onto. If onto has zero length, NaN, or infinite length, it returns the zero vector.

func (Vec2) Reflect

func (v Vec2) Reflect(normal Vec2) Vec2

Reflect returns v reflected across a surface with unit normal n.

func (Vec2) Rotate

func (v Vec2) Rotate(rad float32) Vec2

Rotate returns v rotated by rad radians from +X toward +Y.

func (Vec2) Scale

func (v Vec2) Scale(s float32) Vec2

Scale returns v multiplied by scalar s.

func (Vec2) Size

func (v Vec2) Size() core.Size

Size converts v to an NSGo core.Size losslessly.

func (Vec2) Sub

func (v Vec2) Sub(o Vec2) Vec2

Sub returns v - o.

Jump to

Keyboard shortcuts

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