Hey y’all, recently for a small game project I’ve been working on I’ve decided to rewrite the classic zombie chasing script. And so far, it works! But I can’t say I’m all too happy with it. First things first, here’s the full code.
--[[ -=Variables=- ]]
-- Set to wherever the humanoid, humanoidrootpart, and all subsequent damageParts will be.
local npcRoot = script.Parent
local humanoid = npcRoot:WaitForChild("Humanoid")
local humanoidRootPart = npcRoot:WaitForChild("HumanoidRootPart")
local canDamage = script.Damage
local canChase = script.Chase
local startPosition = humanoidRootPart.Position
--[[ -=Functions=- ]]
-- Loop through body and set networks to nil
for i, v in pairs(npcRoot:GetChildren()) do
if v:IsA("BasePart") then
v:SetNetworkOwner(nil)
end
end
local foundPlayer = false
-- Get nearest torso and its magnitude
local function FindNearestPlayer()
local selfPos = humanoidRootPart.Position
local playerList = workspace:FindFirstChild("Players")
local target = nil
-- To change the range, use the value located inside of the script.
for i, v in pairs(playerList:GetChildren()) do
-- Find humanoidrootpart within detected player.
local playerRoot = v:FindFirstChild("HumanoidRootPart")
if playerRoot ~= nil then
-- Player root detected.
local playerPos = playerRoot.Position
local distance = (playerPos - selfPos).Magnitude
if distance < canChase.Range.Value then
-- Player is in range!
target = playerRoot
foundPlayer = true
return target
else
-- Player is out of range.
foundPlayer = false
target = humanoidRootPart
return target
end
end
--|
end
--|
end
while task.wait() do
if not canChase.Value then
break
end
local target = FindNearestPlayer()
if target ~= nil then
if foundPlayer then
humanoid:MoveTo(target.Position, target)
else
if not canChase.ReturnToStart.Value then
humanoid:MoveTo(target.Position, target)
elseif canChase.ReturnToStart.Value then
humanoid:MoveTo(startPosition)
end
end
end
end
Now, feel free to call me crazy, but the unresponsiveness of my script compared to RetroStudio is very apparent to me. I’m not the best at coding, so getting help from somebody with more knowledge on this stuff would be appreciated! Any tweaks for optimization reasons are appreciated too.
A big issue I have with the script right now is how wide of turns the NPC takes when you circle around them. Compared with RetroStudio, they remain closer to the player when circling around them. Both humanoids use the same walkspeed.