Calculate Angle between 2 Vectors?

image

red is first vector, green is vector that will move arbitrarily. how to calculate the second picture (no constraints) using cframe/ vectors and then position that part properly as well.

image

also how could i calculate this sort of screw motion? (this isnt as important - just a side question)

to calculate the angle in degrees between two vector you can use:
local a = Vector3.new(10, 0, 0)
local b = Vector3.new(0, 0, 10)
print(math.deg(math.acos( a:Dot(b)/(a.Magnitude * b.Magnitude) )))

The most standard way to get the included angle between 2 arbitrary vectors is like this:

angle = math.atan2(v1:Cross(v2).Magnitude, v1:Dot(v2))

This avoids floating point numerical instability you get with math.acos(v1.Unit:Dot(v2.Unit)) when the two vectors are closely aligned and the angle is small.

Often, I find myself needing a signed angle from some vector to another, w.r.t. to some reference rotation axis. For that, I wrote this function:

local function SignedAngleFromV1toV2( v1, v2, axis )
	local cp = v1:Cross(v2)
	local dp = v1:Dot(v2)
	local angle = math.atan2(cp.Magnitude,dp)
	return if cp:Dot(axis) >= 0 then angle else -angle
end

This function requires that you pass in a rotation axis, which shouldn’t be orthogonal to v1 and v2 and is used as the rotation axis reference for deciding if v1 rotates positive or negative to reach v2, per right-hand rule.

1 Like