Hello, I am trying to get an NPC to move to my mouse location using pathfinding, but I need to be able to adjust his ending location.
I am trying to break a loop if the mouse is clicked a second time.
It registers the loop breaking (via the print()), but the loop keeps playing.
I have tried multiple misc things, but the loop keeps playing.
if isMoving then
secondClick = true
end
local path = pathService:CreatePath(pathParams)
path:ComputeAsync(soldier.Position, pos)
local waypoints = path:GetWaypoints()
workspace.PathFindingObjects:ClearAllChildren()
for _, waypoint in pairs(waypoints) do
local part = Instance.new("Part")
part.Shape = "Ball"
part.Material = "Neon"
part.Size = Vector3.new(0.6, 0.6, 0.6)
part.Position = waypoint.Position
part.Anchored = true
part.CanCollide = false
part.Parent = workspace.PathFindingObjects
end
isMoving = true
for _, waypoint in pairs(waypoints) do
soldier.Parent.Humanoid:MoveTo(waypoint.Position)
soldier.Parent.Humanoid.MoveToFinished:Wait()
if secondClick then
print("loop broken")
secondClick = false
break
end
end
print("path ended")
isMoving = false
I would probably alter the approach. Instead of giving an NPC a command and then telling the NPC to do the command. Have the action and the command separately. Let me explain.
When user clicks set the destination of the NPC to the click.
Then separately keep checking.
If the NPC is not at the destination then finish(return)
Otherwise, create a path from the Current Position to the destination.-- You can see this is separate from the command
Yes the looping handles that. That is exactly why I would separate the movement from the commands. Otherwise the NPC will be forced to follow the command until the end.
I am not really good at explaining. Please try to read the post carefully.
It worked! The movement is a bit choppy, but I can fix that easily.
RE.OnServerEvent:Connect(function(plr, pos)
destination = pos
atDestination = false
end)
while true do
if not atDestination then
print("Moving to destination")
local path = pathService:CreatePath(pathParams)
path:ComputeAsync(soldier.Position, destination)
local waypoints = path:GetWaypoints()
soldier.Parent.Humanoid:MoveTo(waypoints[2].Position)
soldier.Parent.Humanoid.MoveToFinished:Wait()
if waypoints[2].Position == destination then
atDestination = true
end
end
wait()
end