I want to make a script where a monster moves to a player with pathfinding
I have tried detecting where the player’s torso is and moving to said torso with pathfinding, however it makes the monster run around in circles. Script:
local zombTorso = script.Parent:WaitForChild("Monster_Torso")
local hum = script.Parent:WaitForChild("Humanoid")
local pathfinding_service = game:GetService("PathfindingService")
local animation = script.Run
local animationTrack = hum:LoadAnimation(animation)
local function findTarget()
local agroDistance = 50000 --distance for where the zombie can attack
local target = nil
for _, object in pairs(game.Workspace:GetChildren()) do --looping through every object in workspace to find a humanoid and a torso
local human = object:FindFirstChild("Humanoid") --searching for said humanoid
local torso = object:FindFirstChild("Torso") --searching for said torso
if human and torso and object ~= script.Parent then --if the object has a humanoid and a torso and its not the zombie's then below will run
-- check distance
if (zombTorso.Position - torso.Position).magnitude < agroDistance then --if the distance between the zombie and the nearest player is less than 100 then the below will run
agroDistance = (zombTorso.Position - torso.Position).magnitude --with each step the zombie takes, its setting the agro distance lower and lower
target = torso --setting the target to be the nearest player's torso
end
end
end
return target --allowing us to use the target later
end
while wait(0.08) do
local torso = findTarget() --since we returned the target, we can get the torso in this thread
if torso then --if torso isn't set to nil then
local path = pathfinding_service:CreatePath()
local success, errorMessage = pcall(function()
path:ComputeAsync(zombTorso.Position, torso.Position)
local part = Instance.new("Part")
part.Anchored = true
part.BrickColor = BrickColor.new("Really red")
part.Material = "Neon"
part.Size = Vector3.new(0.8, 1, 0.75)
part.Position = zombTorso.Position
part.Parent = game.Workspace
animationTrack:Play(0, 30)
end)
if success and Enum.PathStatus.Success then
local waypoints = path:GetWaypoints()
for _, waypoint in pairs(waypoints) do
if waypoint.Action == Enum.PathWaypointAction.Jump then
hum:ChangeState(Enum.HumanoidStateType.Jumping)
end
hum:MoveTo(waypoint.Position)
hum.MoveToFinished:Wait(1)
end
end
else
hum:MoveTo(zombTorso.Position + Vector3.new(math.random(-10, 10), 0, math.random(-10, 10))) --if there arent any player's nearby, the zombie will move side-to-side
end
end
Video:
Any help will be appreciated