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

Why is my NPC's Movement's So Laggy?

Asked by 3 years ago

Basically what I'm doing is having the npc chase the closest player, it works fine, however the movements are super choppy and it just looks very bad, anyone know why this is?

--Services
local players = game:GetService("Players")
local ps = game:GetService("PathfindingService")
local runserv = game:GetService("RunService")

--Asset Variables
local staff = script.Parent
local staffHum = staff.Humanoid
local staffHRP = staff.HumanoidRootPart

--Find Destination(The Closest Player)
local function findClosestPlayer()
    local closestPlayer 
    local closestMag = 50
    for _, player in pairs(players:GetPlayers()) do
        if player.Character then
            local playerHRP = player.Character:FindFirstChild("HumanoidRootPart")
            if playerHRP then
                local mag = (staffHRP.Position - playerHRP.Position).Magnitude
                if mag < closestMag then
                    closestPlayer = player.Character
                    closestMag = mag
                end
            end
        end
    end
    if closestPlayer then
        return closestPlayer
    end
end

local function chaseClosestPlayer()
    --Pathfinding
    local dest = findClosestPlayer()
    local path = ps:CreatePath()
    if dest ~= nil then
        path:ComputeAsync(staffHRP.Position, dest.PrimaryPart.Position)
        local waypoints = path:GetWaypoints()
        for _, waypoint in pairs(waypoints) do
            staffHum:MoveTo(waypoint.Position)
            staffHum.MoveToFinished:Wait()
        end
    end
end

runserv.Heartbeat:Connect(chaseClosestPlayer)
0
Well, I don't think mine is a solution but I'd suggest you to not updating the WayPoints everytime. It causes lag. Xapelize 2658 — 3y

Answer this question