What's the best approach to 2D collision detection on iPhone?
Have worked on this collision detection problem and there seem to be three main approaches I could take:
-
The approach of sprites and masks. (And overlapping sprites and checking for a non-zero number in the received sprite pixel data).
-
Limiting circles, rectangles, or polygons. (Create one or more shapes that enclose the sprites and perform basic math tests to check overlaps.)
-
Use an existing sprite library.
The first approach, while it would be the way I would have done it in the old days of 16x16 sprite blocks, there just seems to be no easy way to get the individual pixel data of an image and / or the alpha channel inside quartz (or OPENGL for that matter). Bounding box overlap detection is easy, but then creating a third image from the overlap and then testing it for pixels is harder, and my inner sensitivity is that even if we could get it to work, it would be slow. Am I missing something here?
The second approach involves splitting our sprites into multiple polygons and testing them for overlap. The more polygons, the more accurate collision detection. The benefit is that it is fast and can be accurate. The downside is that sprite creation becomes more complex. that is, we have to create polygons for each sprite. For speed, the best approach is to create a polygon tree.
Third approach I'm not sure as it involves buying code (or using an open source license). I'm not sure if it is better to use a library or it will make life easier or give us a problem integrating this into our application.
In short, I prefer the polygon and tree approach, and would appreciate your views on this before I go and write a lot of code.
Best wishes
Dave
a source to share
Consider polygonizing your sprites. Maintain a polygon representation for your sprites "in the background" and perform collision testing with a polygonized version of your game world. This creates some overhead and added complexity, but is often very useful in terms of additional capabilities. (dynamic shadows, lighting effects, sprite-independent collision detection, many collision detection methods, polygonal intersection, etc.)
Otherwise, you're stuck with the pixel-based method you described, which is pretty good too. (ORing to overlap) You can just do it yourself or let OpenGL do it in the framebuffer. (I don't remember the calls, I think it's called z-masking (?), ... sorry. For small sprites it might even be slower ...) To optimize some of them, use binary space sharing techniques:
Square trees, for example, allow you to quickly find candidate sprites for collision testing. They are applicable both pixel and vertex based. Or just use BSPTrees.
Btw: I think pixel precision in collision detection is actually a good feature, I used a lot in Jump'n Runs. This may not apply to your game.
a source to share