[gameprogrammer] Re: Diff Between 2 Angles

  • From: Olof Bjarnason <olof.bjarnason@xxxxxxxxx>
  • To: gameprogrammer@xxxxxxxxxxxxx
  • Date: Fri, 30 Sep 2005 09:08:17 +0200

double absanglediff(double angle1, double angle2) {
  // Rotate angle1 with angle2 so that the sought after
  // angle is between the resulting angle and the x-axis
  angle1 -= angle2;

  // "Normalize" angle1 to range [-180,180)
  while(angle1 < -180)
    angle1 += 360;
  while(angle1 >= 180)
    angle1 -= 360;

  // angle1 has the signed answer, just "unsign it"
  return abs(angle1);
}

/Olof
On 9/29/05, Simon <simonmihevc@xxxxxxxx> wrote:
>
> > I've got a really simple problem that I'm almost ashamed to ask about!
> > I've written a 3D pseudo-realtime strategy game called Lazer Squad 3D
> > (www.carlylesmith.karoo.net/lazersquad3d/).  One problem I always think
> > I've solved, but then comes back to bite me, is how to get the
> > difference between two angles.  This seems easy on the face of it, but
> > then along comes two angles and my formula gets it all wrong.  (This is
> > degrees, BTW, not rads).
> >
> > The main problem is when dealing with negative angles, angles > 360, and
> > also getting the shortest distance (i.e. not the long way round).  For
> > example, the difference between -359 and 359 should be 2 degrees.  The
> > difference between 90 and -270 should be zero.  Etc.. etc.. Can anyone
> > help please?
> >
> > Thanks in advance,
> >
> > Steve Smith
> >
>
> Maybe try it like this:
>
> // convert angles to positive
> while (angle1 < 0) angle1 += 360;
> while (angle2 < 0) angle2 += 360;
>
> // clamp angles betwen 0 and 360
> angle1 = angle1 % 360;
> angle2 = angle2 % 360;
>
> // compute angle difference
> angle_dif = abs(angle1 - angle2)
>
> // find the smaller angle
> if (one_angle_dif > 180) angle_dif = 360 - angle_dif;
>
> Cheers, Simon.
>
>
> ---------------------
> To unsubscribe go to http://gameprogrammer.com/mailinglist.html
>
>
>


---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html


Other related posts: