I'm working in GLSL, and need to calculate the angle between two 2D vectors fast and efficiently.
Given two vec2 vectors, for instance (30, 20) and (50, 50), I need to calculate the angle between them.
I'm currently using
acos(dot(vector1, vector2));
Although this doesn't seem to be giving me the angle correctly. Am I doing something wrong, or is this the right function to be using?
To find the angle between two vectors a and b, we can use the dot product formula: a · b = |a| |b| cos θ. If we solve this for θ, we get θ = cos-1 [ (a · b) / (|a| |b|) ].
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.
Assuming your known points are origin O (0,0), vector1 head A (x,0) - on the x-axis and another point B (m,n). If you want the angle made by OA and OB, the angle would be acos(m/sqrt(mm + nn))*180/pi degrees.
A vector dot product will compute the cosine of the angle between two vectors, scaled by the length of both vectors. If you want to get just the angle, you must normalize both vectors before doing the dot product.
The dot product alone will give you some very rough information about the angle between two vectors, even if they're not unit vectors:
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