Hey everyone!
Currently i’m trying for my NPCs to follow a moving target (a Player in this case) only using PathfindingService
, I have done this already, but i can’t seem to find a way that i would say is “convenient”.
See code below:
local function followPath(goal)
path:ComputeAsync(npcRootPart.Position, goal.Position)
Waypoints = {}
if path.Status == Enum.PathStatus.Success then
Waypoints = path:GetWaypoints()
for i = 1, #Waypoints do
local waypoint = Waypoints[i]
if waypoint.Action == Enum.PathWaypointAction.Walk then
npcHumanoid:MoveTo(waypoint.Position)
-- npcHumanoid.MoveToFinished:Wait()
else
npcHumanoid.Jump = true
end
end
else
warn("No path found.")
end
end
This works, however the NPC keeps bumping into obstacles and it’s also pretty clunky if i use MoveToFinished:Wait()
, things change when i remove that part from the code (as seen above), without it the NPC becomes pretty responsive and actually never gets stuck.
As far as i’m aware, the responsiveness happens because it’s re-computing the path way too often, it’s important to the question to mention this is running in a while loop each heartbeat, so my main question is… Is there a good method to compute the path less often, while also having great responsiveness?
This is an example of the while loop i’m talking about:
while somerandomthing do
local target = findClosestTarget()
if target then
followPath(target)
end
RunService.Heartbeat:Wait()
end
Just to clarify 1st, I’ve tried using a raycast to detect if the way is blocked and then enter pathfinding “mode”, however, i don’t like the innaccuracy of it. If the player is in an open area the NPC is pretty dumb.
Just to clarify 2ndly, I’m not asking to be spoon-fed, i’m just asking for someone to point me into the right direction, maybe using pseudo-code or just giving me an idea on how to do it, sorry if it sounds like i’m asking for someone to make me an script, i’m just saying this because english isn’t my first language, so i’m not sure if maybe this sounds too “direct” or something. Thanks in advance!