Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

how do i use atan2 so that it works in a 3d space?

i have 2 vectors and and i want to find the angle between them.

1 answer

✓ Accepted answer

To get the dot product of two vectors, take the sum of the products of corresponding coordinates.

(x_1, y_1, z_1) · (x_2, y_2, z_2) = x_1 * x_2 + y_1 * y_2 + z_1 * z_2

To find the magnitude (|u|), we can just use .magnitude

Using these two operations, we can apply the equation...

cos x = (u · v) / (|u| |v|)

...and then rearrange...

x = acos ((u · v) / (|u| |v|))

...to get our answer.

function dotProduct(u, v)
    return u.x * v.x + u.y * v.y + u.z * v.z
end

function angle(u, v)
    local top = dotProduct(u, v)
    local bottom = u.magnitude() * v.magnitude()
    return (top / bottom)
end

3 comments

0

There is some intuition behind the equation I can try to explain if you want, like, what actually is a dot product?

0

yes please. that would be helpful

0

Ok I'm going to level with you here. I tried explaining it and I can't manage to write it down in words properly. Sorry :( Maybe try having a look at 3Blue1Brown's stuff on YouTube? (e.g., https://www.youtube.com/watch?v=LyGKycYT2v0)

This discussion is preserved as it was. New answers, comments, and votes are closed.