Find the angle between 2 3D vectors
I want the angles X Y Z between the 2 vectors
To make a line between them two.
math.atan2(t2.y - t1.y, t2.x - t1.x) * 180 / math.pi)-90
This was the account I used to find out the Z, but the others I can not do, the X and Y.
The size is
C.Size=Vector3.new(0.2,math.sqrt((t2.z-t1.z)^2+(t2.y-t1.y)^2+(t2.z-t1.z)^2),0.2)
Example:
I did in paint because I have to go fast.
I need to find out the angle to rotate the Orange Line between the 2 points, connecting them by the same.
1 answers
The size (or magnitude) of a vector is calculated by the Pythagorean formula, 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. Thus, by dividing the scalar product by the sizes of the vectors, we arrive at the cosine of the angle.
Having the cosine of Angle, math.acos(x)
will give you the angle in radians. This function acos
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.
Therefore, 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))
Note 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 displays as output for this 54.735610317245
(in degrees).