The size (or magnitude) of a vector is calculated by the formula of Pythagoras, that is, the square root of the sum of the squares of each component of the vector.
The scalar product of two vectors is calculated as the sum of the products of each component, and what it represents is the product of the length of the two vectors with the cosine of the angle formed between them. Then, by dividing the scalar product by the sizes of the vectors, one arrives at the cosine of the angle.
Having the cosine of the angle, math.acos(x)
will give you the angle in radians. This acos
function means arc-cosine , or inverse cosine.
Having the angle in radians, math.deg(x)
will give you the angle in degrees. This function serves exactly to convert radians to degrees.
So this should be what you want:
function vetor3D(x, y, z)
local v = {}
v.x = x
v.y = y
v.z = z
return v
end
function magnitude(v)
return math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z)
end
function produto_escalar(a, b)
return a.x * b.x + a.y * b.y + a.z * b.z
end
function angulo(a, b)
ta = magnitude(a)
tb = magnitude(b)
if ta == 0.0 or tb == 0.0 then
return 0.0
end
return math.deg(math.acos(produto_escalar(a, b) / ta / tb))
end
# Teste
a = vetor3D(1, 0, 0)
b = vetor3D(0, 1, 0)
print(angulo(a, b))
c = vetor3D(1, 1, 1)
print(angulo(a, c))
See here working on ideone.
Notice that at the end this angulo(a, c)
will give the angle between one of the edges of the cube and the diagonal. The program outputs 54.735610317245
(in degrees) as output.