With any video game, it can be necessary to detect whether or not two objects are touching.
Touching, in this sense, means that one object's (or image's) pixel position is over the pixel position of another.
For the sake of this post, I'm sticking strictly to circle-to-circle collision detection, as it was something I had to figure out, which can be easily related to other types of collision.
I tried many different approaches by comparing various x/y components, and finally settled on this much simpler solution:
public boolean checkCollision(Circle a, Circle b){
//Circle has 3 components: x, y, and radius
//We're going to use the distance formula here
//We'll start be getting the x and y differences between the objects's centers
int xDif = Math.abs(a.x - b.x);
int yDif = Math.abs(a.y - b.y);
//Now to get the distance, we raise both differences to the power of 2
//Then we add them together, and take the square root
int distance = Math.sqrt(Math.pow(xDif, 2) + Math.pow(yDif, 2));
//If the calculated distance is less than the combined radii then the circles are overlapping
if ((a.radius + b.radius) > distance) return true;
else return false;
}
Boom. Basic circle to circle collision detection.
No comments:
Post a Comment