Recently I’ve been trying to create a Bear which chases the player once they get close enough. My only problem with this is shown in the video below, the bear pathfinds and then walks to the player’s old position if they move
Here’s my code for the bear, also it’s best that the bear pathfinds instead of just spamming :MoveTo() to the Player’s HumanoidRootPart
local function move()
--some variables
--// Calculate Path and Move towards Player
local newPath = PathfindingService:CreatePath({
Costs = {
Water = math.huge, -- Avoid Water
}
})
newPath:ComputeAsync(mob_torso.Position, characterPosition)
local waypoints = newPath:GetWaypoints()
if not waypoints then
warn("Waypoints in mob is nil, Mob:", mob_model)
return
end
local WalkAnimTrack = self.WalkTrack
WalkAnimTrack:Play()
for _, waypoint: PathWaypoint in waypoints do
mob_humanoid:MoveTo(waypoint.Position)
mob_humanoid.MoveToFinished:Wait()
end
WalkAnimTrack:Stop()
end
I’m pretty sure this question has been answered multiple times in previous posts.
Try searching the forums. I used the search phrase “npc doesn’t move to current player position” and got a few promising posts. You could also try phrases like “NPC only moves to previous player position”, or “NPC won’t follow player”.
From those posts I seem to remember that you should check to see if the player has moved more than about .5 studs, and if they do then recalculate the MoveTo, not just Wait until each waypoint has been reached.
There are different methodologies for doing this. The one I prefer is by checking if the player is in direct view of the NPC and then simply moving the NPC to the player’s position (within a loop) using Humanoid:MoveTo. This way, as long as the player is in direct line of sight of the bear, the bear will move to the players position directly, if the bear isn’t, then it uses pathfinding service.
A common method is to check if the NPC directly sees the target (raycasting) and then directly loop :MoveTo() without pathfinding so it moves smooth.
-- assuming this is running in a while loop
if canSee then
-- moveto target
task.wait()
else
-- calculate waypoints via pathfinding + moveto waypoint
end
You should also look into recursive pathfinding where instead of calculating waypoints and going through all of them which:
fails to account for the target changing positions
fails to adapt to dynamic maps with moving parts
prone to getting stuck on corners, edges, etc.
You calculate waypoints, move to the first few waypoints, then use break and restart the loop (rather than completing the entire table of waypoints.)
From my personal experience, restarting the loop after the first 3-5 waypoints (assuming default waypoint spacing) made it feel responsive enough.
Are you worrying about performance? You can ratelimit the amount of raycasts you perform to check that the player is in line of sight (assuming you’re considering my method of raycast + move to target)