Tank turret works fine when facing forward, breaks when facing any other direction

Here’s my code, it takes the player’s mouse lookvector:

function LightTank:SetTurretLookVector(lookVector: Vector3)
	local side = -math.deg(math.atan2(lookVector.Z, lookVector.X)) - 90
	local up = math.deg(math.atan2(lookVector.Y, -lookVector.Z))
	
	local cannon = self.Model.CannonAssembly
	local upHinge: CylindricalConstraint = cannon.GunMount.RollController
	local turretRing: CylindricalConstraint = cannon.TurretMount.TurretRing
	
	upHinge.TargetAngle = up
	turretRing.TargetAngle = side
	
	print("Tried to go to", side, up)
end

To clarify, the turretRing controller (labeled “side”) works fine, but the upHinge controller breaks when the turret inverts.

there is a problem with how the upHinge controller.

function LightTank:SetTurretLookVector(lookVector: Vector3)
local side = -math.deg(math.atan2(lookVector.Z, lookVector.X)) - 90
local up = math.deg(math.atan2(lookVector.Y, -lookVector.Z))

local cannon = self.Model.CannonAssembly
local upHinge: CylindricalConstraint = cannon.GunMount.RollController
local turretRing: CylindricalConstraint = cannon.TurretMount.TurretRing

turretRing.TargetAngle = side

-- Limit the range of motion for upHinge when the turret is facing downwards
if up > 90 then
    up = 90
elseif up < -90 then
    up = -90
end

upHinge.TargetAngle = up
    
print("Ayo", side, up)

end

This code limits the range of motion for upHinge to between -90 and 90 degrees, which should prevent it from breaking when the turret is facing downwards.

1 Like

I prefer using math.clamp instead of if then statements

1 Like

Not sure if that’s the solution to the exact issue I’m having. When the tank is facing forwards (+X direction), the gun works fine. However, when the lookVector points vaguely into the -X direction, the gun shoots into the floor.

This is obviously super weird because the up controller doesn’t even use the X value of our lookVector.