Search code examples
pythonmathvectorangle

How To Turn A Calculated Angle (vector) Into A Single Number Representing That Angle?


I basically got my angle vector from two points:

Point aa is going to Point bb.... (Window.width=800, Window.height=600)

 aa = (50.0*Window.width/100.0, 50.0*Window.height/100.0)
 bb = (10.0*Window.width/100.0, 70.0*Window.height/100.0)

 Angle = Vector(bb)-Vector(aa)

 print(Angle)

 [-320, 120]

Is there a way to convert the vector into a single number that represents the angle...like 90.0, 45.0, 180, etc...? Keep in mind, we're going from aa to bb....that angle.

Another way to put it is, I want to convert the above "Angle" value into a single number.


There's no Z axis here. Only the 2d two points of aa and bb. The Window x-cord is defined going from left to right, with 0 starting at the left.

The Window y-cord is defined going from bottom to top, with 0 starting at the bottom.


Trying to be more clear here...

Vector point aa is like the middle of a circle. Degree zero will start at the the middle-right edge of the circle and going counter clockwise will increase the degrees, until you hit 360 which places you back at the middle-right edge.

Vector point aa can move but regardless of its position in the Window, I want to calculated the angle between aa and the point its moving towards (bb), with aa being the center of the circle and degrees going counter clockwise like I explained above.

Hope that sheds some more light.


Ok, I found a python function that works but not perfect.

 def GetAngleOfLineBetweenTwoPoints(self, p1, p2):
     xDiff = p2[0] - p1[0]
     yDiff = p2[1] - p1[1]
     return degrees(atan2(yDiff, xDiff))

What happens is,

I do get the correct degree but it's in a split screen format and what I mean by that is, the top half of my screen going from right to left is 0 to 180 positive. The bottom half of my screen going from right to left is 0 to -180.

See what's going on there?

How can I make that function return a value between 0 to 360, like a whole circle instead of the 0 to 180 +/- split like it's currently doing?


Solution

  • Got it!

     from math import atan2, degrees, pi, cos, sin
    
     def GetAngleOfLineBetweenTwoPoints(self, p1, p2):
         xDiff = p2[0] - p1[0]
         yDiff = p2[1] - p1[1]
         val = degrees(atan2(yDiff, xDiff))
         if str(val).find('-')!=-1:
             val = float(360)-float(val)
         return val
    

    Yaaaaaayyyyyyy!!!!!!!