1

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

Adrin
  • 543
  • 3
  • 10
  • Using the centre point of both circles you should be able to calculate the angle: https://stackoverflow.com/questions/9614109/how-to-calculate-an-angle-from-points – Turnip Oct 26 '18 at 11:36

2 Answers2

3

You can detect the angle with some simple trigonometry.

tangent = Opposite/Adjecent

So let angle = Math.atan(dy/dx)

Pac0
  • 16,761
  • 4
  • 49
  • 67
Dorian B
  • 138
  • 7
1

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 .

Pac0
  • 16,761
  • 4
  • 49
  • 67
  • (btw, anyone knows if we can use LaTeX on SO, like in [Math.SE] ?) – Pac0 Oct 26 '18 at 12:06
  • @adam west : it took me a bit of time, but I think I have the correct solution now. See my last version of this answer. – Pac0 Oct 26 '18 at 12:09
  • Thanks for explanation – Adrin Oct 26 '18 at 12:57
  • @adamwest : Also note that this may give you an *obtuse* angle instead of the *acute* one (like in my picture). To solve this, just take `Math.min(angleInDegrees, 180-angleInDegrees)`. – Pac0 Oct 26 '18 at 14:49