I’m having an issue in my game with a “sentry” system. The sentry is supposed to face a target when one is detected. While it works, the results are inconsistent and not what I expected.
I’ve included a video showing the issue for better context.
local currentAngleY = HorizontalDrive.CFrame:ToEulerAnglesYXZ() -- Get the initial Y-axis angle of HorizontalDrive
local currentAngleX = VerticalDrive.CFrame:ToEulerAnglesYXZ() -- Get the initial X-axis angle of VerticalDrive
local function rotateAndFaceTarget(deltaTime)
if SAM.Target.Value == nil then
SAM.Base.Move:Stop()
return
end
if not SAM.Base.Move.IsPlaying and SAM.Target.Value ~= nil then
SAM.Base.Move:Play()
end
local directionToTarget = ( SAM.Target.Value.Position - HorizontalDrive.Position).unit
local targetAngleY = math.atan2(directionToTarget.X, directionToTarget.Z) -- Target angle on Y-axis
local angleDifferenceY = math.atan2(math.sin(targetAngleY - currentAngleY), math.cos(targetAngleY - currentAngleY))
local rotationStepY = math.clamp(angleDifferenceY, -math.rad(rotationSpeed * deltaTime), math.rad(rotationSpeed * deltaTime))
currentAngleY = currentAngleY + rotationStepY
HorizontalDrive.CFrame = CFrame.new(HorizontalDrive.Position) * CFrame.Angles(0, currentAngleY, math.rad(90))
--verticle
local targetAngleX = math.atan2(directionToTarget.Y, directionToTarget.Z)
local angleDifferenceX = math.atan2(math.sin(targetAngleX - currentAngleX), math.cos(targetAngleX - currentAngleX))
local rotationStepX = math.clamp(angleDifferenceX, -math.rad(rotationSpeed * deltaTime), math.rad(rotationSpeed * deltaTime))
currentAngleX = currentAngleX + rotationStepX
local newC0 = CFrame.new(Pole.VerticleDrive.C0.Position) * CFrame.Angles(0, -currentAngleX + math.rad(90), math.rad(90))
Pole.VerticleDrive.C0 = newC0
end
game:GetService("RunService").Heartbeat:Connect(rotateAndFaceTarget)