Java – “Simple” Rectangle Collision Detection: Why doesn’t the code work


Hey guys, please take a look at my code and see what's wrong here. I looked at the docs and everything and it seems like this should work.

public Boolean CollisionTest (Rect one, Rect two) {
        if (one.intersect(two)) {
            collided = true;
        } else {
            collided = false;

Should this not return if two rectangles collide? The reason I am doubting this I am having some null pointer exception inside my Main Thread (it is stopping on my finally statement for my game loop thread) errors when debugging and when I do not use this function it is fine.

Very weird, also I would appreciate if anyone could post links to useful collision detection tutorials. I want to deal with my own collision detection and not use outside libraries.


Best Solution

According to the Android Developers documentation for the intersect function:

If the specified rectangle intersects this rectangle, return true and set this rectangle to that intersection, otherwise return false and do not change this rectangle.

The part that I added emphasis to means that your one parameter could be changed if the rectangles do intersect -- which I'm guessing is how it's somehow getting set to null, and causing your error later on in the game loop.

The documentation also states:

To just test for intersection, use intersects().

A description of the Rect.intersects(Rect a, Rect b) method is available here.

If we modify your method to use Rect.intersects, it would look like this:

public Boolean CollisionTest (Rect one, Rect two) {
        return Rect.intersects(one, two);

At this point you could probably get rid of CollisionTest altogether and just call Rect.intersects directly -- unless at some point you wanted to implement your own collision detection. In that case, you'd just have to modify this one method. It's up to you, really.

Related Question