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

spatial

game/spatial 無需逐個檢測即可找出某個區域附近或視口內的 2D 物件:2D 寬相空間索引(Hash、Quadtree)以及視口精靈裁剪(CullBatch、BatchCuller、Cull),預熱後零分配。物件池見 mempool。

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

2D 空間索引(Hash、Quadtree)

用 O(k) 的區域查詢、點查詢與重疊配對替代 O(n²) 暴力掃描。兩種索引都會複用內部桶/節點,並把結果寫入呼叫方傳入的切片,實現穩態查詢零分配:

grid := spatial.NewHash[uint32](64) // 單元格尺寸通常設為常見實體尺寸的 1~2 倍
grid.Insert(id, entityBounds)
grid.Update(id, movedBounds)

// 複用切片進行零分配區域查詢:
hits = grid.Query(cameraView, hits[:0])

// 去重後的寬相重疊實體對:
grid.QueryPairs(func(a, b uint32) {
	resolveNarrowPhase(a, b)
})

實體尺寸相近或世界無固定邊界時優先使用 Hash[ID];實體尺寸差異較大或集中在已知世界矩形內時使用 NewQuadtree[ID](worldBounds, maxItems, maxDepth)。兩者均提供 Insert、Update、Remove、Clear、Len、Query 與 QueryPoint。

視口裁剪(CullBatch、BatchCuller、Cull)

在向 core.Drawing 提交繪製命令前先剔除螢幕外的精靈:

var culler spatial.BatchCuller

// 在 Canvas.Draw 中:
culler.Draw(spriteBatch, cameraViewBounds, d)
  • BatchCuller.Draw(batch, view, d) 複用內部臨時 sprite.Batch,做到每幀零分配;若只需一次性便捷呼叫,可使用 spatial.CullBatch(batch, view, d)。
  • 使用 spatial.CullSprites(view, src, dst[:0])、spatial.SpriteBounds(s)、spatial.Intersects(a, b) 或泛型 spatial.Cull(view, items, boundsOf, dst[:0]) 裁剪任意 2D 世界物件。
編輯此頁