• Create Account

Need scary sound effects or creepy audio loops for your next horror-themed game? Check out Highscore Vol.3 - The Horror Edition in our marketplace. 50 sounds and 10 loops for only \$9.99!

# Using atan2 to find an angle between two points

Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

3 replies to this topic

### #1mcjohnalds45  Members   -  Reputation: 106

Like
0Likes
Like

Posted 16 April 2012 - 06:58 AM

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 )

### #2JTippetts  Moderators   -  Reputation: 6646

Like
1Likes
Like

Posted 16 April 2012 - 07:35 AM

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.

### #3rip-off  Moderators   -  Reputation: 6190

Like
0Likes
Like

Posted 16 April 2012 - 07:57 AM

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?

### #4mcjohnalds45  Members   -  Reputation: 106

Like
0Likes
Like

Posted 18 April 2012 - 01:32 AM

Thanks heaps JTippetts, fixed the problem!

Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

PARTNERS