How to move turret cannon up and down?

Can you send your current code?

local RunService = game:GetService("RunService")
local Turret = script.Parent.Turret
local Hull = script.Parent.Hull
local Gun = Turret.Gun.Barrel



RunService.Heartbeat:Connect(function()	
	if Turret:FindFirstChild("TurretSeat") then
		if Turret.TurretSeat.Steer == 1 then
			Turret:PivotTo(Turret:GetPivot() * CFrame.Angles(0, -math.rad(1), 0))
		elseif Turret.TurretSeat.Steer == -1 then
			Turret:PivotTo(Turret:GetPivot() * CFrame.Angles(0, math.rad(1), 0))
		end
		if Turret.TurretSeat.Throttle == 1 then
			Gun.CFrame = Gun:GetPivot() * CFrame.Angles(0, 0, -math.rad(1))
		elseif Turret.TurretSeat.Throttle == -1 then
			Gun.CFrame = Gun:GetPivot() * CFrame.Angles(0, 0, math.rad(1))
		end
	end
end)	
1 Like

Hopefully this works for you since I can’t test and debug it, I added some comments to explain the best I can what I did, if it doesn’t work just reply back with the error.

local steer = 0
local throttle = 0

local abs = math.abs --let's localize this function since we're going to be calling it a lot!

RunService.Heartbeat:Connect(function()	
	local turretSeat = Turret:FindFirstChild("TurretSeat") --save turretseat as variable since we're going to be reading it multiple times
	
	if turretSeat then
		
		--[[
		```
		turretSeat.Steer ~= 0 and (abs(steer + turretSeat.Steer)) < (MAX_STEER + 1)
        ```
        This gets the current steer amount and adds the direction the player wants to go, then it calls math.abs() on it,
        which turns it into a positive number if it's a negative number, then checks if the steer we're going is going to be
        the max steer which if it is then if statement fails, the + 1 is to account for the + turretSeat.Steer that can add a 1
		]]--
		if turretSeat.Steer ~= 0 and (abs(steer + turretSeat.Steer)) < (MAX_STEER + 1) then
			--[[
			Instead of using ifs and repeating ourselves we can just use the steer value since it's already going to 1 or -1
			don't repeat yourself when possible! (even though we're kinda repeating ourselves right here)
			]]--
			steer += turretSeat.Steer
			Turret:PivotTo(Turret:GetPivot() * CFrame.Angles(0, math.rad(turretSeat.Steer), 0)) 
		end
		
		--same thing here
		if turretSeat.Throttle ~= 0 and ((abs(throttle + turretSeat.Throttle)) <(MAX_THROTTLE + 1)) then
			throttle += turretSeat.Throttle
			Gun.CFrame = Gun:GetPivot() * CFrame.Angles(0, 0, math.rad(turretSeat.Throttle))
		end
	end
end)
1 Like

Works perfectly, thanks for the help!
Now ill try to make the driver but i can hopefully just use an already made script

i noticed another issue, if a part it blocking the turret, it just slides off to the side, how could i fix this? The barrel also does this
grafik

Fixed both of the problems by replacing the Welds and so on with Motor6D’s

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