How to continue MoveTo() until it's finished?

So I have an R6 NPC that has to swim and I notice, it doesn’t even complete 1/4th of MoveTo(). The NPC moves for only like 5-6 seconds. It travels a tiny distance and stops nowhere near its destination.

local npc = script.Parent
local player = game.Players.LocalPlayer

npc.Humanoid.WalkSpeed = 10

local button = game.Workspace.Button.ClickDetector
local destination= game.Workspace.Destination

local function moveto()
	npc.Humanoid:MoveTo(destination.Position) 
	end

button.MouseClick:Connect(function(player)
	if player and player.Character  then
		moveto()
	end
end
)

So, the question is, how do I continue MoveTo so that it continues until the destination is reached?

Try rewriting your script to work with :Move(), it moves in a direction instead forever, so you can stop the movement when you desire.

Taking a look at the MoveTo documentation you can see a list of all conditions that ends a MoveTo:

Out of the presented options, the one that sounds the most likely is the second from the top.

The character gets stuck and the eight-second timer expires.

The documentation elaborates that the Humanoid will stop moving regardless of whether it reached its destination if this eight-second timer ends

We can implement the proposed solution here pretty easily by adding onto the moveto you have provided:

local function moveto()
    npc.Humanoid:MoveTo(destination.Position) 

    local Finished = false -- Whether or not the humanoid has reached its destination
    npc.Humanoid.MoveToFinished:Connect(function()
        Finished = true -- The humanoid reached its destination!
    end)

    task.delay(8,function() -- After 8 seconds check if the humanoid reached the destination
        if Finished then return end -- If they did, do nothing
        moveto() -- Otherwise we call the function again to keep moving
    end)
end

With this, the moveto function will recursively call itself until it reaches its destination.

I hope this helps!

2 Likes

Thanks for the detailed information, it was quite useful, it’s a triple A quality response, I appreciate it.

Implementing your code worked. I felt the need to decrease the 8 second timer though, because I found that doing so reflects a more effective/natural result (especially in water which is what I was working with). Decreasing it to 1, 2 or 3 can make a significant difference for any developers that are interested in using Stef’s code.

Once again, thanks for the info and your assistance. Absolutely loved your topic reply.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.