Original Post
I need to implement efficient collision detection in a 2D game. Factors to consider: 1. I'd like to support a large number of dynamic entities, 1000-plus if possible (but I'll take what I can get). They all need to be tested each update. There will be very few (if any) static collidable objects. 2. Most entities can collide with most others (i.e., very few collision pairs that can be ignored). 3. The entities will often be clustered (with frequent collisions in a cluster), but the playing area is very large, so there will be great distances between clusters. 4. There won't be much variance in size of entities. There may be just a few entities larger than most, but I can implement these as a collection of smaller collision objects if necessary. 5. Most entities' actual collision primitive is a circle (and those that aren't can use a bounding circle for the initial test, of course). 6. Entities will be destroyed and new entities spawned frequently. Given these factors, what would be my best pruning/space partitioning/whatever scheme? I don't think a uniform grid is a good option, because of the very large area. It would take a lot of memory, with a very tiny percentage of the cells actually occupied. Or could I allocate cells as needed, keeping them (with their position) in a list? The list would need some fast hashing of some kind, to look up a cell by its x,y grid position. I've considered recursive dimensional clustering, but I think some of the clusters would be too large for that to be efficient. I'm thinking a quadtree might be my best option, but I have some questions about the best way to implement this. Again, due to the large area, the quadtree probably shouldn't be generated in its entirety up front. I'll have to add nodes as needed. Should I generate the tree from scratch each update? Or keep the tree persistent, and have entities remove and add themselves to nodes as they move, adding nodes on demand and removing empty ones? When an entity would straddle two or four child nodes, should I keep it in the parent node, or put it in both (or all four) child nodes? The problem I have with keeping it in the parent is that my main root node would have all the entities that straddle its two dividing axes, which could be a lot of entities (too many to reasonably do a n^2 test on). Any tips or insights on this will be greatly appreciated.