dan boy
dan boy

Reputation: 89

Need help detecting collision between two objects

I'm having some issue regarding collision detection in a game i am making. I have the distance between the two objects using this:

    double b1Dist = Math.sqrt((obOneX - obTwoX) * (obOneX - obTwoX)
            + ((obOneY - obTwoY) * (obOneY - obTwoY)));
    double b1DistTwo = b1Dist - objectOneRadius;
    b1DistFinal = b1DistTwo - objectTwoRadius;

and I was attempting to do collision detection with this:

  if (b1DistFinal <= objectOneRadius && b1DistFinal <= objectTwoRadius ) {
            return false;
        }
         else
            return true;

    }

I'm new to java so i'm sure theres probably much better/more efficient ways to write the above, however could anyone please help me out or point me in the right direction?

Thanks

Upvotes: 1

Views: 326

Answers (1)

chm
chm

Reputation: 1519

There's nothing wrong with the efficiency of that. However, if obOneX, obOneY, etc are the x and y coordinates of the centers of the objects, then your formula is wrong.

The variable b1DistFinal is the distance between the outer edges of the two objects. If it's zero, those objects have collided.

Try:

if (Math.abs(b1DistFinal) < 0.001) {
    return true;
} else {
    return false;
}

Note: Rather than checking if it is exactly zero, I am checking if it is close to zero to allow for some rounding error during the double arithmetic.

Upvotes: 1

Related Questions