How to make a turret on ship move to mouse position with hinge constraint

I want the turret to move to the mouse’s position but it just bugs out. This is what I have so far:


My code: (GunRotateY is the hinge constraint and the type is set to servo)

local hinge = script.GunRotateY

mouseMovedEvent.OnServerEvent:Connect(function(player, mouseHitPos)
	
	local delta = mouseHitPos - hinge.Attachment0.CFrame.Position

	hinge.TargetAngle = math.deg(math.atan2(-delta.Z, delta.X))
	
end)

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:

Well I figured that out a bit ago but now my problem is making it go up and down. How would I do that?
This is what it’s like so far:

local myX = (mouseHitPos.Y - hingeX.Attachment0.WorldPosition.Y)
local myY = (mouseHitPos.Z - hingeX.Attachment0.WorldPosition.Z)

local theta = math.atan2(myX, myY)
hingeX.TargetAngle = math.deg(theta) + 180

Well actually my question is, how would I do this but do pitch instead of yaw?

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

How could it handle both. I will send you my turret. There is the base of it connected to the ship that rotates yaw and another one handles pitch.


The top one handles pitch so I can’t do yaw and pitch in one I need to figure out how to get the pitch from the angle

It works for both.

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