Finding the angle of a vector
Hello, how do find the angle of a vector whose tail is at origin? The vector is rotating as well so I want to keep updating the angle.
I've been using this:
angle = Math.atan2(vector.x, vector.y);
angle = Math.toDegrees(angle);
But I'm not sure if its right, as it stands when the vector is pointing directly down (6o'clock) the above code is giving the reading of 0'degs, then if I rotate the vector anti-clockwise to 12o'clock it gives the reading of 180'degs, but if I continue to rotate the vector anti-clockwise the angle reading becomes negative -180 to -1 then back to 0'degs at 6o'clock and so on.
As you can probably guess to vectors :)
Cheers
As the spec for Math.atan2 says, it gives an angle between -PI and +PI radians.If you want to convert it to the more common range of 0 to 2PI, angle = Math.PI-Math.atan2(vector.x, vector.y);
Abusea at 2007-7-15 14:15:19 >

heres a bit code from my Vector2D class:
public double getDegrees(){ //Winkelabfrage
if(this.x == 0)
return 90+(this.y<0 ? 180 : 0);
if(this.y == 0)
return this.x<0 ? 180 : 0;
int turns = 0;
while(!(x>0 && y>0)){
this.mul(0,-1);
turns++;
}
double tmpDeg = Math.toDegrees(Math.atan(this.y/this.x));
for(int i=turns; i > 0; i--)
this.mul(0,1);
return 90*turns+tmpDeg;
}
I think its not too pretty and not too fast, but it works ...
Okay, its **** bad :(
> Cheers Abuse, works a treat, I only whish I knew how
> :)
Who cares how it works ^_^ (but if you are realy interested, u could try googling for 'arc tangent' or 'converting rectangular to polar coordinates')
>
> Is this a common way to find the angle or is there a
> more straight forward way?
It can't realy get more straight forward than a single method call :o
and yeah, I believe it is the correct way of converting a vector into an angle.
It doesn't do anything horribly inefficient (like a sqrt ;P), so i don't think you need to worry about it being a performance bottleneck.
Abusea at 2007-7-15 14:15:19 >
