i’m trying to make a guard npc that patrols and if he sees you (via eyesight), he’ll veer off path to chase you
the problem is that he isn’t using his eyeballs while he patrols and instead ignores me and continues his patrol
here’s my code:
local function checking()
while task.wait(1) do
if checkSight(Guard) then
PatrolPath:Stop()
ChasePath:Run(objectLastDetected)
else
ChasePath:Stop()
for _, Waypoint in workspace.Waypoints:GetChildren() do
PatrolPath:Run(Waypoint)
PatrolPath.Reached:Wait()
end
end
end
end
coroutine.wrap(checking)()
i think the issue is that it iterates through all the waypoints before restarting the loop which means it would only detect me if i was standing in front of the guard as the loop restarts. i also think in this situation you would wanna use coroutines but i’m not certain where or how i’d set it up
I do believe that the problem is caused because of the loop, which is yielding the entire update thread.
You could make a separate thread for the waypoint loop so that it doesn’t intervene with the rest of the function.
I’d recommend delving into the task library instead of the coroutines one, as they’re more straightforward and newer (imo).
local patrolThread = nil
local function update()
local sawSomething = checkSight(Guard)
if sawSomething then
PatrolPath:Stop()
if patrolThread then
task.cancel(patrolThread)
patrolThread = nil
end
ChasePath:Run(objectLastDetected)
else
ChasePath:Stop()
if not patrolThread then
patrolThread = task.spawn(function()
for _, Waypoint in workspace.Waypoints:GetChildren() do
PatrolPath:Run(Waypoint)
PatrolPath.Reached:Wait()
if not patrolThread then
break
end
end
end)
end
end
-- whatever else you wanna check for
end
task.spawn(function()
while task.wait(1) do
update()
end
end)
My code starts a new thread whenever the guard starts its patrol waypoint loop, and cancels it whenever it enters its chase state, without ever yielding the main thread, which should allow for the guard to still keep updating what it sees while also moving at the same time.
yeah, I also intended to do the same at first but the code was unreadable but it still did what I needed it to do so I ended up keeping it. could be a good idea asking chatgpt to make it more readable tho in case you need inspiration