Python’s atan and atan2 functions

This is needed to get an angle based on the rise and run of a vector. So I need this in situations where I need to aim say a turret, and a player sprite and fire. I need to calculate the vector’s rise y2-y1 and run  x2-x1 and put those two parameters into the atan2 function.

There are some things I can’t quite visualize yet but I’ll get to that.

First, there are positive and negative angles. Positive angles are when you go counter clockwise around the unit circle, and negative angles are when you go clockwise. Also, the angle in radians if you go counter clockwise starting from zero, will be the same as that angle if it were positive and going clockwise. enter image description here

so – 45 degrees is positive 315 degrees.

This is important because in aiming something like a turret in the game, having negative angles means you can turn it both ways, instead of having to turn 315 counter clockwise, it can just go clockwise -45 degrees.

So atan2 allows for this by having the parameters for rise and run separate. atan, another math. function, only accepts the already calculated ratio, and so if rise and run were both negative, the result would be positive.

Also for atan, this means the angle then could never be in the 4rd quadrant, the part of the cartesian plane where both y and x are negative.

So the issue in pygame is we a y axis that starts from 0 and goes down from there. So if y1 was 5 and y2 was 10, y2 would be lower than y1 on the screen. I’m trying to get an idea of why the options for fixing this work the way they do.

The first way people fix this is  dy = y1-y2 and then set dy to negative before passing it to atan2. atan2(-dy, dx).

The other way that works for some reason is just flipping the two numbers, atleast when using atan anyways, people are doing atan(dx/dy) and say that works…

I’m going to take a break from it for now but that’s something I’d like to figure out.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

Du kommentierst mit Deinem Abmelden /  Ändern )

Google Foto

Du kommentierst mit Deinem Google-Konto. Abmelden /  Ändern )


Du kommentierst mit Deinem Twitter-Konto. Abmelden /  Ändern )


Du kommentierst mit Deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s