In slick2d, there is a class called vector2f. I hope you know what that is, because it will take years to explain. How do I get the angle that it is going?
In the Slick source of [icode]Vector2f.java[/icode] there’s a method called [icode]getTheta()[/icode]. Here’s it’s documentation.
/**
* Get the angle this vector is at
*
* @return The angle this vector is at (in degrees)
*/
You can access the source here at https://bitbucket.org/kevglass/slick/src/c0e4b96798d1c5b1969a26cb62eb7489d701ca6f/trunk/Slick/src/org/newdawn/slick?at=default
The question is that you want to do with your angle. If you need to calculate sin and cos, then you can skip calculating the angle all together.
This is the ‘naive’ way:
Vector2f vec = new Vector2f(..., ...);
double angle = Math.atan2(vec.y, vec.x);
double cos = Math.cos(angle);
double sin = Math.sin(angle);
This is a nice fast shortcut:
Vector2f vec = new Vector2f(..., ...);
vec = vec.normalize();
double cos = vec.x;
double sin = vec.y;
I am sorry to hijack the thread but I think the OP will find the answer to this question useful as well.
Vector2 vec = body.getPosition();
double angle = MathUtils.atan2(vec.y, vec.x);
System.out.println("Angles: " + angle);
I tried this as soon as I saw Riven’s answer. It gave me something like 1.1726287603378296 and 0.6320657730102539 as output. There are negative values as well. My question is what the unit of the angle we get here is.
I think it’s not an ordinary angle. Because if I get angle by vec.angle() [Libgdx], it is different. This is the output when I add vec.angle() to the system output:
[quote]Angles: 0.24124036729335785 or 13.907541
[/quote]
Radians
the dot product of two vectors is also very usefull, because it is the cos of the angle between the two vectors.(both vectors have to be normalized)
So if the dot is 0 the vectors are orthogonal to each other, if |cos(a)| == 1 then they are parallel and with the sign you can see if they are pointing in the same(+) or different(-) direction
If you are trying to do homing missiles, this is a fast way to simulate it. In fact, you don’t need to normalize for it to work.