Search code examples
java2dcollision-detectiontrigonometrygeometry

Calculating tangent from a point on a circle?


I'm trying to create an algorithm to find the tangent on a circle so that I can calculate the angle of reflection for that circle when it collides with an object. I know the x and y values of the centre of the circle and the radius. I also have the x and y values for the point of impact with the other object. Any help with how to calculate the tangent perhaps using a Java library would be great, or if anyone has any recommendations on how to calculate the angle of reflection another way would be appreciated. Thanks.


Solution

  • From what I understand, you actually want to calculate the angle of incidence for the circle. For this, you need to know the angle of the circle's movement and the angle of the surface it is bouncing off; the point of collision will not be enough since it is the same no matter the angle the circle collides at. If you have this angle, then the circle's new angle is given by (360 - circle's angle + (surface's angle * 2)) % 360. I doubt you keep track of the circle's angle of movement, though you may already have two variables describing its movement, perhaps something along the lines of: "for every update, move circle dx units right and dy units up". If you have this you can compute the circle's angle in degrees with (180 / π) * arctan(dy / dx). This formula works because dy / dx gives the slope of the line created by the movement of the circle across the plane. Once we have the slope, we take the inverse tangent (arctan) of it which gives its angle in radians. Finally we convert that angle to degrees with the 180 / π part.

    This also works if we use the slope of the surface. Say the surface is a line starting at point (x1, y1) and ending at point (x2, y2). The surface's slope is found with (y1 - y2) / (x1 - x2). Then we can apply the formula as before, substituting the slope of the surface, like so: (180 / π) * arctan((y1 - y2) / (x1 - x2)).

    Now you have both the circle and the surface in terms of degrees and can apply the first formula above.