# Getting the angle of a part relative to another part

Hello everyone, recently while trying to code a traversing turret I came across a problem with limiting the traversal amounts,
Baseplate = center (DOES NOT ROTATE)

Rpart = rotating cannon (DOES ROTATE)

So, I have a center of the turret (Baseplate)
and I want to get the angle the Rpart is facing relative to this Baseplate
how would I get that?

I hope this image clarifies further what I am looking for:

here is one method to do it props to @ThanksRoBama in this turret post.

``````--Function for a hinge constraint
local function calculateServoAngle(hinge : HingeConstraint, targetPosition : Vector3)
local baseAttachment = hinge.Attachment0

local object_horizontal_offset = (baseAttachment.WorldCFrame):PointToObjectSpace(target.Position)
local object_yaw_angle = math.atan2(object_horizontal_offset.Y, -object_horizontal_offset.Z)
object_yaw_angle = math.deg(object_yaw_angle)

return object_yaw_angle
end
``````

This is how it’s done, the axis is based on the CFrame it is being pointed to object space.

Origin is equal to the baseAttachment.WorldCFrame in the above case for a hinge constraint

(baseAttachment is the attachment attached to the base that doesn’t move not the turret, depends on how you setup the hinge constraint)

For the atan you might need to swap the axis. Y/-Z in the case for a hinge constraint, you might need to do X/Z for a vertical angle or horizontal angle whatever should be easy to mess around and find. Just remember it’s based on the CFrame axis it’s relative to baseAttachment in the above case.

1 Like

Whoops, the above method works but not specifically for part-part. More like part-target position

This should also work

``````local cframeRotationalDifference = basePartCFrame:ToObjectSpace(turretPartCFrame)

local x,y,z = cframeRotationalDifference:ToOrientation()-- angles in radians
``````
2 Likes

You are a king! Thanks, mate worked perfectly! I hope others can use this post, as I couldn’t find any relating to this exact problem.

1 Like