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

Why is a NPC With PathfindingService that follows the nearest player is "lagging" behind the player?

Asked by 5 years ago
Edited 5 years ago

So I have a NPC that uses PathfindingService, and is meant to follow the nearest player. But when I run from the NPC, no matter what, EVEN if it's WalkSpeed is bigger than mine, it always seems like there's a wall behind me that always blocks it. Script:

local h = script.Parent.Humanoid
local hPart = script.Parent.HumanoidRootPart

local PathfindingService = game:GetService("PathfindingService")

local path = PathfindingService:CreatePath()

local walkAnimation = script.Walk
local walk = h:LoadAnimation(walkAnimation)

local HumanoidRan

HumanoidRan = h.Running:Connect(function(speed)
    if speed > 0 then
        walk:Play()
    else
        walk:Stop()
    end
end)

local torso = script.Parent.HumanoidRootPart
local spawnCF = torso.CFrame

function FindPlayer()
    for _, v in next, game.Players:GetPlayers() do
        if v.Character then
            local char = v.Character
            if char:FindFirstChild("Humanoid") and char:FindFirstChild("HumanoidRootPart") then
                local ptorso = char.HumanoidRootPart
                if (ptorso.Position - torso.Position).magnitude <= 110 then
                    return v
                end
            end
        end
    end
    return nil
end

while wait() do
    local player = FindPlayer()
    if player ~= nil then
        path:ComputeAsync(hPart.Position, player.Character.HumanoidRootPart.Position)
        local waypoints = path:GetWaypoints()
        for _, waypoint in pairs(waypoints) do
            h:MoveTo(waypoint.Position)
        end
        if player.Character.Humanoid.Health <= 0 then
            player.Character.HumanoidRootPart:Destroy()
        end
    end
end

1 answer

Log in to vote
0
Answered by 5 years ago

It appears that you are running this in a while wait loop, and that you are finding a player all the time and continously calculating a new path - which explains why it "stops" all the time. I suggest you instead make it move to the first waypoint and once it has stopped- calculate a new path etc.

0
Can you show an example? AradIsHere 2 — 5y
Ad

Answer this question