Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Finding X Y angle between two Vector3s?

Asked by
tukars 17
6 years ago
Edited 6 years ago

For example I can do the method with cframe:

CFrame.new(pos1, pos2)

but it flips past 180 degrees.

I need to do a method which doesn't flip the angles (Im working out a planeCF) .

I heard people use :Dot() product but only get one number?

This is how I format the planeCF...

angle x,y = ...
planeCF = CFrame.new(pos1) * CFrame.Angles(x, y, 0)

here is graph to show what i mean... https://imgur.com/a/xBSu0ty
of course it is meant to show 3d space but I can only draw in 2d

0
Vector2, UDim, UDim2 greatneil80 2647 — 6y

1 answer

Log in to vote
1
Answered by 6 years ago
Edited 6 years ago

A dot product is definitely the simplest way. Your diagram has a black vector that is (pos2 - pos1). You want to normalize that, and take the dot product with (0,1,0), which is the green World Up vector. The dot product of two vectors is the product of their magnitudes times the cosine of the included angle (angle between them). That equation looks like this (using Lua function

v1 (dot) v2 = |v1||v2|cos(theta)

So, you're going to compute what's on the left side, in order to solve for theta, the angle between v1 and v2.

When you normalize your vectors, the product of their magnitudes (|v1||v2|) is just 1 times 1, so 1. That just leaves you with the dot product being the cosine of the angle. So, you take the inverse cosine of that and it's the angle in radians. I'm renaming the vectors with u to indicate they are unit vectors:

u1 (dot) u2 = cos(theta)

arccos(u1 (dot) u2) = theta --take the inverse cosine of both sides

In Lua, it looks like this for your problem:

local v = (pos2 - pos1).Unit
local angleInRadians = math.acos(v:Dot(Vector3.new(0,1,0))

P.S. "(dot)" should be a dot product dot. But apparently this site does not support unicode characters on the forum, just in the answer editor. Even the theta character I typed got converted to a question mark :-/

0
thank you tukars 17 — 6y
Ad

Answer this question