Search code examples
androidcollision-detection

How to detect shape collision - Android


I would like to detect collisions between shapes dynamically drawn on a canvas (SurfaceView) for an Android game.

I can easily use intersect method of Rect or RectF objects but the result is not very good (see picture below where I have a "false" detection).

enter image description here

I don't want to use Bitmap so it's impossible to use the "pixel perfect" method.

Do you know a way to do this for circle, rect, triangle and other basic shapes intersection ?

Thx for help ;)


Solution

  • For a good collision detection you have to create your own models behind. In those models you specify the conditions that two objects colide.

    For example, a circle is described by the center position and by the radius. A square is described by the left down corner and by the edge length.

    You don' t have to describe all possible poligons, you can use the so called bounding boxes, meaning that, for a complex random poligon you can use a square or whathever shape fits it best(also you can use multiple shapes for a single object).

    After you have the objects in mind you compute the condition that each one of them will colide with all other shapes including itself.

    In your example The sphere and the square colides if the distance between any corner of the square is greater than the circle's radius.

    Here you can read more http://devmag.org.za/2009/04/13/basic-collision-detection-in-2d-part-1/

    This problem can get very complex, keep it simple if you want something simple.