Game Development Community

Angle calculation

by Northeastern University (#0001) · in Torque Game Engine · 04/17/2006 (5:41 pm) · 3 replies

Hello, I found a function to figure out the angle between two vectors from the advanced 3D book, but it doesn't seem to work for me.

I'm using version 1.4.

I was wondering if anybody can tell me if the following should work or not:

function AIPlayer::GetBearing(%this, %that)
{
%here = %this.getPosition();
%there = %that.getPosition();

%xhere = getWord(%here, 0);
%yhere = getWord(here, 1);

%xThere = getWord(%there, 0);
%yThere = getWord(%there, 1);

%x = %xThere - %xHere;
%y = %yThere - %yHere;

if (%x != 0)
{
%slope = %y/%x;
%angle = mRadToDeg( mATan(%slope, -1) ); // -1 is only 2nd arg that works
}

else
%angle = 90.000;

if ((%x >= 0) && (%y >= 0)) // target in quadrant 1, 0-89.999 degrees
%adjustment = -90;
else if ((%x >= 0) && (%y < 0)) // target in quadrant 2, 90-179.999 degrees
%adjustment = 270;
else if ((%x < 0) && (%y < 0)) // target in quadrant 3, 180-269.999 degrees
%adjustment = 90;
else // target in quadrant 4, 270-359.999 degrees
%adjustment = 90+360;

%angle += %adjustment;

return %angle;
}


thanks for the help.

#1
04/18/2006 (7:15 am)
%angle = mRadToDeg( mATan(%x,%y) );

will give you the correct angle and you should not have to do the quadrant stuff.
#2
04/18/2006 (8:08 am)
Not really related to your angle problem, but your code probably won't work as you have a typo on line 7.

%yhere = getWord(here, 1);
->
%yhere = getWord(%here, 1);
#3
05/03/2009 (4:45 pm)
This seems to work (in C++ code)

parts borrowed from AIFlyingVehicle.cc. I know the code could be optimized...

F32 ShapeBase::getBearing(ShapeBase* base, ShapeBase* target)
{
   Point3F targPos;
   Point3F basePos;
   VectorF baseDir;
   VectorF targDir;
   
   Point3F forward;
   Point3F up;
   Point3F right;
   
   F32 bearing; 	   
   
   MatrixF baseMat = base->getRenderTransform();
   MatrixF targMat = target->getRenderTransform();
	   
   baseMat.getColumn(1, &forward);
   baseMat.getColumn(2, &up);
   baseMat.getColumn(3, &basePos);
   
   baseMat.getColumn(1, &baseDir);
   targMat.getColumn(3, &targPos);

   forward.normalize();
   up.normalize();
  
   mCross( forward, up, right );
   right.normalize();

   targPos.z = 0; // We don't care about the Z-Axis for bearing.
   basePos.z = 0;

   targDir = targPos - basePos;
   targDir.normalize();

   F32 dotTurn = mDot( right, targDir );

   if (!isZero(targDir.x) || !isZero(targDir.y)) 
   {
      if (dotTurn < 0) bearing = -mRadToDeg(dotTurn);
	  else { bearing = 360.0f - mRadToDeg(dotTurn); }; 
   }
   else
   {
   	  bearing = 0.0f;
   }
  
   return bearing;
}