Attachments used relative CFrames (attachments CFrames are relative to the CFrame the part it is parented in), for the calculation to work with a world space vector such as mouse Hit position relative to 0,0,0 you use .WorldCFrame instead.
However even that might have issues if the base is rotated. Then you will also need to point to object space for that:
Just use my function It should handles pitch and yaw using PointToObjectSpace.
This is assuming the attachment0 is connected to the base of the turret which is not the one rotating, you might need to swap and modify yours if you set it up differently, though the math should be the same.
local function calculateServoAngle(hinge, targetPosition)
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
local head = workspace.Head
local hinge = script.Parent
local function calculateServoAngle(hinge, targetPosition)
local baseAttachment = hinge.Attachment0
local object_horizontal_offset = (baseAttachment.WorldCFrame):PointToObjectSpace(targetPosition)
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
while true do
hinge.TargetAngle = calculateServoAngle(hinge, head.Position)
task.wait()
end
Hmmm well anyways I got it working but thanks for your help. I probably came across as dumb lol because I’ve never worked with this before. Sorry for wasting your time