Here is a sample script that demonstrates how to switch between patrol and pursuit states for a humanoid NPC in Roblox:
code
-- Constants
local PATROL_POINTS_FOLDER = script.Parent:WaitForChild("PatrolPoints")
local PURSUIT_RADIUS = 20
-- State variables
local currentState = "patrol"
local pursuitTarget = nil
-- Functions
-- Returns a random patrol point from the patrol points folder
local function GetRandomPatrolPoint()
local patrolPoints = PATROL_POINTS_FOLDER:GetChildren()
local patrolPoint = patrolPoints[math.random(#patrolPoints)]
return patrolPoint.Position
end
-- Updates the pursuit target based on the players within the pursuit radius
local function UpdatePursuitTarget()
local closestPlayer = nil
local closestDistance = math.huge
for _, player in pairs(game.Players:GetPlayers()) do
local distance = (player.Character.HumanoidRootPart.Position - script.Parent.HumanoidRootPart.Position).Magnitude
if distance < PURSUIT_RADIUS and distance < closestDistance then
closestPlayer = player
closestDistance = distance
end
end
pursuitTarget = closestPlayer
end
-- Main loop
while true do
if currentState == "patrol" then
-- Choose a random patrol point and move towards it
local targetPosition = GetRandomPatrolPoint()
script.Parent.Humanoid:MoveTo(targetPosition)
script.Parent.Humanoid.MoveToFinished:Wait()
-- Check if there is a player within pursuit radius
UpdatePursuitTarget()
if pursuitTarget then
currentState = "pursuit"
end
elseif currentState == "pursuit" then
-- Update the pursuit target in case it has changed
UpdatePursuitTarget()
if pursuitTarget then
-- Move towards the pursuit target
script.Parent.Humanoid:MoveTo(pursuitTarget.Character.HumanoidRootPart.Position)
script.Parent.Humanoid.MoveToFinished:Wait()
else
-- If there is no pursuit target, switch back to patrol state
currentState = "patrol"
end
end
end
This script first defines the constants PATROL_POINTS_FOLDER and PURSUIT_RADIUS, which represent the folder containing the patrol points and the radius within which the NPC will pursue players, respectively.
It also defines the state variables currentState and pursuitTarget. currentState is a string that indicates whether the NPC is currently patrolling or pursuing a target, and pursuitTarget is a reference to the player character that the NPC is currently pursuing.
The script then defines two functions: GetRandomPatrolPoint and UpdatePursuitTarget. GetRandomPatrolPoint returns a random patrol point from the patrol points folder, and UpdatePursuitTarget updates the pursuitTarget variable based on the players within the pursuit radius.
The script then enters a loop that repeatedly checks the current state and takes appropriate actions. If the NPC is patrolling, it chooses a random patrol point and moves towards it. If it reaches the patrol point, it checks for