Skip to main content
GameDev.net gamedev.net
🔒 Locked

Using atan2 to find an angle between two points

Started by mcjohnalds45 Apr 16, 2012 at 12:58 PM 2 replies 11.3k views
Original Post
mcjohnalds45
mcjohnalds45
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.

WfQMZ.png

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 wink.png)
JTippetts
JTippetts
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.

rip-off
rip-off
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?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.