So I’m trying to make a Push the Payload type game mode like in Overwatch or Team Fortress 2. The payload is an NPC so I was using Pathfinding service to move the NPC toward the objective when a player is near. However, the problem is when there are no more players near the payload it should stop moving but you cant just stop a pathfinding and start it again. The best i could think of was anchoring the NPC when players are no longer near but I don’t think that’s optimal. Does anybody have any better ideas?
if #game.Players.GetPlayers() > 0 then
-- move forward
else
-- do nothing
end
Ik how to do that but how would i make it do nothing. How would i cancel the pathfinding once there are no players activating it
In your pathfinding script, I assume you have a function that calls humanoid:MoveTo(waypoint)
. You can use @Mystxry12’s if
statement to determine whether to call that function or not.
game.Players.GetPlayers()
Need a colon and I don’t think this will apply because this would just be returning the number of players in the server, the thread’s poster wants his NPC to move whenever a player is close-by but when a player isn’t close-by then the NPC should be stationary.
local npc = script.Parent --example reference to npc
local function checkForClosePlayer()
local distances = {}
local closest = math.huge
for _, player in ipairs(game.Players:GetPlayers()) do
local distance = player:DistanceFromCharacter(npc.HumanoidRootPart.Position)
if distance then
distances[distance] = player.Name
end
end
for distance, plrName in pairs(distances) do
if distance < closest then
closest = distance
end
end
if closest <= 50 then --closest player when function called within 50 studs of npc
print(distances[closest].." is moving the payload!")
--move the npc
elseif closest > 50 then
print("The payload has stopped moving!")
--do not move npc
end
end
Here’s an example of what you could do, loop through every player currently in the server and fetch their distance in studs from the NPC, if the closest distance is within a given range then move the NPC otherwise stop the NPC.
You can anchor the HRP of the NPC or assign the “WalkSpeed” property of its Humanoid instance a value of 0 to prevent it from moving.
And as was previously suggested you could manage calls to the pathfinding function from within this provided function, so only call the pathfinding function when the NPC should move and stop calling it when the NPC should be stationary.