LWJGL Forum

Programming => Lightweight Java Gaming Library => Topic started by: amoeba on August 20, 2004, 13:13:20

Title: Calculating angle from 2d point A to 2d point B
Post by: amoeba on August 20, 2004, 13:13:20
Currently my 'ships' in my game move using an x, y, velocity and angle variable. I want to be able to point at 'something' with the angle vector - i.e. another ship.

Is there an algorithm to give me Angle from x1,y2,x2,y2?

Thanks.
Title: Calculating angle from 2d point A to 2d point B
Post by: tomb on August 20, 2004, 14:11:18

/** Gets the angle of the vector given by (xp, yp)
*/
public static final double getAngleFromVector(double xp, double yp)
{
if ((xp!=0)&&(yp!=0))
   {
    //Calculate angle of vector
    double angle=0;
    if (xp!=0)
    {
    if ((xp>=0)&&(yp>=0))
    angle=Math.atan(yp/xp);
    if ((xp<0)&&(yp>=0))
    angle=Math.PI-Math.atan(yp/-xp);
    if ((xp<0)&&(yp<0))
    angle=Math.PI+Math.atan(-yp/-xp);
    if ((xp>=0)&&(yp<0))
    angle=Math.PI*2-Math.atan(-yp/xp);
    }
    else
    {
    if (yp>=0)
    angle=Math.PI/2;
    else
    angle=Math.PI+Math.PI/2;
    }
    return angle;
}
else
{
if (xp==0 && yp==0) return 0;
if (xp==0 && yp>0) return Math.PI*0.5;
if (xp==0 && yp<0) return -Math.PI*0.5;
if (yp==0 && xp>0) return 0;
else return Math.PI;
}
}
Title: Calculating angle from 2d point A to 2d point B
Post by: princec on August 20, 2004, 14:38:37
Doesn't Math.atan2() do all that for you in one call?

Cas :)
Title: Calculating angle from 2d point A to 2d point B
Post by: amoeba on August 20, 2004, 14:47:48
And to use that its;

getAngleFromVector( source.x-target.x, source.y-target.y)

?
Title: Calculating angle from 2d point A to 2d point B
Post by: amoeba on August 20, 2004, 15:06:38
Aaah excellent thanks.