Jump to content
  • Advertisement
Sign in to follow this  
mcjohnalds45

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.

If you intended to correct an error in the post then please contact us.

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.

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)

Share this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!