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
Hi, I tried making this but I only got it half-working (yaw only works once & pitch was very glitchy). Can I please get the file or model of the turret if you still have it? robloxapp-20241108-1731241.wmv (294.0 KB)