Hi, all. I have a script in a Humanoid that is supposed to find a random player and use Roblox's pathfinding service to maneuver its way around walls to get to the player.
But the Humanoid doesn't go anywhere, and there are no errors in the output.
Here's the script inside the Humanoid:
local root = script.Parent.Parent.HumanoidRootPart -- Get the zombie's HumanoidRootPart function moveToPlayer() -- Declare the function local players = game.Players:GetPlayers() -- Get a list of players for _, each in ipairs(game.Players:GetPlayers()) do -- Find a random player local char = each:FindFirstChild("Character") -- Get player's character... if char then -- ...and check if it exists local human = char.Humanoid -- Get the char's humanoid if human.Health > 0 then -- Check if the humanoid still alive local pRoot = human.Parent.HumanoidRootPart -- Get the character's HumanoidRootPart local path = game:GetService("PathfindingService"):ComputeRawPathAsync(root.Position, pRoot.Position, 500) -- Compute a path local points = path:GetCoordinates() -- Get a list of the coordinates for i = 1, #points do script.Parent:MoveTo(points[i]) -- Make the zombie move along the points end end end end end while wait() do moveToPlayer() end
Please help me. I'll give you a free, imaginary, figurative, nonexistent cookie if you do!
There are two problems with the code you have written. The first is that you are running the follow code for every player, rather than choosing a random player. The second is that Humanoid:MoveTo doesn't yield, so in a loop with no waits the zombie will almost instantly start heading to the final point in the list. Below is an example of your code where these problems are corrected.
local root = script.Parent.HumanoidRootPart local rand = Random.new() local function Path() local players = game.Players:GetPlayers() if #players > 0 then -- From the list of all players, choose a random player local playerToFollow = players[rand:NextInteger(1, #players)] if playerToFollow.Character and playerToFollow.Character.Humanoid.Health > 0 then local pRoot = playerToFollow.Character.HumanoidRootPart local path = game:GetService("PathfindingService"):ComputeRawPathAsync(root.Position, pRoot.Position, 500) local points = path:GetPointCoordinates() for i = 1, #points do script.Parent.Humanoid:MoveTo(points[i]) repeat -- Wait until we are close to a point before moving to the next local distance = (points[i] - root.Position).magnitude wait() until distance < 3 end end end end -- The number inside wait will determine how long the zombie idles at -- the end of a path before starting to follow another player while wait(1) do Path() end