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

How can I improve my zombie path finding script?

Asked by 3 years ago

So I've made a zombie path finding script that works but not very well (The zombies moving stutters a lot) I know there is a way better way to make this and I was wondering how that would be done.

here is my code:

wait(5) -- Just giving time for the character to load in and also give me time for testing

local PFS = game:GetService("PathfindingService")
local marker = game.Workspace.PathfindingMarker
local Zomhum = script.Parent.Humanoid
local ZomhumRoot = script.Parent.HumanoidRootPart
local players = game.Workspace.Players:GetChildren() -- i have another script that moves all the characters into a folder in the workspace

local target = nil
local targetLastPos = nil

local currentTarget = nil
local closestTarget = math.huge
local chosenTarget = nil

for i, player in pairs(players) do
    local playerDistance = (player.HumanoidRootPart.Position - ZomhumRoot.Position).magnitude
    currentTarget = playerDistance

    if currentTarget <= closestTarget then
        closestTarget = currentTarget
        chosenTarget = player

    elseif currentTarget > closestTarget then
        print("")
    end
end

local function ComputePath()
    local path = PFS:CreatePath()
    path:ComputeAsync(ZomhumRoot.Position, chosenTarget.HumanoidRootPart.Position)
    local waypoints = path:GetWaypoints()

    local x = 0
    local targetPrevPos = chosenTarget.HumanoidRootPart.Position
    for i, waypoint in pairs(waypoints) do
        x=x+1
        Zomhum:MoveTo(waypoint.Position)
        Zomhum.MoveToFinished:Wait()
        if chosenTarget.HumanoidRootPart.Position ~= targetPrevPos and x >= 3 then -- im using the x >=3 to try and make the movement a bit smoother
            x = 0
            ComputePath()
        end 
    end
end

ComputePath()

Answer this question