PathFinding delay when second activate

  1. On the second activation of the pathfinding, it should follow me with no delay.

  2. What is the issue? When I activate the ‘spawntroops’ event for the first time, everything works perfectly; the troops follow me. However, after 60 seconds, they get destroyed. On the second activation of the ‘spawntroops’ event, the troops are delayed by about 1-3 seconds when I move. Here is a clip of that happening the first time I activate the ‘SpawnTrooper’ event:
    robloxapp-20240212-1045079.wmv (3.0 MB)

And here is on the second time i activate the spawnTroopers Event:
robloxapp-20240212-1046459.wmv (3.0 MB)

  1. I have tried to increase the refresh rate and debug the issue, but I couldn’t find anything. I’ve also rewritten the script, but it still doesn’t work.

Here’s the sequence of events: When I join the game, I make 15 kills, then press ‘b’ to spawn the troopers. Initially, everything works perfectly; everyone follows me. However, after 60 seconds, the troopers get destroyed.

Then, after I gain another 15 kills and activate the event again, the troopers spawn, but there’s a significant delay of about 1-3 seconds. I don’t want this delay; I want everything to proceed smoothly

Here is the code:

local Players = game:GetService("Players")
local PathfindingService = game:GetService("PathfindingService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Workspace = game:GetService("Workspace")

-- RemoteEvents
local SpawnTropper =  ReplicatedStorage:WaitForChild("Remotes"):WaitForChild("Guis"):WaitForChild("JoinGui"):WaitForChild("Streaks"):WaitForChild("StreaksEvents"):WaitForChild("SpawnTroppers")

-- Rates for troppers
local refreshRate = 0.2
local predictionTime = 1
local followingDistance = 7
local followingTroops = {}
local formationOffsets = {
	Front = Vector3.new(0, 0, followingDistance),
	Right = Vector3.new(followingDistance, 0, 0),
	Left = Vector3.new(-followingDistance, 0, 0)
}


local function followPath(tropper, path)
	local humanoid = tropper:FindFirstChild("Humanoid")
	if not humanoid then
		warn("Humanoid not found in", tropper.Name)
		return
	end

	local waypoints = path:GetWaypoints()
	for _, waypoint in ipairs(waypoints) do
		humanoid:MoveTo(waypoint.Position)
		print("Humanoid is moving to the way point")
		local reached = humanoid.MoveToFinished:Wait()
		print(reached)
		if not reached then break end
	end
end



local function startFollowing(player, tropper, offset)
	local troopId = tropper:GetAttribute("TroopId") 
	if not troopId then
		troopId = "Troop" .. math.random()
		tropper:SetAttribute("TroopId", troopId)
		print(troopId .. "This is the tropp id from".. tropper.Name)
	end
	
	followingTroops[troopId] = true
	print(followingTroops)
	print(followingTroops[troopId])
	
	while followingTroops[troopId] and tropper.Parent do
		local playerCharacter = player.Character
		print("While Loop is starting")
		
		if not tropper or not tropper.Parent or not tropper:FindFirstChild("Humanoid") then
			print("While loop broke")
			break 
		elseif not playerCharacter or not playerCharacter.PrimaryPart then
			task.wait(1)
			print("While loop is continuing")
			continue
		end
		
		
		local futurePosition = playerCharacter.PrimaryPart.Position + (playerCharacter.PrimaryPart.Velocity * predictionTime)
		local targetPosition = futurePosition + offset

		local path = PathfindingService:CreatePath({
			AgentCanJump = true,
			AgentRadius = 2,
			AgentHeight = 5,
			AgentCanUseClimbing = true,
			AgentCanUseWalking = true
		})
		

		path:ComputeAsync(tropper.PrimaryPart.Position, targetPosition)
		
		print("Creating Path")

		if path.Status == Enum.PathStatus.Success then
			followPath(tropper, path)
			print(path.Status)
		end
		
		task.wait(refreshRate)
		print("Refreshing the path")
	end
end


local function stopFollowing(troopId)
	if followingTroops[troopId] then
		followingTroops[troopId] = false
	end
end


local function initializeFollowing(player, frontTropper, rightTropper, leftTropper)
	task.spawn(startFollowing, player, frontTropper, formationOffsets.Front)
	task.spawn(startFollowing, player, rightTropper, formationOffsets.Right)
	task.spawn(startFollowing, player, leftTropper, formationOffsets.Left)
end


SpawnTropper.OnServerEvent:Connect(function(player)
	print("Activating spawntroopers")
	local playerCharacter = player.Character
	local characterPrimaryPart = playerCharacter and playerCharacter:FindFirstChild("HumanoidRootPart")
	if not characterPrimaryPart then
		return 
	end
	
	if Workspace.Troppers:FindFirstChild(player.UserId) then
		for _, troop in ipairs(Workspace.Troppers[player.UserId]:GetChildren()) do
			local troopId = troop:GetAttribute("TroopId")
			if troopId then
				stopFollowing(troopId)
				followingTroops[troopId] = nil 
			end
			troop:Destroy() 
		end
	end

	
	
	local cloneFrontTropper = ReplicatedStorage:WaitForChild("SpawnableObj"):WaitForChild("Troppers"):WaitForChild("NormalMaps"):WaitForChild("TropperFront"):Clone()
	local cloneRightTropper = ReplicatedStorage:WaitForChild("SpawnableObj"):WaitForChild("Troppers"):WaitForChild("NormalMaps"):WaitForChild("TropperRigth"):Clone()
	local cloneLeftTropper = ReplicatedStorage:WaitForChild("SpawnableObj"):WaitForChild("Troppers"):WaitForChild("NormalMaps"):WaitForChild("TropperLeft"):Clone()
	
	-- // Refreshing the adtributes
	cloneFrontTropper:SetAttribute("TroopId", "Troop" .. math.random()) 
	cloneLeftTropper:SetAttribute("TroopId", "Troop" .. math.random())
	cloneRightTropper:SetAttribute("TroopId", "Troop" .. math.random())
	
	followingTroops[cloneFrontTropper:GetAttribute("TroopId")] = true 
	followingTroops[cloneLeftTropper:GetAttribute("TroopId")] = true 
	followingTroops[cloneRightTropper:GetAttribute("TroopId")] = true 
	
	-- Set the position of the troops relative to the player
	local playerPosition = characterPrimaryPart.Position
	cloneFrontTropper:SetPrimaryPartCFrame(CFrame.new(playerPosition + formationOffsets.Front))
	cloneRightTropper:SetPrimaryPartCFrame(CFrame.new(playerPosition + formationOffsets.Right))
	cloneLeftTropper:SetPrimaryPartCFrame(CFrame.new(playerPosition + formationOffsets.Left))
	print("Troops spawned next to you")

	-- Parent the clones to the workspace under a folder for the player's UserId
	local playerFolder = Workspace:FindFirstChild("Troppers") and Workspace.Troppers:FindFirstChild(player.UserId) or Instance.new("Folder", Workspace.Troppers)
	playerFolder.Name = player.UserId
	cloneFrontTropper.Parent = playerFolder
	cloneRightTropper.Parent = playerFolder
	cloneLeftTropper.Parent = playerFolder

	-- Set cloned Troppers' Humanoid WalkSpeed
	cloneFrontTropper.Humanoid.WalkSpeed = 25
	cloneRightTropper.Humanoid.WalkSpeed = 25
	cloneLeftTropper.Humanoid.WalkSpeed = 25
	print("Walkspeed changed to 25")

	-- Initialize following
	local frontFollow, rightFollow, leftFollow 
	frontFollow = task.spawn(startFollowing, player, cloneFrontTropper, formationOffsets.Front)
	rightFollow = task.spawn(startFollowing, player, cloneRightTropper, formationOffsets.Right)
	leftFollow = task.spawn(startFollowing, player, cloneLeftTropper, formationOffsets.Left)
	print("Following path")
	-- Destroy the troops after 60 seconds
	task.wait(60)

	stopFollowing(cloneFrontTropper:GetAttribute("TroopId"))
	stopFollowing(cloneRightTropper:GetAttribute("TroopId"))
	stopFollowing(cloneLeftTropper:GetAttribute("TroopId"))
	
	print("Stopfollowing")
	
	
	if cloneFrontTropper then cloneFrontTropper:Destroy() end
	if cloneRightTropper then cloneRightTropper:Destroy() end
	if cloneLeftTropper then cloneLeftTropper:Destroy() end
	
	print("Troopers destroyed")
end)

I really dont know why this is happening i have tryed many things.

1 Like