GitHub快速開始
2D 擴充與系統

math2d

game/math2d 提供在 NSGo 遊戲包之間共享的輕量、零堆分配 2D 值型別:Vec2 向量、軸對齊矩形 Rect、圓 Circle 以及 3×2 仿射變換 Affine,並支援與 NSGo core 幾何型別之間的無損互轉。

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

所有座標均採用 float32,與 core.Points、core.Point、core.Size、core.Bounds 和 core.Drawing 保持一致。角度單位為弧度,從 +X 轉向 +Y(在 NSGo 向下為 +Y 的畫布座標系中即順時針方向)。

向量(Vec2)

可使用 V2(x, y)、Zero()、One()、UnitX()、UnitY() 或 FromAngle(rad) 構造向量,並與 NSGo core 無損轉換:

pos := math2d.FromPoint(pointerPos)
dir := target.Sub(pos).Normalize()
vel := dir.Scale(220).ClampLen(240)
next := pos.Add(vel.Scale(float32(dt.Seconds())))

// 無損轉回 NSGo core 型別:
pt := next.Point()
sz := math2d.V2(32, 48).Size()
_, _ = pt, sz
方法 作用
Add、Sub、Mul、Div、Scale、Neg 分量四則運算與標量縮放。
Dot、Cross、Len、LenSq、Dist、DistSq 點積、2D 標量叉積(X*o.Y - Y*o.X)、長度與距離。
Normalize、ClampLen 單位化(零向量返回 Zero())與模長上限鉗制。
Lerp、MoveTowards 線性插值與固定步長朝目標逼近。
Angle、Rotate、Perp、Reflect、Project 極角、弧度旋轉、90° 垂線、反射與投影。
Min、Max、Clamp、ApproxEqual 分量上下界與誤差容限比較。

矩形與圓(Rect、Circle)

Rect 儲存 {X, Y, W, H},包含判定採用半開區間 [X, X+W) × [Y, Y+H),與 core.Bounds 一致。當 W <= 0、H <= 0 或任意欄位為 NaN 時視為空矩形。

box := math2d.FromCenter(math2d.V2(160, 90), math2d.V2(40, 24))
expanded := box.Expand(4)

if hit, ok := expanded.Intersection(math2d.FromBounds(viewBounds)); ok {
	coreRect := hit.Bounds()
	_ = coreRect
}

blast := math2d.Circle{Center: math2d.V2(180, 96), Radius: 36}
if blast.OverlapsRect(box) {
	closest := box.ClosestPoint(blast.Center)
	_ = closest
}
  • 用 FromBounds(b)、FromCenter(center, size) 或 FromMinMax(lo, hi) 建立矩形,用 r.Bounds() 轉回 core.Bounds。
  • 矩形查詢涵蓋 Min、Max、Center、Size、Normalized、Empty、Contains、ContainsRect、Overlaps、Intersection、Union、Expand、Translate、ClampPoint 與 ClosestPoint。
  • 圓查詢涵蓋 Contains、Overlaps、OverlapsRect、Bounds、Translate 與 ApproxEqual。

2D 仿射變換(Affine)

Affine 以 {A, B, C, D, Tx, Ty} 的列序儲存 3×2 矩陣,與 core.Drawing.Transform 和 core.Matrix3D.Affine(Canvas 2D / SVG matrix(a, b, c, d, e, f))完全一致:

// 先縮放、再旋轉、最後平移:
m := math2d.TRS(math2d.V2(120, 80), 0.35, math2d.V2(2, 2))
worldPt := m.TransformPoint(math2d.V2(8, 0))
worldBox := m.TransformRect(localBounds)

// 求逆以把螢幕/世界座標映回區域性空間:
if inv, ok := m.Invert(); ok {
	localPt := inv.TransformPoint(worldPt)
	_ = localPt
}

// 與 core.Matrix3D 無損互轉:
mat3d := m.ToCore()
back, ok := math2d.FromCore(mat3d)
_, _, _ = worldBox, back, ok

可使用 Identity()、Translate(x, y)、Scale(sx, sy)、Rotate(rad)、RotateAround(rad, cx, cy)、TRS(pos, rot, scale) 與 m.Mul(other)(自右向左生效:先應用 other,再應用 m)。TransformVector(v) 僅應用線性部分而忽略平移。

編輯此頁