Assume I want to move my NPC to some part, but that part’s position is constantly changing. With the MoveTo() function, the humanoid will move to the part’s position when I call the function, and if the part’s position changes while it’s moving, it will go to the wrong spot.
I’ve tried putting MoveTo into a while loop and this behavior still occurs. Any way I can make my NPC constantly follow the part?
local function moveTo(humanoid, targetPoint, andThen)
local targetReached = false
-- listen for the humanoid reaching its target
local connection
connection = humanoid.MoveToFinished:Connect(function(reached)
targetReached = true
connection:Disconnect()
connection = nil
if andThen then
andThen()
end
end)
-- start walking
humanoid:MoveTo(targetPoint)
-- execute on a new thread so as to not yield function
spawn(function()
while not targetReached do
-- does the humanoid still exist?
if not (humanoid and humanoid.Parent) then
break
end
-- has the target changed?
if humanoid.WalkToPoint ~= targetPoint then
break
end
-- refresh the timeout
humanoid:MoveTo(targetPoint)
wait(6)
end
-- disconnect the connection if it is still connected
if connection then
connection:Disconnect()
connection = nil
end
end)
end
you could copy this code and use it yourself as it’s already made but you should read over it so you learn something
MoveTo() has an optional second argument for your exact use case. Pass the part you are moving towards as the second argument and the humanoid will move toward the part as it moves. This works by offsetting the target by any movement of the part since the function was called.
:MoveTo(game.Workspace.Target.Position, game.Workspace.Target) you should get your desired behavior.