Im working on a pathfinding system that allows you to move a dummy from point to point with PathfindingService. Problem is, when I click for the dummy to move somewhere else while its still moving to its previous determined end position. He kinda gets confused and does a little dance.
Code:
local pathFinding = game:GetService("PathfindingService")
local activeID
script.Parent.selected.OnServerEvent:Connect(function()
script.Parent.Highlight.Enabled = true
end)
script.Parent.moveCharacter.OnServerEvent:Connect(function(p, torso, endPos)
activeID = newproxy()
local path = pathFinding:CreatePath()
path:ComputeAsync(torso, endPos)
local pathWaypoints = path:GetWaypoints()
for i, waypoint in pairs(pathWaypoints) do
script.Parent.Humanoid:MoveTo(waypoint.Position)
script.Parent.Humanoid.MoveToFinished:wait(2)
end
end)
They act “funny” because when you click again before the first walk is over, you don’t break the loop. Meaning the new and the old loop run at the same time, one wants the character to move to the first position, and the other wants it to move to the second position, and thus the character wobbles between the two positions.
I would create a new variable, let’s name it clickNum, and increase it by 1 every time you click, then check in the loop if the clickNum is the same as when it started
local clickNum = 0;
script.Parent.moveCharacter.OnServerEvent:Connect(function(p, torso, endPos)
activeID = newproxy()
local path = pathFinding:CreatePath()
path:ComputeAsync(torso, endPos)
local pathWaypoints = path:GetWaypoints()
clickNum += 1
local currentNum = clickNum -- to save the clickNum at which the loop started
for i, waypoint in pairs(pathWaypoints) do
if currentNum == clickNum then
script.Parent.Humanoid:MoveTo(waypoint.Position)
script.Parent.Humanoid.MoveToFinished:wait(2)
else
break
end
end
end)