Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

data structures - What technique should be used to prune 2d collision checks?

From the outset, collision detection feels like it is an O(n^2) problem.

You have a bunch of objects and you need to check if each object is colliding with any of the other objects. However, I know that it is wildly ineffecient to check each object against all the other objects. Why do a relatively expensive collision check between two balls if they aren't even close to eachother?

Here is example of my simple program I'm working on:

alt text

If you have 1000 balls then if you went with the naive collision detection you would have 1000^2 collection checks (a million)! This collision checking has quickly become the bottleneck in my application. I need to implement some broad phase pruning.

What techniques should be used to prune collision checks when working with 2d - circular objects? I've read about QuadTrees, BSP, spatial hashing, etc but it is difficult to sort out what method is most appropriate to this use case.

Does anyone have any knowledge about what might work best?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wouldn't use QuadTrees or anything that complicated because you'll be constantly balancing and rebalancing trees as balls move between them. It would probably be more efficient just to have a grid - every time you move a ball, you can just calculate what grid cell it's in, and throw it in there if it's changed. And every time you need to make a collision check, you can just check balls whose center is either in your grid, or in adjacent ones if you're sufficiently close to the edge.

You can experiment with grid size to find the optimum. You may find it depends on how many balls you have.

I said this in a comment below, but I think it deserves to be part of the answer: Only do collsion detection when something moves, so you only have to check the moving thing against things in its grid square (and ajacent ones as mentioned above). That way if you get a pile of things in the bottom that aren't moving, pretty soon those objects are never checked for collision, because nothing is moving within their grid nor is anything moving into or out of their grid.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...