Calculate angle between two vectors (including negative angles)

I am trying to figure out a way to calculate the angle between two vectors, but I have a hard time figuring out a way to include negative angles as well as positives. Here’s what I have done so far (where the angle is in the interval [0, pi]:

local a = Vector3.new(0,script.Parent.CFrame.LookVector.Y,0)
local b = Vector3.new(target.X-script.Parent.Position.X,target.Y-script.Parent.Position.Y,target.Z-script.Parent.Position.Z)
local r = math.acos(a:Dot(b)/(a.Magnitude*b.Magnitude))
2 Likes

Assuming negative angles means clockwise, you can use the fact that the sign of the Y component of the resulting cross product of two vectors determines which direction a rotation is being applied, clockwise or anticlockwise, negative or positive. If the sign of Y component of the vector resulting from a:Cross(b) is positive, that basically means in order to get from a to b you need to rotate anticlockwise (positive angle), if it’s negative, that basically means in order to get from a to b you need to rotate clockwise. If you flip the order, b:Cross(a) the sign determines in what direction you need togo to get from b to a and not a to b, so there is a difference. Imagine it in your brain.

Then you simply use math.sign on the Y componener which will return -1 if it’s negative or 1 if it’s positive and you multiply the angle by that.

local sign = math.sign(a:Cross(b).Y)
local r = (the equation) * sign
8 Likes

What is this for? There might be another method of accomplishing the goal.

Not sure if this works or not. Let’s call a and b 2 Vector3, we have:

 Angle = acos((a.x * b.x + a.y * b.y + a.z * b.z)/(math.sqrt(a.x + a.y + a.z)*sqrt(b.x + b.y + b.z)))

If you want to get Angle from Vector2, we have:

Angle = acos((a.x * b.x + a.y * b.y)/(math.sqrt(a.x + a.y)*sqrt(b.x + b.y)))

You basically converted what he already did into a version without using any built-in features. Also when calculating magnitude you need to square the components which you aren’t doing.