Search code examples
javascriptmathcollision-detection

detecting collision angle between two circle


I'm detecting collision between two circles like this:

var circle1 = {radius: 20, x: 5, y: 5}; //moving
var circle2 = {radius: 12, x: 10, y: 5}; //not moving

var dx = circle1.x - circle2.x;
var dy = circle1.y - circle2.y;
var distance = Math.sqrt(dx * dx + dy * dy);


if (distance < circle1.radius + circle2.radius) {
    // collision detected
}

My question is How can I detect the collision angle of circle2? (circle2 is not moving). I would appreciate any explanation


Solution

  • Solution :

    I think I got it :

    arccos((ra^2+rb^2-c^2)/(2*ra*rb))

    where :

    • c is the distance between the centers of both circles (distance in your question)
    • ra is the radius of the first circle
    • rb is the radius of the second circle

    Code : In JavaScript with your values, that should give :

    const angleInRadians = Math.acos((circle1.radius*circle1.radius + circle2.radius*circle2.radius - distance*distance)/(2*circle1.radius*circle2.radius))
    

    Note that the result is in radians, see doc for acos

    If you want to have it in degrees, just use the conversion :

    const angleInDegrees = angleInRadians / Math.PI * 180
    

    Explanation :

    The angle between the circles is defined as the angle between the tangent lines at any of the intersection points (if there are two points, both angles are the same).

    The angle between tangents is the same as the angle between the corresponding radiuses (because radiuses are orthogonal to the tangent lines).

    To get the angle between radiuses :

    Draw a triangle between both centers and one of the intersection point. Use law of cosines based on the angle at the intersection point.

    c^2 = ra^2 + rb^2 - 2*ra*rb*cos(alpha)

    sketch of 2 circles intersecting

    If you need more explanations, feel free to ask in comments .