# Using atan2 to find an angle between two points

This topic is 2406 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm trying to find the angle aimDirection with this code.

 aimDirection = atan2(mouseY - vertical centre of box, mouseX - horizontal centre of box) * 180 / pi; // what I'm doing in english 

 aimDirection = atan2((double)(mouseY - hitBox.y + (hitBox.h / 2)), (double)(mouseX - hitBox.x + (hitBox.w / 2))) * 180 / M_PI; // actual code 

I thought you could use atan2 like so to find an angle, maybe I'm wrong.

 angle = atan2(y2 - y1, x2 - x1) * 180 / pi. 

I don't know how to describe the situation clearly so I made a pretty picture instead.

But the angle is never what I expect (depending on where I move my mouse vs the middle of the box) when I run the program.

(Sorry if I don't reply till tomorrow, it's getting late and I don't want to be drowsy for school )

##### Share on other sites
What exactly is happening?

One possible issue I see might be the order of operations of your relative vector calculation. If the center of your hit box is calculated as (rect.position + rect.size/2) then what you are actually doing in your call to atan2 is not correct. Consider the case of a hit box at (1,1) and sized (2,6). The center of the hitbox will be at (2,4). Now, consider a mouse location at, say, (4,4). Logically, the vector (mouse.position-hitbox.center) would be (2,0). But the vector you are calculating with (mouseY-hitBox.y+(hitbox.h/2), mouseX-hitBox.x+(hitbox.w/2) is not equal to (2,0). It's equal to (4-1+1, 4-1+3), or (4,6). You see? It's the order of operations. What you want is (A-(B+C)) but what you are doing is (A-B+C), which is not the same.

So try parenthesizing to get the correct order of operations atan2(mouseY-(hitbox.y+hitbox.h/2), mouseX-(hitbox.x+hitbox.w/2)) and see if that makes any difference.

##### Share on other sites
In addition, consider if you even need angles at all. Perhaps the aim direction vector (a normalised vector from the box to the mouse) is all you actually need?

##### Share on other sites
Thanks heaps JTippetts, fixed the problem!

1. 1
Rutin
41
2. 2
3. 3
4. 4
5. 5

• 18
• 20
• 14
• 14
• 9
• ### Forum Statistics

• Total Topics
633379
• Total Posts
3011570
• ### Who's Online (See full list)

There are no registered users currently online

×