Hello!!
I’m working on a system where an NPC goes to your table and then orders food. I am using “MoveTo()” to move the NPC to a chair that is free and there are no other NPCs sitting in it. The problem is that sometimes NPCs collide with other objects such as tables or chairs and do not reach their destination.
I have thought about using the Pathfinding service but I don’t know how to implement it.
Could someone explain to me how it works and how can I implement the route lookup service in my script? Thank you so much!
Here is my script so you can also advise me if there is another more efficient way to achieve what I want.
--// Services
local ServerStorage = game:GetService("ServerStorage")
local PathfindingService = game:GetService("PathfindingService")
--// Variables
local NPCs_Folder = ServerStorage:WaitForChild("NPCs")
local NPCs = NPCs_Folder:GetChildren()
--// Configuration
local MaxNpcInRestaurant = 4
local NPCs_Module = {}
-- // Functions
function DetectAvailableSeat()
local availableSeat
for _, seat in pairs(workspace:WaitForChild("Restaurant_Chairs"):GetChildren()) do
if seat.Name == "Chair" and seat:GetAttribute("Taken") == false then
seat:SetAttribute("Taken", true)
availableSeat = seat
break
end
end
return availableSeat
end
function DetectUnseatedNPC()
for _, character in pairs(workspace.Clients:GetChildren()) do
if character.Name == "NPC" and (not character:GetAttribute("IsPlayerOnChair") or character:GetAttribute("IsPlayerOnChair") == false) then
return character
end
end
return nil
end
function SeatNPC(character, seat)
local seatCFrame = seat.CFrame
character:SetAttribute("IsPlayerOnChair", true)
character.Humanoid:MoveTo(seat.Position)
seat:SetAttribute("Taken", true)
end
function SpawnNPC()
local availableSeat = DetectAvailableSeat()
if availableSeat then
local randomNPC = NPCs[math.random(1, #NPCs)]
local clonedNPC = randomNPC:Clone()
clonedNPC.Parent = workspace.Clients
clonedNPC.HumanoidRootPart.CFrame = CFrame.new(workspace.Clients.SpawnNPC.Position)
clonedNPC:SetAttribute("IsPlayerOnChair", false)
SeatNPC(clonedNPC, availableSeat)
else
print("No seat available for npc")
end
end
function NPCs_Module.Start()
for i = 1, MaxNpcInRestaurant do
SpawnNPC()
task.wait(3)
end
end
return NPCs_Module