3
votes

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?

3

3 Answers

9
votes

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
13
votes

Another method I can think of will work with simple objects that can be constructed using Paths.

Once you have two objects whose boundaries are represented by paths, you may try this:

Path path1 = new Path();
path1.addCircle(10, 10, 4, Path.Direction.CW);
Path path2 = new Path();
path2.addCircle(15, 15, 8, Path.Direction.CW);

Region region1 = new Region();
region1.setPath(path1, clip);
Region region2 = new Region();
region2.setPath(path2, clip);

if (!region1.quickReject(region2) && region1.op(region2, Region.Op.INTERSECT)) {
    // Collision!
}

Once you have your objects as Paths, you can draw them directly using drawPath(). You can also perform movement by transform()ing the path.

2
votes

It's much easier to use an existing library like AndEngine instead of reinventing the wheel. I'm not sure if it can be used with a SurfaceView though. Check this article: Pixel Perfect Collision Detection for AndEngine.