Angle between two 2D vectors

Hello guys!

I am trying to calculate the angle between two “2D” vectors (3D vectors excluding the XZ plane).
The first vector a is the position of a part, while vector b is the player’s mouse.Hit.p.

This is my code so far:

local a = script.Parent.Position
local b = mouse.Hit.p
local index = math.acos(a:Dot(b)/(a.Magnitude*b.Magnitude))
local angle = math.deg(index)
2 Likes

Any suggestions on how to solve this? :slight_smile:

Personally not sure what you’re currently doing, but I would try using tangent.
You would actually want to use atan2 and pass it like math.atan2(B.y - A.y, B.x - A.X) iirc.

image

4 Likes

Yeah this is partially correct, it shows the correct angle only when I am facing the positive direction along the X axis

angle = arccos(a dot b)

a and b are unit vectors

Use mypositionvector = mypositionvector.unit to get the unit vector

Note that the location of the angle will be the origin (0, 0, 0)

I will be back later if you need more help, this was a quick post. I have to go now.

1 Like

Your code segment should work, aside from the fact that mouse.Hit.p only runs once, but I’m chalking that up to simplicity.

Do you have an erroneous result you could show us? Is there something unexpected?

Okay, I’m back. Your code works, though the result may be in degrees already, so be sure to check on that. Also note that the position of the angle (per say, can’t remember the math word) is at the origin with your current code. If you want the position to be somewhere else, do this:
a = otherpos - script.Parent.Position
b = otherpos - mouse.Hit.p