I’m creating a zombie game with a friend and I was tasked with scripting the zombie AI, it works pretty good however it twitches while walking and I can’t figure out why. If somebody knows how to fix this please let me know how.
Thanks in advance to all who reply
Here’s my code:
local PathFindingService = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local root = character:WaitForChild("HumanoidRootPart")
root:SetNetworkOwner(nil)
local followRange = 70 -- In studs
local lastWander = tick()
local function createPath(a, b)
local size = character:GetExtentsSize()
local params = {
["AgentRadius"] = (size.X + size.Z) / 4,
["AgentHeight"] = size.Y,
["AgentCanJump"] = true,
}
local path = PathFindingService:CreatePath(params)
local created, result = pcall(function()
return path:ComputeAsync(a, b)
end)
if created then
return path
else
warn(result)
end
end
local function walkTo(path)
if not path then
return
end
local waypoints = path:GetWaypoints()
for _, waypoint in pairs(waypoints) do
if waypoint.Action == Enum.PathWaypointAction.Jump then
humanoid.Jump = true
end
humanoid:MoveTo(waypoint.Position)
local timeOut = humanoid.MoveToFinished:Wait()
if not timeOut then
humanoid.Jump = true
walkTo(path)
end
end
end
function getTarget()
local least = math.huge
local instance = nil
for _, player in pairs(Players:GetPlayers()) do
local char = player.Character
if char then
local mag = (char.HumanoidRootPart.Position - root.Position).Magnitude
if mag < least and mag <= followRange then
least = mag
instance = char.HumanoidRootPart.Position
end
end
end
return instance
end
while wait(0.5) do
local target = getTarget()
if target then
local path = createPath(root.Position, target)
coroutine.wrap(walkTo)(path)
else
if tick() - lastWander >= 5 then
local randX = math.random(-10, 10)
local randZ = math.random(-10, 10)
humanoid:MoveTo(Vector3.new(randX, 0, randZ))
humanoid.MoveToFinished:Wait()
lastWander = tick()
end
end
end