I haven't had much luck searching the internet for code to find the tangents to a circle, which pass though a external point, so i wrote this one up:
def find_tangents_through_point(circle_center, circle_radius, point):
#find the direction from the point to the center of the circle
dir = point - circle_center
#extract the length and angle
len = dir.length
angle = atan2(dir.y, dir.x)
# derive the length of the tangent using pythagoras
tangent_len = sqrt(len**2 + circle_radius**2)
# and the angle using trigonometry
tangent_angle = atan(circle_radius/len)
# there are 2 tangents, one either side
pos = angle + tangent_angle
neg = angle - tangent_angle
#return the direction vector of each tanget (the starting point was passed in)
return ( vec2d(cos(pos), sin(pos)), vec2d(cos(neg), sin(neg)) )
Unfortunately, it seems to have some accuracy problems:
find_tangents_through_point( vec2d(0,0), 2.0, vec2d(2.0,2.0) )
yields:
vec2d(0.169101983309, 0.985598564148), vec2d(0.985598564148, 0.169101983309)
instead of the expected (0, 1), (1, 0).
Any ideas where the inaccuracy is coming from? Am I doing something silly re floating point error?