Skip to content

Instantly share code, notes, and snippets.

@fogleman
Created December 20, 2016 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fogleman/8b1e45e174f7c3a03de25643d11eb9d9 to your computer and use it in GitHub Desktop.
Save fogleman/8b1e45e174f7c3a03de25643d11eb9d9 to your computer and use it in GitHub Desktop.
Simple Spatial Hash in Go
package path
type SpatialHash struct {
CellSize float64
Cells map[SpatialHashKey][]interface{}
}
type SpatialHashKey struct {
X, Y int
}
func NewSpatialHash(cellSize float64) *SpatialHash {
cells := make(map[SpatialHashKey][]interface{})
return &SpatialHash{cellSize, cells}
}
func (h *SpatialHash) KeyForPoint(point Vector) SpatialHashKey {
x := Round(point.X / h.CellSize)
y := Round(point.Y / h.CellSize)
return SpatialHashKey{x, y}
}
func (h *SpatialHash) Add(point Vector, data interface{}) {
key := h.KeyForPoint(point)
h.Cells[key] = append(h.Cells[key], data)
}
func (h *SpatialHash) Nearby(point Vector) []interface{} {
var result []interface{}
key := h.KeyForPoint(point)
for dx := -1; dx <= 1; dx++ {
for dy := -1; dy <= 1; dy++ {
k := SpatialHashKey{key.X + dx, key.Y + dy}
result = append(result, h.Cells[k]...)
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment