I have a small circle which is inside a bigger circle. The small Circle is flying around, and if the small circle comes to the border of the big circle it should collide. I have almost managed to do so, but it still does not work perfect. Sometimes the circle collides just before the border, and sometimes right after the border. This is my code:
if (!(Math.pow((xSmallCircle + radiusSmallCircle) - (xBigCircle), 2) + Math.pow((
ySmallCircle + radiusSmallCircle) - yBigCircle, 2) < Math.pow(radiusBigCircle + 10, 2))) {
xVelocity *= -1;
yVelocity *= -1;
} else if (!(Math.pow((xSmallCircle - radiusSmallCircle) - (xBigCircle), 2) + Math.pow((
ySmallCircle - radiusSmallCircle) - yBigCircle, 2) < Math.pow(radiusBigCircle + 10, 2))) {
xVelocity *= -1;
yVelocity *= -1;
} else if (!(Math.pow((xSmallCircle + radiusSmallCircle) - (xBigCircle), 2) + Math.pow((
ySmallCircle - radiusSmallCircle) - yBigCircle, 2) < Math.pow(radiusBigCircle + 10, 2))) {
xVelocity *= -1;
yVelocity *= -1;
} else if (!(Math.pow((xSmallCircle - radiusSmallCircle) - (xBigCircle), 2) + Math.pow((
ySmallCircle + radiusSmallCircle) - yBigCircle, 2) < Math.pow(radiusBigCircle + 10, 2))) {
xVelocity *= -1;
yVelocity *= -1;
}
Any ideas why this does not work?
It’s because you’re only checking for collision at four points, which are actually all outside the inner circle. Try a simpler, and mathematically correct collision detection mechanism.
The logic here is that if you calculate the length of the line segment between the centers of each circle, and add the small circle’s radius, you’ll get the radius of the smallest circle which is (a) concentric to the the outer circle, and (b) completely encircling the smaller circle. If that circle is larger or the same size as your outer circle, you have a collision.
If you still have inexact collisions, it’s probably a rounding error.