Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

A better method to path find to a moving player?

So I was attempting to create a path finding script for my NPC using ROBLOX's path finding service. The script is supposed to follow the player and not get stuck on walls and make sure it can follow them where ever they go.

The current script does function, its just after the player a NPC is following dies the NPC begins to track the next player but then will start going between the spot the first player died and the path in which the new player is on.

My current script

local pathService = game:GetService("PathfindingService")
local teams = game:GetService("Teams")
local debris =game:GetService("Debris")

local maxDistance = 512

local undeadTeam = teams:FindFirstChild("Undead")
local survivorsTeam = teams:FindFirstChild("Survivors")

local upper = script.Parent.UpperTorso
local target

local humanoid = script.Parent.Humanoid


function pathFind()
	local OldSpot = target.Character.UpperTorso.Position
	local newSpot
	local path = pathService:CreatePath()
	path:ComputeAsync(upper.Position,OldSpot)
	local waypoints = path:GetWaypoints()
	
	for _, waypoint in pairs(waypoints) do
		newSpot = target.Character.UpperTorso.Position
		local part = Instance.new("Part")
		part.Size = Vector3.new(0.6, 0.6, 0.6)
		part.Position = waypoint.Position
		part.Anchored = true
		part.CanCollide = false
		part.Parent = game.Workspace
		part.Transparency = 1
		debris:AddItem(part,0.75)
		humanoid:MoveTo(waypoint.Position)
		humanoid.MoveToFinished:Wait()
		if (newSpot-OldSpot).magnitude>5 then--if satment that checks if the target has moved
			break
		end
	end
end

while wait()do
	for i,v in pairs(game:GetService("Players"):GetChildren())do
		local shortestDistance = 512--players have to be closer than 512 studs by default
		if v.Team == survivorsTeam and workspace:FindFirstChild(v.Name)then
			local chr = v.Character
			if chr then
				if chr:FindFirstChild("Humanoid").Health >0 then
					if (chr:FindFirstChild("UpperTorso").Position-upper.Position).magnitude < shortestDistance then--checks if the target is the closest 
						shortestDistance = (chr:FindFirstChild("UpperTorso").Position-upper.Position).magnitude
						target = v
					end
				end
			end
		end
	end
	if target then
		repeat 
			wait()
			pathFind()
		until 
			target.Team == undeadTeam
	end	
end

if you have any questions ask away I will try and reply to them as soon as possible.

1 answer

You can use humanoid.Running Very well with this

CHARACTERPARENTHERE.Humanoid.Running:Connect(function()
	--This will detect if someone is using wasd at all.
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.