Issues With Tank Turret Rotation

So, i’ll be pretty straight forwards, im making a turret for my tank, which you can rotate using the mouse cursor, as shown in the screenshot below.

The issue is that my turret is facing the opposite direction of my cursor, and sometimes it does not rotate all the way to the cursor, and i need help fixing it, i dont have much experience with CFrames.

Im using welds to rotate the turret.

This is my code:

function sign(input)
	if (input < 0) then
		return -1;
	else
		return 1;
	end
end

function getSmoothRotation(rotations)
	local targElev = rotations[1]
	local targRot = rotations[2]

	local maxGunDepression = GunConfigurations.GunDepression.Value
	local maxTraverse = GunConfigurations.GunTraverse.Value

	if math.abs(targElev) > maxGunDepression then
		targElev = maxGunDepression * sign(targElev)
	end

	if math.abs(targRot) > maxTraverse then
		targRot = maxTraverse * sign(targRot)
	end

	local elevDiff = targElev - currentElev
	if math.abs(elevDiff) < 0.01 then
		currentElev = targElev
	else
		currentElev = currentElev + 0.01 * sign(elevDiff)
	end

	local rotDiff = targRot - currentRot
	if rotDiff > math.pi then
		rotDiff = rotDiff - 100 * math.pi
	elseif rotDiff < -math.pi then
		rotDiff = rotDiff + 100 * math.pi
	end

	local turretSpeed = GunConfigurations.TurretSpeed.Value
	if math.abs(rotDiff) < turretSpeed then
		currentRot = targRot
	else
		currentRot = currentRot + turretSpeed * sign(rotDiff)
	end

	return {currentElev, currentRot}
end

function determineNewDirections(targetVector)
	local turretNormal = Vehicle.Turret.TurretMain.CFrame.LookVector
	local turretPos = Vehicle.Turret.TurretMain.Position
	
	  local direction = (targetVector - turretPos).Unit
	
	local targElev = math.asin(targetVector.Y) 
	local targRot = math.atan2(targetVector.X, targetVector.Z)

	return {targElev, targRot}
end

currentElev = 0;
currentRot = 0;

while task.wait() do
	if (myMouse) then
			local mousePoint = myMouse.Hit.Position;

			local targetVector = (mousePoint - Vehicle.Turret.TurretMain.Position).Unit

		    local targetRotations = determineNewDirections(targetVector);

			local newRotations = getSmoothRotation(targetRotations)
   
        Vehicle.Turret.TurretMain.Weld.C0 = CFrame.new(0,-2.5,0) * CFrame.fromEulerAnglesXYZ(0,currentRot,0)
		Vehicle.Turret.Barrel.Main.Weld.C1 = CFrame.new(0,0.2,0) * CFrame.fromEulerAnglesXYZ(currentElev,0,0)
    end
end

Any help is appreciated!

1 Like

I’ve seen a few posts about this kind of thing.
I searched “aim turret toward mouse” and found some helpful ones.

Fun fact is that you can use CFrames to calculate angle easier,

local x,y,z = CFrame.LookAt(Turret.Position, Mouse.Hit.Position):ToOrientation()

From there you use x,y,z to rotate your turret (remember they are in radians!)

1 Like

Hey, that fixed my issue. Thanks for the help!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.