How to make a Player Spawn on a Spawn Point that is the farthest from a specific part?

I’m trying to make a horror game that has a AI that chases the player around while they try to find Books to escape.

There is going to be 3 Spawn Points, and each Spawn Point will contain a barrier preventing the AI from entering the Spawn.


I have no Idea on how to make the AI stop chasing the player whenever they enter the spawn point so Instead I want the Player to spawn on the farthest spawn from the AI…

Only problem is… I have no Idea on how to do that either!

Please help if you can. I literally followed a tutorial on the AI but I still know a little bit about how the code works…


Here’s the AI Code:

local PathfindingService = game:GetService("PathfindingService")

local npc = script.Parent
local humanoid = npc:WaitForChild("Humanoid")
local hrp = npc:WaitForChild("HumanoidRootPart")
hrp:SetNetworkOwner(nil)

local walkAnim = humanoid.Animator:LoadAnimation(script.Walk)
local attackAnim = humanoid.Animator:LoadAnimation(script.Attack)

local pathParams = {
	AgentHeight = 5,
	AgentRadius = 3,
	AgentCanJump = false,
}

local rayParams = RaycastParams.new()
rayParams.FilterType = Enum.RaycastFilterType.Blacklist
rayParams.FilterDescendantsInstances = {npc}

local lastPos
local animPlaying = false

local RANGE = 45
local DAMAGE = 100

local function canSeeTarget(target)
	local orgin = hrp.Position
	local direction = (target.HumanoidRootPart.Position - hrp.Position).Unit * RANGE
	local ray = workspace:Raycast(orgin, direction, rayParams)

	if ray and ray.Instance then
		if ray.Instance:IsDescendantOf(target) then
			return true
		else
			return false
		end
	else
		return false
	end
end

local function findTarget()
	local players = game.Players:GetPlayers()
	local maxDistance = RANGE
	local nearestTarget

	for i, player in pairs(players) do
		if player.Character then
			local target = player.Character
			local distance = (hrp.Position - target.HumanoidRootPart.Position).Magnitude

			if distance < maxDistance and canSeeTarget(target) then
				nearestTarget = target
				maxDistance = distance
			end
		end
	end

	return nearestTarget
end

local function getPath(destination)
	local path = PathfindingService:CreatePath(pathParams)

	path:ComputeAsync(hrp.Position, destination.Position)

	return path	
end

local function attack(target)
	local distance = (hrp.Position - target.HumanoidRootPart.Position).Magnitude
	local debounce = false

	if distance > 5 then
		humanoid:MoveTo(target.HumanoidRootPart.Position)
	else
		if debounce == false then
			debounce = true

			npc.Head.AttackSound:Play()
			attackAnim:Play()
			target.Humanoid.Health -= DAMAGE
			task.wait(0.5)
			debounce = false
		end
	end
end

local function walkTo(destination)
	local path = getPath(destination)

	if path.Status == Enum.PathStatus.Success then
		for i, waypoint in pairs(path:GetWaypoints()) do
			path.Blocked:Connect(function()
				path:Destroy()
			end)

			if animPlaying == false then
				walkAnim:Play()
				animPlaying = true
			end

			attackAnim:Stop()

			local target = findTarget()

			if target and target.Humanoid.Health > 0 then
				lastPos = target.HumanoidRootPart.Position
				attack(target)
				break
			else
				if waypoint.Action == Enum.PathWaypointAction.Jump then
					humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
				end

				if lastPos then
					humanoid:MoveTo(lastPos)
					humanoid.MoveToFinished:Wait()
					lastPos = nil
					break
				else
					humanoid:MoveTo(waypoint.Position)
					humanoid.MoveToFinished:Wait()
				end
			end
		end
	else
		return
	end
end

local function patrol()
	local waypoints = workspace.Waypoints:GetChildren()
	local randomNum = math.random(1, #waypoints)
	walkTo(waypoints[randomNum])
end

while task.wait(0.2) do
	patrol()
end

Put all of the parts in a folder so they can be easily accessed, then use a simple algorithm to find the one with the farthest distance from the player. You can teleport the character to this part right after they spawn.

local spawnParts = --put the folder with the spawn parts here


game.Players.PlayerAdded:Connect(function(plr) -- run for each player
  plr.CharacterAdded:Connect(function(char) --run every time a character spawns

    --wait for their root part to load
    local hmr = char:WaitForChild("HumanoidRootPart")

    --find the farthest part
    local best, bestdis
    for i,v in pairs(spawnParts:GetChildren()) do
      local dis = plr:DistanceFromCharacter(v.Position)
      if not best or dis > bestdis then 
        bestdis = dis
        best = v
       end
    end
     
    --teleport player
    char:MoveTo(best.Position)
  end)
end)
1 Like

As a sidenote, you can stop your AI from going into spawns by defining a region around your spawns with a high pathfinding cost and checking if the path to the player is blocked. You can find the Roblox documentation on how to do that here.

1 Like

Thank You so much!

You actually saved my day. I had no Idea it was this easy, and you genuinely enabled me to learn something new. Thank You!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.