How to make a NPC Spot and Chase the Nearest Player

So I was recently creating a Pathfinding NPC and made a patrol system for it, but I also wanted to add a Player Spot and chase feature to the same script without using more scripts, so if anyone could help me with this, I’d appreciate it a lot.


Certainly, I can help you integrate both the patrol and chase features into the same script for your Pathfinding NPC. Here’s a basic outline of how you can achieve this:

luaCopy code

local npc = script.Parent -- Assuming the script is a child of the NPC
local player = game.Players.LocalPlayer -- You can replace this with the actual player you want to chase

local PathfindingService = game:GetService("PathfindingService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local TakeDamage = ReplicatedStorage:WaitForChild("TakeDamage") -- Replace this with your damage handling event

local patrolPoints = {, 0, 10),, 0, 10),, 0, -10),, 0, -10),

local currentPatrolIndex = 1
local chasingPlayer = false

function patrolToPoint(point)
	local path = PathfindingService:CreatePath({
		AgentRadius = 2,
		AgentHeight = 5,
		AgentCanJump = true,
		AgentJumpHeight = 10,
		AgentMaxSlope = 45,

	path:ComputeAsync(npc.Position, point)
	if path.Status == Enum.PathStatus.Complete then

function chasePlayer()
	chasingPlayer = true
	while chasingPlayer do
		local targetPosition = player.Character and player.Character:WaitForChild("HumanoidRootPart").Position
		if targetPosition then
		wait(1) -- Adjust the delay as needed

function onTouched(hit)
	local character = hit.Parent
	local humanoid = character:FindFirstChild("Humanoid")
	if humanoid and not chasingPlayer then


while true do
	if not chasingPlayer then
		currentPatrolIndex = currentPatrolIndex % #patrolPoints + 1
	wait(1) -- Adjust the delay for patrol

This script sets up a patrol system with a basic chase feature. When the NPC is touched by a player’s character, it will start chasing the player. Once the player is within range, the NPC will follow the player. When the player leaves, the NPC will return to patrolling.

Remember to replace "TakeDamage" with your actual damage handling event reference. Also, this script is a simplified example, so you may need to adjust it according to your game’s needs and logic.

1 Like

Thanks so much! This helped a lot! I recently looked up tutorials on ray casting and pathfinding so I can learn that stuff myself. I appreciate the help.


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