Spatial Hash Grid for Nearby Entity Queries in a 2D Game
Last updated: November 29, 2026
Quick Overview
Build a uniform-grid spatial hash that supports inserting, moving and removing entities by id and querying all entities within radius r of a point, returning ids sorted.
Unity
November 29, 20260
0
0 solved
Build a uniform-grid spatial hash that supports inserting, moving and removing entities by id and querying all entities within radius r of a point, returning ids sorted.
Gameplay programmers at Unity and its customers constantly need cheap proximity queries (AI perception, area damage, pickup radius) without running full physics. The interviewer checks bucketing math, handling negative coordinates, updates that only touch buckets when a cell changes, and an exact distance filter.
What the Interviewer Expects
- Map positions to cells with floor division so negatives work
- Query only the cells overlapping the bounding square of the circle
- Filter candidates by exact squared distance
- Move entities between buckets only when their cell changes
- Discuss choosing the cell size relative to typical query radius
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you pick cell size when query radii vary a lot?
- How would you extend this to 3D, and when would a BVH or octree win?
- How would you parallelize queries for thousands of agents in a job system?
- What happens with very large or sparse worlds and how does hashing help?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
API: upsert(id, x, y), remove(id), query(x, y, r) -> sorted ids. Many entities move every frame, so updates must be cheap; queries happen often with a radius similar to the cell size. Boundary r...
High-Level Design
Pick a cell size c. Cell key is (floor(x/c), floor(y/c)); math.floor rather than int() matters because int(-0.5) is 0, which would put points on both sides of the origin in the same column. ...