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

How do I fix my NPC from lagging behind me?

Asked by 3 years ago
Edited 3 years ago

My NPC that I've created looks like it is lagging / teleporting while it is walking towards its target. Here is a video of what I am talking about: www.youtube.com/watch?v=I7xmUE8QkRw&feature=youtu.be

The YouTube link does work, but only if you copy and paste it =P

This is the code that I have that is located inside of him.

local npc = script.Parent
local hum = script.Parent.Humanoid
local humRP = script.Parent.HumanoidRootPart
local distance = 50


local function moveToPlayer()
    local enemyFound = false
    local WS = workspace:GetChildren()
    if enemyFound == false then
        for i, v in pairs (WS) do
            if v:FindFirstChild("Humanoid") and v ~= npc and enemyFound == false then
                if (v.HumanoidRootPart.Position - humRP.Position).Magnitude <= distance and enemyFound == false then
                    enemyFound = true
                    print("Enemy is close")
                    local plr = v
                    local plrHumRP = plr.HumanoidRootPart
                    local target = plrHumRP
                    return target
                end
            end
        end 
    end
end


while true do
    wait(.01)
    moveToPlayer()
    local targ = moveToPlayer() 
    if targ ~= nil then
        hum:MoveTo(targ.Position)   
    end
end

Thank you everyone.

2 answers

Log in to vote
1
Answered by 3 years ago

Maybe try repeating at a less rate? The server can only handle so many things at a time, here's a little rewrite if this can help you understand some more. Feel free to use with my permission.

local Character = script:FindFirstAncestorOfClass("Model")
local Humanoid = Character:FindFirstChildOfClass("Humanoid")
local HumanoidRootPart = Humanoid.RootPart ~= nil and Humanoid.RootPart or Character:FindFirstChild("HumanoidRootPart")

local Distance = 50

local function GetTarget()
    local EnemySpotted = false
    for _,v in pairs(game:GetService("Workspace"):GetDescendants()) do
        if v:IsA("Model") and v:FindFirstChildOfClass("Humanoid") and not v ~= Character and EnemySpotted == false then
            local Humanoid2 = v:FindFirstChildOfClass("Humanoid")
            local HumanoidRootPart = Humanoid2.RootPart or Humanoid2.Parent:FindFirstChild("HumanoidRootPart")
            return HumanoidRootPart
        end
    end
end

coroutine.resume(coroutine.create(function()
    while true do
        wait(.1)
        pcall(function() Humanoid:MoveTo(GetTarget().Position) end)
    end
end))
Ad
Log in to vote
-1
Answered by 3 years ago

you need to stop being stinkey stonkerson and it will work :thumbs up!:

Answer this question