Tank barrel rotating improperly

I am trying to get my tank barrel to slowly aim towards it’s target without using hingeconstraints, instead i am using cframes.

my code works perfectly fine until the target crosses from 180 radians to -180 radians and the turret tries to rotate the long way.

this topic might have been posted before but as far as I have looked on the Devforum I haven’t found anything. please don’t respond with just a link to another post, it would be much more helpful for a more direct response. Thanks!

my current code:

while wait(0.01) do
	
	pos2 = script.Parent.Position
	script.Parent.WeldConstraint:Destroy()
	
	g = script.Parent.Orientation.Y - script.Parent.Parent.Pike.Orientation.Y
	--g2 = g2 * -1
	--script.Parent.CFrame = script.Parent.CFrame + script.Parent.CFrame.LookVector * Vector3.new(script.Parent.Speed.Value * script.Parent.po.Value, script.Parent.Speed.Value * script.Parent.po.Value, script.Parent.Speed.Value * script.Parent.po.Value)
	if g < 0 then
		script.Parent.CFrame = script.Parent.CFrame * CFrame.fromEulerAnglesXYZ(0, 0.05, 0)
	elseif g > 0 then
		script.Parent.CFrame = script.Parent.CFrame * CFrame.fromEulerAnglesXYZ(0, -0.05, 0)
	end
	script.Parent.g.Value = g
	--[[
	if g > p then
		script.Parent.CFrame = script.Parent.CFrame * CFrame.fromEulerAnglesXYZ(0, 0.001, 0)
	else
		script.Parent.CFrame = script.Parent.CFrame * CFrame.fromEulerAnglesXYZ(0, -0.001, 0)
	end
	]]
	script.Parent.Position = pos2
	weldconstraint = Instance.new("WeldConstraint")
	weldconstraint.Parent = script.Parent
	weldconstraint.Part1 = script.Parent
	weldconstraint.Part0 = script.Parent.Parent.Base
end
1 Like