Hey, I am using a script that I got from another post, and I have this choppy movement with the NPC I am trying to move, this has been asked here many times, but I still struggle to understand how to fix this.
This, while running at ~30 times per second of course, returns laggy movement, even if I bump it up to wait(.5) it still has unpredictable and randomized stutters in the movement.
For the ones who didn’t open the post, this is the code:
local NPC = script.Parent
local Humanoid = script.Parent:WaitForChild("Humanoid")
local HRP = script.Parent:WaitForChild("HumanoidRootPart")
local function GetClosestPlayer(range)
local List = {}
local Target = nil
for i, v in pairs(game.Players:GetPlayers()) do
local dist = v:DistanceFromCharacter(HRP.position)
if dist <= range then
table.insert(List, {dist, v})
end
end
table.sort(List, function(A, B)
return A[1] < B[1]
end)
pcall(function()
Target = List[1][2]
end)
return Target
end
while true do
wait()
local Target = GetClosestPlayer(400)
print(Target)
if Target ~= nil then
if Target.Character ~= nil then
Humanoid:MoveTo(Target.Character.PrimaryPart.Position)
Humanoid.MoveToFinished:Wait()
end
end
end
It’s “laggy” because of the MoveToFinished:Wait() call. Essentially what’s happening is you’re giving the humanoid a target position to move to, and then pausing the code while the humanoid walks to the position. While the humanoid is walking, the player is also moving, but the humanoid is continuing to walk to the original player position and doesn’t start walking to the player’s current position until after it has reached the old position.
In the GIF you posted with the MoveToFinished:Wait() removed, it doesn’t appear to be laggy and the humanoid is following the player much more closely, why do you say it is?
The gif is in about 20 fps, i’ll try to get a better shot.
What I mean is this: https://gyazo.com/d2987ce04b0110610bcee9756c633862.gif
You see the health bar is being choppy, that’s the movement, anyway to fix that as well?
let’s suppose this Red part is the target location, while using Humanoid.MoveDirection we can get a decent result so that the NPC is following ahead of the player
I think you misunderstand what connecting a wait() to an event (MoveToFinished) does. It doesn’t cancel the movement if the time inside the wait() has passed, it yields the thread until the event fires and the number inside the wait() is an additional time to wait after the event fires. So in this case, if you put a MoveToFinished:wait(7) then when the humanoid reaches it’s destination it’s going to stand still for 7 seconds before going back to following.
Nevermind, I assumed that the event:wait() followed the same functionality as a normal wait(), but it simply yields until the event fires (and doesn’t accept any parameters).