Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating angle between two vectors in GLSL

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?

like image 379
Reedie Avatar asked Feb 01 '17 16:02

Reedie


People also ask

How do you find the angle between two vectors given two vectors?

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|) ].

How do you calculate the angle of a vector?

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.

How do you find the angle of an obtuse between two vectors?

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.


2 Answers

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.

like image 188
Nicol Bolas Avatar answered Oct 08 '22 15:10

Nicol Bolas


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 the dot product is 0, the vectors are 90 degrees apart (orthogonal or perpendicular).
  • If the dot product is less than 0, the vectors are more than 90 degrees apart.
  • If the dot product is greater than 0, the vectors are less than 90 degrees apart.
like image 41
Peter O. Avatar answered Oct 08 '22 14:10

Peter O.