Tank turret vertical point to mouse with hinge servo

im working on a tank and the gun wont rotate to the mouse correctly

video:

code:

local tankSpaceAimPoint = chassis.Turret.GunRotateBase.Attachment0.WorldCFrame:ToObjectSpace(mouse.Hit)
local pitchAngle = math.atan2(tankSpaceAimPoint.Y, tankSpaceAimPoint.Z)
-- changing the negative value of the aimpoints didnt change anything

turret.TargetAngle = math.deg(pitchAngle)

circled hinge is “attachment0”


image

Are you referring the red, long gun at the end, or the spinning seating area?

the one moving up and down the red stick is to show where its pointing

fix found

took a while but found a solution

new code:

local turretOrigin = chassis.Turret.GunRotateBase

local x = math.abs(mouse.Hit.Position.X - turretOrigin.Position.X)
local y = math.abs(mouse.Hit.Position.Y - turretOrigin.Position.Y)
local angle = math.atan2(y, x)
if mouse.Hit.Position.Y < turretOrigin.Position.Y then
	angle = -angle
end
turret.TargetAngle = math.deg(angle)