How to make turret only be able to turn left and right?

Ok, so here is my issue, I’ve created some tanks, and I’ve got it so i t can aim at the the mouse position, but i only want one part to turn left/right, and the other up and down, here is a video demonstrating what i mean:

And here is my code

Client:

--[ VARIABLES ]--
local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()

--[ SERVICES ]--
local UserInputService = game:GetService("UserInputService")

--[ MAIN ]--
while true do
	wait(0.001)
	game.ReplicatedStorage.TankTurretEvent:FireServer(Mouse.Hit.Position, Mouse.TargetFilter)
end

Server:

game.ReplicatedStorage.TankTurretEvent.OnServerEvent:Connect(function(Player, MouseHit, TargetFilter)
	local LookAtX = CFrame.lookAt(script.Parent.Turret.PrimaryPart.Position, MouseHit)
	local Lerp = script.Parent.Turret.PrimaryPart.CFrame:Lerp(LookAtX, 0.010)
	
	script.Parent.Turret:SetPrimaryPartCFrame(Lerp)
end)

Please help, and thank you!

1 Like
game.ReplicatedStorage.TankTurretEvent.OnServerEvent:Connect(function(Player, MouseHit, TargetFilter)
	local LookAtX = CFrame.lookAt(script.Parent.Turret.PrimaryPart.Position, Vector3.new(MouseHit.X, 0, MouseHit.Z))
	local Lerp = script.Parent.Turret.PrimaryPart.CFrame:Lerp(LookAtX, 0.010)
	
	script.Parent.Turret:SetPrimaryPartCFrame(Lerp)
end)

change the server script to this(should work)

1 Like

It still does the same thing ( sorry for my late reply )

1 Like
local turretCF = script.Parent.Turret.PrimaryPart.CFrame
local barrelCF = script.Parent.Barrel.PrimaryPart.CFrame
local barrelOffset = turretCF:ToObjectSpace(barrelCF)
local facingVector = (turretCF.Position - MouseHit).Unit
local horizontalDir = facingVector * Vector3.new(1, 0, 1)
local verticalAngle = math.atan2(facingVector.X, facingVector.Y)

turretCF = CFrame.lookAt(turretCF.Position, turretCF.Position + horizontal, turretCF.UpVector)
barrelCF = turretCF * barrelOffset * CFrame.FromAxisAngle(Vector3.new(1, 0, 0), verticalAngle)

script.Parent.Turret:SetPrimaryPartCFrame(turretCF)
script.Parent.Barrel:SetPrimaryPartCFrame(barrelCF)

(I don’t know what your barrel is called so I just did script.Parent.Barrel)

2 Likes

Thanks for the reply, and sorry for my late response, the solution does the trick, some parts can only aim on XZ/ and some Y, but it seems to change the orientation of the parts, or face the opposite direction all together sometimes:

image

Fixed hopefully, edited the code. charactersssss