Skip to content Skip to sidebar Skip to footer

Check Whether A Point Exists In Circle Sector Or Not With Python

I am aware that on the net and also here the question has already been asked, but unfortunately not in the Python environment. Looking on the net, I found this (Link) and from ther

Solution 1:

The easiest way to find the best direction is to calculate the cosine of the angle between the line from the player position to the mouse position and the line from the player position to the 8 points.
It has to be found that direction vector which has the smallest angle to the "mouse" direction. The cosine of 0 degrees is 1 and the cosine of 180° is -1. So the direction with the greatest cosine is the direction to be found.

The easiest way to calculate the cosine is the dot product.

In general the dot product of 2 vectors is equal the cosine of the angle between the 2 vectors multiplied by the magnitude (length) of both vectors.

dot( A, B ) == | A | * | B | * cos( angle_A_B ) 

This follows, that the dot product of 2 unit vectors is equal the cosine of the angle between the 2 vectors, because the length of a unit vector is 1.

uA = normalize( A )
uB = normalize( B )
cos( angle_A_B ) == dot( uA, uB )

The dot product of 2-dimensional vectors A and B can be calculated by 2 multiplications and 1 addition:

dotAB = Ax * Bx + Ay * By  

Set up a list with the 8 normalized directions:

dir = [(0, 1), (0.707, 0.707), (1, 0), (0.707, -0.707),
       (0, -1), (-0.707, -0.707), (-1, 0), (-0.707, 0.707)]

Find the "best" direction, this is the direction with the closest angle or the greatest cosine of the angle:

dx, dy = mpx - cpx, mpy - cpy
max_i = max([i for i in range(len(dir))], key = lambda i: dx*dir[i][0] + dy*dir[i][1])

Finally max_i contains the searched direction.

Note the algorithm doesn't calculate and compare the cosine of the angles, it compares product of the cosine and the radius. dx*dir[i][0] + dy*dir[i][1] is eqault to radius * cos(alpha).

The searched point finally is:

radius = math.hypot(mdir_x, mdir_y) + 20
X = (dir[max_i][0] * radius, dir[max_i][1] * radius)


Post a Comment for "Check Whether A Point Exists In Circle Sector Or Not With Python"