Hi. I am using PathFindingService, and I want to control NPC by clicking.
When I first click, it works normally, but when I click the second, it will first go to the second path waypoints and go back to the first path waypoints, and go to the second path waypoints again, etc.
--script on starterplayerscript
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local RS = game.ReplicatedStorage
local event = RS.pos
mouse.Button1Up:Connect(function()
event:InvokeServer(mouse.Hit.Position)
end)
-- Script that put on the NPC
local pathfinding = game:GetService("PathfindingService")
local human = script.Parent:WaitForChild("Humanoid")
local torso = script.Parent:WaitForChild("Torso")
local RS = game.ReplicatedStorage
local event = RS.pos
local position = Vector3.new(0,0,0)
local path = pathfinding:CreatePath()
local pos = Vector3.new(0,0,0)
local waypointss = {}
event.OnServerInvoke = function(player, pos)
waypointss = {}
if game.Workspace:FindFirstChild("pathmodel") then
game.Workspace:FindFirstChild("pathmodel"):Destroy() end
local pathmodel = Instance.new("Model", game.Workspace)
pathmodel.Name = "pathmodel"
path:ComputeAsync(torso.Position, torso.Position)
human:MoveTo(torso.Position)
path:ComputeAsync(torso.Position, pos)
waypointss = path:GetWaypoints()
for i, waypoint in pairs (waypointss) do
local point = Instance.new("Part")
point.Shape = "Ball"
point.Parent = pathmodel
point.Position = waypoint.Position - Vector3.new(0, 0.3, 0)
point.Material = "Neon"
point.Size = Vector3.new(1,1,1)
point.Anchored = true
point.CanCollide = false
point.Transparency = 0.3
end
for i, waypoint in pairs (waypointss) do
human:MoveTo(waypoint.Position)
human.MoveToFinished:Wait(2)
end
script.Parent:WaitForChild("Humanoid"):MoveTo(pos)
end
I had cleared the table of 1st path waypoints before it ran the second path, but it still runs.
How to cancel the old path??