How do you find the unit vector from a vector? I can compute vectors but they end up having variable lengths, I need a common short version before I can use them further.
Unit Vector
length_of_vector = sqrt(vec.x^2 + vec.y^2) // 2D representation
unit_vector = vec / length_of_vector
3D is exactly the same but you add in the component vec,z^2 before the sqrt.
Dev careful. Pixel on board.
Buckle up. Everything will be revealed.
Adding some explanation, it's the same as the Pyrhagoras right angled triangle formula you have learned in school:
a^2 + b^2 = c^2
Because the x and y you have lie on orthogonal grid axis, you can imagine them forming a triangle, where c is the unknown length of the 3rd edge.
Solving for c then is: c = sqrt(a*a + b*b)
Which gives the unit vector by division: u = (a,b) / c.
But you can't divide if c is closely zero. So usually you need to check for that using a small number:
if (c > 1.0e-6f) return vec2(a,b) / c
else return vec2(0.f,0.f)
If you already use the dot product, you can rewrite it as: c = sqrt(dot(myVector, myVector)),
because dot product with itself gives squared length.