Help with angles for hinge welds

I am having an issue where my turret only turns to face my mouse on the up/down axis on only one specific side, the side the turret faces in to start. After you go beyond 90 degrees from the starting angle of 0 on either side along the yaw, it breaks and goes in some extreme angle.

Video of what is the issue:
robloxapp-20210414-1842519.wmv (3.8 MB)

The code responsible for angling the turret:

-- Code for the angling
while wait() do
	local Mouse = game.Players.LocalPlayer:GetMouse()
	
	Mouse.TargetFilter = game.Workspace.BrenLMGTurret
	
	local MouseTargetPos = Mouse.Hit.Position
	
	local OriginPointYaw = Vector2.new(game.Workspace.BrenLMGTurret.YawAxis.Position.X, game.Workspace.BrenLMGTurret.YawAxis.Position.Z)
	local TargetPointYaw = Vector2.new(MouseTargetPos.X, MouseTargetPos.Z)
	local AngleYaw = math.atan2((TargetPointYaw.Y-OriginPointYaw.Y), (TargetPointYaw.X-OriginPointYaw.X))
	
	local OriginPointPitch = Vector2.new(game.Workspace.BrenLMGTurret.PitchAxis.Position.X, game.Workspace.BrenLMGTurret.PitchAxis.Position.Y)
	local TargetPointPitch = Vector2.new(MouseTargetPos.X, MouseTargetPos.Y)
	local AnglePitch = math.atan2((TargetPointPitch.Y-OriginPointPitch.Y), (TargetPointPitch.X-OriginPointPitch.X))
	
	AngleYaw = math.deg(AngleYaw)
	AnglePitch = math.deg(AnglePitch)
	

	game.Workspace.BrenLMGTurret.YawAxis.YawConstraint.TargetAngle = -AngleYaw
	game.Workspace.BrenLMGTurret.PitchAxis.PitchConstraint.TargetAngle = AnglePitch
	
end

The actual turret if you want to download it and test it:
Turret.rbxm (69.9 KB)

  1. Your AngleYaw should be math.atan2(-dZ, dX) (and then un-negate your constraint angle I think)
  2. Your AnglePitch can be math.asin(dY / magnitude)
	local DirYaw = MouseTargetPos - workspace.BrenLMGTurret.YawAxis.Position
	local AngleYaw = math.atan2(-DirYaw.Z, DirYaw.X)

	local DirPitch = MouseTargetPos - workspace.BrenLMGTurret.PitchAxis.Position
	local AnglePitch = math.asin(DirPitch.Y / DirPitch.Magnitude)
1 Like