How can i make a npc pathfind stop when see the player?

im make a walking npc that goes to the player with pathfind but i have this problem

my code here:

local function chasePlayer()
	local player, distancia = findTarget()
	if player then
		local origin = npc.HumanoidRootPart.Position
		local direction = (player.HumanoidRootPart.Position - npc.HumanoidRootPart.Position).unit * 60
		local ray = Ray.new(origin, direction)

		local hit, pos = workspace:FindPartOnRay(ray, npc)
		if hit then
			if hit:IsDescendantOf(player) then
				collision = false
			else
				collision = true
			end
			
			local pathParams = {
				["AgentHeight"] = 5,
				["AgentRadius"] = 1.5,
				["AgentCanJump"] = false
			}
			local path = pathfindingservice:CreatePath(pathParams)
			path:ComputeAsync(npc.HumanoidRootPart.Position, player.PrimaryPart.Position)
			if path.Status == Enum.PathStatus.Success then
				for index, waypoint in pairs(path:GetWaypoints()) do
					if collision == false then
						humanoid:MoveTo(player.PrimaryPart.Position)
						break
					else
						humanoid:MoveTo(waypoint.Position)
						humanoid.MoveToFinished:Wait()
					end
				end
			end
			
		end
	end
end

but i want to make it so that when the npc looks at the player the pathfind will stop and not follow its pattern and move towards the player

1 Like

I think here you’re evaluating whether or not there’s an obstacle in the way before the path is computed, so the whole path will be walked on before it does the raycast again. It might not be the most performant, but doing the raycast on each waypoint would be the way you need to do this, and then break out of the current for loop going over the waypoints if there are no obstacles anymore

1 Like