Search code examples
android2dcollision-detection

Collision detection with bitmaps on SurfaceView's canvas in Android


In Android I use a SurfaceView to display a simple 2D game. The bitmaps (.png) with alpha (representing the game objects) are drawn on the canvas.

Now I would like to do a simple but accurate collision detection. Checking whether these bitmaps are overlapping is quite easy.

But how do I check for collisions when these bitmaps have transparent areas? My challenge is detecting whether two balls collide or not. They fill up the whole bitmap in width and height both but in all four edges, there are transparent areas of course as it's a circle in a square.

What is the easiest way to detect collisions there only if the balls really collide, not their surrounding bitmap box?

Do I have to store coordinates of as many points on the ball's outline as possible? Or can Android "ignore" the alpha-channel when checking for collisions?


Solution

  • If it is ball collision you can perform analitical collision detection - it will be much faster then per-pixel detection. You only need to have two centers of balls (x1,y1) and (x2,y2) and radius r1 for the first ball and r2 for second one. Now if distance between centers of ball is less or equal of sum of radius then the balls are colliding:

        colide = sqrt((x1-x2)^2+(y1-y2)^2)<=r1+r2
    

    but a little faster way is to compare square of this value:

       colide =  (x1-x2)^2+(y1-y2)^2<=(r1+r2)^2