Skip to content

Instantly share code, notes, and snippets.

@joaoffcosta
Created December 4, 2012 16:20
Show Gist options
  • Save joaoffcosta/4205751 to your computer and use it in GitHub Desktop.
Save joaoffcosta/4205751 to your computer and use it in GitHub Desktop.
Angle of a vector
// angle of a vector (defined as AB)
float R2Point::angle(R2Point A, R2Point B)
{
// tg(o) = y / x
float diffy = B.y - A.y;
float diffx = B.x - A.x;
float ang = 0;
// special case;
if ((diffy == 0) & (diffx == 0))
return ang;
// general case - 3 steps
float PI = 4*atan(1.0f);
if (diffx == 0) ang = (float) PI / 2;
else ang = atan(fabs(diffy) / fabs(diffx)); // angle assuming absolute
if (diffx < 0) ang = (float) PI - ang;
if (diffy < 0) ang = -ang;
return ang;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment