pythag0ras_
pythag0ras_

Reputation: 162

Making a vector library in python, but my heading() function has a problem with the atan2 function

I'm making a vector library for python (I'm pretty new to python) and I'm making a function to find the heading of the vector. Here's the code for it. (I'm using radians for all of this, btw).

def heading(self):
    return math.atan2(self.x, self.y)

I know that this is broken because when I run my setHeading function (which I've tested already, it works fine) to set the heading of the vector, getting the heading returns a different value. I looked on google to see what was wrong with it, and it said that the python math.atan2 function returns a value between -PI and PI. Fine, I add PI when I return it. Still doesn't work. How do I fix this?

EDIT: I was asked to put the setHeading function up here as well.

 def setHeading(self, a):
    if type(a) == int or type(a) == float:
        self.x = math.cos(a) * self.mag()
        self.y = math.sin(a) * self.mag()
    else:
        print("Vector2.setHeading() only takes a float or an int")

Upvotes: 0

Views: 421

Answers (1)

DarrylG
DarrylG

Reputation: 17156

Issue is you have x and y reversed in atan2 call in heading function

atan2 function signature:

math.atan2(y, x)¶

Consequently, change heading function definition to:

def heading(self):
    return math.atan2(self.y, self.x)

Upvotes: 3

Related Questions