Calculate Angle (Degree) between to vector positions

Hello, I posted a few days ago about a similar issue. But now I’ve scratched that and I’m using hinge constraints, however I’m having trouble finding the formula to calculate the angle required for the gun barrel to aim towards the target. See photos

image
image

Any help is appreciated

Angle between 2 Vector3s? Just use CFrame.lookAt and derive the angle from its orientation

Something like this? image
I’ve tried this and this while using math.deg() and no luck, sorry CFrames completely go over my head :joy:

Try using :GetOrientation() on the CFrame to get its individual angles.

--example
local cf = CFrame.lookAt(...)
local x, y, z = cf:ToOrientation()

Also, another possible way of getting the angle between 2 vectors would be to take the dot product of the vectors, but that’s linear algebra :slight_smile:

Vector3s work with no effective difference to a 2-dimensional vector as far as the fundamental math goes.

To calculate this with math you would use dot product (which is essentially v1.mag*v2.mag*cos(angle between vectors). Fortunately Roblox has v1:Dot(v2) for this, which saves some trouble.

This would be the math required to get the angle between two vectors:

a = workspace.a
b = workspace.b

dot = a.Position:Dot(b.Position)

m_a = a.Position.Magnitude
m_b = b.Position.Magnitude

angle_between = math.deg(math.acos((dot)/(m_a*m_b)))

print(angle_between)
1 Like

I only get 5 degrees returned

image

Probably because this is solving for the overall angular difference between two 3D vectors, and because magnitude cannot be negative in nature you have no actual direction, just the angle difference. This angle difference could never be > math.pi.

Here’s a better approach to get the actual angle:

a = workspace.a
b = workspace.b

axis1, axis2 = "X", "Y"

p_v = a.CFrame:PointToObjectSpace(b.Position)
angle = math.deg(math.atan2(p_v[axis2], p_v[axis1]))
1 Like

Hey why don’t you just try my original solution that uses CFrame.lookAt

local p1 = workspace.a.Position
local p2 = workspace.b.Position
local angle = math.deg(CFrame.lookAt(p1, p2):ToOrientation())
print(angle)
2 Likes

Sorry didn’t see you post it, that works thanks :slight_smile:

Thanks for helping aswell, SummerEquinox

I know your post is old, but it has helped me out with a problem I have been trying to solve for a week now. Thanks!