My rig switches between two states:
- Patrol - patrol area
- Chase - chase people when near
when the rig patrols it moves from part 1 to part 4 so it starts moving to part 1 and when it finishes it goes to part 2 and when it reach part 4 it will start from the beginning and so it loops
when the rig chases that state only happens when a player that is near atleast as 30 studs away from the rig and once the player is in the 30 studs range the rig chases the player but in that chasing state the rig slightly oscillates left and right but its hard to describe in this situation right now so try reading the comments when i give you the script that does this
script:
local steps = workspace.Steps
local guard = script.Parent
local humanoid = guard.Humanoid
local runservice = game:GetService("RunService")
-- find nearest player from array of players
local function findNearestPlayerFromArray(rig:Model, array:{[number]:Player})
local target -- delcare variable target for refrerence of the nearest character
local range = 30 -- maximum range to detect nearest player
--[[
loop through all players in given array and get character safely
then get the distance between the player and rig and check if
the distance is below maximum range, if so then set range to
distance and set target to the player character
]]
for _,player in array do
local character = player.Character or player.CharacterAdded:Wait()
local distance = (rig.HumanoidRootPart.Position-character.HumanoidRootPart.Position).Magnitude
if distance < range then
range = distance
target = character
end
end
return target
end
-- guard patrol state logic
local function loop()
for _,step in steps:GetChildren() do
humanoid:MoveTo(step.Position)
humanoid.MoveToFinished:Wait()
end
loop()
end
local thread = task.spawn(loop) -- calls function and returns thread
-- chase state logic
runservice.PostSimulation:Connect(function()
local nearest = findNearestPlayerFromArray(guard, game.Players:GetPlayers()) -- get nearest player character
if nearest then -- check if nearest player isnt nil
if coroutine.status(thread) ~= "dead" then -- check if thread is dead
task.cancel(thread) -- cancel thread when dead
end
humanoid:MoveTo(nearest.HumanoidRootPart.Position) -- chase nearest player
end
end)
video:
sometimes the rig dont oscillate after a while but starts lagging sometimes after that
i have tried to look for similar topics and solutions for this in roblox documentation but couldnt really find one