Reedie
Reedie

Reputation: 309

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?

Upvotes: 10

Views: 18298

Answers (2)

Peter O.
Peter O.

Reputation: 32878

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.

Upvotes: 9

Nicol Bolas
Nicol Bolas

Reputation: 473292

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.

Upvotes: 23

Related Questions