CIRCLE/CIRCLE
Collision with points is fine, but rarely do objects actually occupy a single point in space. Next, we can use the same application of the Pythagorean Theorem from the Point/Circle example to test if two circles are colliding.
First, calculate the distance between the two circle's centers:
var distX = c1x - c2x;var distY = c1y - c2y;var distance = ;
To check if they are colliding, we see if the distance between them is less than the sum of their radii.
if distance <= c1r+c2r return true;return false;
Built into a full example, it looks like this:
var c1x = 0; // circle 1 positionvar c1y = 0; // (controlled by mouse)var c1r = 30; // radius var c2x = 300; // circle 2 positionvar c2y = 200;var c2r = 100; { var canvas = ; ;} { ; // update position to mouse coordinates c1x = mouseX; c1y = mouseY; // check for collision // if hit, change color var hit = ; if hit ; else ; ; // other circle, controlled by mouse ; ;} // CIRCLE/CIRCLE { // get distance between the circle's centers // use the Pythagorean Theorem to compute the distance var distX = c1x - c2x; var distY = c1y - c2y; var distance = ; // if the distance is less than the sum of the circle's // radii, the circles are touching! if distance <= c1r+c2r return true; return false;}
Circle/Circle collision can be used to create "bounding circles" around more complex objects. While sacrificing accuracy, this kind of collision detection is very fast and can be a good approximation.
You may be wondering why we are only talking about circles and not ellipses. It might seem fairly similar, but the math for ellipse collision is actually quite complicated. Consider it a great challenge once you master the other collision examples!