Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I improve this pathfinding script? The zombies only go to the delayed player position.

Asked by
jakeovi -1
3 years ago

Script:

local pathfindingservice = game:GetService("PathfindingService")
local path = pathfindingservice:CreatePath()
local Zombie = script.Parent
local target
local player = game.Players:GetPlayers()[math.random(1,#game.Players:GetPlayers())]
if workspace:FindFirstChild(player.Name) then
    local char = workspace:FindFirstChild(player.Name)
    if char.Humanoid.Health > 0 then
        target = char
    end
end
local function changeTarget()
    local player = game.Players:GetPlayers()[math.random(1,#game.Players:GetPlayers())]
    if workspace:FindFirstChild(player.Name) then
        local char = workspace:FindFirstChild(player.Name)
        if char.Humanoid.Health > 0 then
            target = char
        end
    end
end

local function chaseTarget()
    if game.ReplicatedStorage:FindFirstChild(target.Name) then
        local goalPos = game.ReplicatedStorage[target.Name].Value
        local human = Zombie.Humanoid
        local torso = Zombie.Torso
        path:ComputeAsync(torso.Position, goalPos)
        local waypoints = path:GetWaypoints()
        for i, waypoint in pairs(waypoints) do
            if waypoint.Action == Enum.PathWaypointAction.Jump then
                human:ChangeState(Enum.HumanoidStateType.Jumping)
            end
            human:MoveTo(waypoint.Position)
            if target.Humanoid.Health <= 0 then
                changeTarget()
            end
            human.MoveToFinished:Wait()
        end
    end
end
while wait() do
    chaseTarget()
end

Answer this question