Im trying to find out the angle (in degrees) between two 2D vectors. I know I need to use trig but I'm not too good with it. This is what I'm trying to work out (the Y axis increases downward):
I'm trying to use this code at the moment, but it's not working at all (calculates random angles for some reason):
private float calcAngle(float x, float y, float x1, float y1)
{
float _angle = (float)Math.toDegrees(Math.atan2(Math.abs(x1-x), Math.abs(y1-y)));
Log.d("Angle","Angle: "+_angle+" x: "+x+" y: "+y+" x1: "+x1+" y1: "+y1);
return _angle;
}
These are my results (There constant when providing a constant position, but when I change the position, the angle changes and I can't find any link between the two angles):
Position 1: x:100 y:100 x1:50 y1:50 Angle: 45
Position 2: x:92 y:85 x1:24 y1:16 Angle: 44.58
Position 3: x:44 y: 16 x1:106 y1:132 Angle: 28.12
Edit: Thanks everyone who answered and helped me figure out that was wrong! Sorry the title and the question was confusing.
To calculate the angle between two vectors in a 2D space: Find the dot product of the vectors. Divide the dot product by the magnitude of the first vector. Divide the resultant by the magnitude of the second vector.
It is always either zero or 180 degrees. As the definition of a vertical component is aligned with the gravitational force axis.
It should be :
atan( abs(x1 - x)/abs(y1 - y) )
abs
stands for absolute (to avoid negative values)
You first have to understand how to compute angle between two vectors and there are several of them. I will give you what I think is the simplest.
v1x * v2x + v1y * v2y
With this information, please take this definition:
dot(v1, v2) = norm(v1) * norm(v2) * cos(angle(v1, v2))
Now, you solve for angle(v1, v2)
:
angle(v1, v2) = acos( dot(v1, v2) / (norm(v1) * norm(v2)) )
Finally, taking the definitions given at the beginning, then you end up with:
angle(v1, v2) = acos( (v1x * v2x + v1y * v2y) / (sqrt(v1x^2+v1y^2) * sqrt(v2x^2+v2y^2)) )
Again, there are many ways to do this, but I like this one because it is helpful for dot product given angle and norm, or angle, given vectors.
The answer will be in radians, but you know that pi radians (that is 3.14 radians) are 180 degrees, so you simply multiply by the conversion factor 180/pi.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With