implement a spatial hashgrid in csharp

To implement a spatial hashgrid in C#, follow the steps below:

  1. Define a spatial hash cell class that contains a list of objects within that cell:
main.cs
public class SpatialHashCell<T>
{
    public List<T> objects = new List<T>();
}
80 chars
5 lines
  1. Define a SpatialHashGrid class that contains a dictionary of spatial hash cells, where the keys are the cell coordinates:
main.cs
public class SpatialHashGrid<T>
{
    private Dictionary<Vector2Int, SpatialHashCell<T>> grid = new Dictionary<Vector2Int, SpatialHashCell<T>>();

    public void AddObject(T obj, Vector2 position, float cellSize)
    {
        var cellCoord = new Vector2Int((int)(position.x / cellSize), (int)(position.y / cellSize));
        if (!grid.TryGetValue(cellCoord, out var cell))
        {
            cell = new SpatialHashCell<T>();
            grid.Add(cellCoord, cell);
        }
        cell.objects.Add(obj);
    }

    public List<T> GetObjects(Vector2 position, float cellSize, int radius)
    {
        var result = new List<T>();
        var cellCoord = new Vector2Int((int)(position.x / cellSize), (int)(position.y / cellSize));
        for (int x = -radius; x <= radius; x++)
        {
            for (int y = -radius; y <= radius; y++)
            {
                var offset = new Vector2Int(x, y);
                if (grid.TryGetValue(cellCoord + offset, out var cell))
                {
                    result.AddRange(cell.objects);
                }
            }
        }
        return result;
    }

    public void Clear()
    {
        grid.Clear();
    }
}
1184 chars
39 lines
  1. Use the SpatialHashGrid to add and retrieve objects based on their position:
main.cs
var hashGrid = new SpatialHashGrid<GameObject>();
hashGrid.AddObject(gameObject1, gameObject1.transform.position, 10);
hashGrid.AddObject(gameObject2, gameObject2.transform.position, 10);

var result = hashGrid.GetObjects(playerPosition, 10, 2);
foreach (var obj in result)
{
    // do something with the object
}
314 chars
10 lines

The code above creates a SpatialHashGrid that stores GameObjects, adds two GameObjects to the grid, and retrieves all objects within a radius of 2 cells around the player's position.

gistlibby LogSnag