Hello! I’m trying to make a tank turret system where the turret follows the driver’s mouse and I have come up with the following system:
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")
local Players = game:GetService("Players")
local Motor = Workspace:WaitForChild("Passive"):WaitForChild("Motor6D")
local Mouse = Players.LocalPlayer:GetMouse()
RunService.Heartbeat:Connect(function()
local NewCFrame = CFrame.new(Motor.Parent.Position, Mouse.Hit.Position)
local X, Y, Z = NewCFrame:ToEulerAnglesYXZ()
print(math.deg(Y))
Motor:SetDesiredAngle(-Y)
end)
And it works pretty well in most cases:
But I have ran into an issue when the target rotation of the turret goes from being 179 to -179 and vice versa which causes the turret to rotate the “wrong way” to get to the new point which looks rather strange:
Please reply if you have any idea on how to combat this issue. Thanks in advance!
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")
local Players = game:GetService("Players")
local Motor = Workspace:WaitForChild("Passive"):WaitForChild("Motor6D")
local Mouse = Players.LocalPlayer:GetMouse()
local DegPerSec = 5 -- replace this with the correct value
local radPerSec = math.rad(degPerSec)
local lookVec = CFrame.new(Motor.Parent.Position, Mouse.Hit.Position).LookVector
local currentAngle = math.atan2(lookVec.X, lookVec.Z)
RunService.Heartbeat:Connect(function(delta)
local targetDir = Motor.Parent.Position-Mouse.Hit.Position
local targetAngle = math.atan2(targetDir.X, targetDir.Z)
local difference = targetAngle-currentAngle
local angleToAdd
if math.abs(difference) > math.pi then
angleToAdd = -math.sign(difference)*(math.abs(difference)-math.pi)
else angleToAdd = difference
end
angleToAdd = math.clamp(angleToAdd, -radPerSec*delta, radPerSec*delta)
Motor.C0 *= CFrame.Angles(0, angleToAdd, 0)
currentAngle += angleToAdd
end)