Find the angle between 2 vectors in 3d

3

I want the angles X Y Z between the 2 vectors

To make a line between them.

math.atan2(t2.y - t1.y, t2.x - t1.x) * 180 / math.pi)-90

This was the account I used to discover 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 not paint because I have to go fast.

I need to find the angle to rotate the orange line between the 2 points, connecting them by the same.

    
asked by anonymous 21.12.2016 / 14:37

1 answer

5

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.

    
21.12.2016 / 17:09