The NPC can still find the player

Hi, I have a issue, but i don’t know why. I made a function that gets the player in a certain distance, but for some reason when i’m far away the NPC still can find the player.

Code:

local RunService = game:GetService("RunService")

local npc = script.Parent

local range = 10

local target = nil
local newTarget = nil

local function findTargets()
	newTarget = nil
	-- Get the players
	for _, player in game.Players:GetPlayers() do
		local character = player.Character
		if character then
			-- Distance between the target and the npc
			local distance = (character.HumanoidRootPart.Position - npc.HumanoidRootPart.Position).magnitude
			if distance < range then
				newTarget = character
			else
				newTarget = nil
			end
		end
	end
	target = newTarget
end

RunService.Heartbeat:Connect(function()
	if target then
		print(target)
	else
		findTargets()
	end
end)

maybe try setting the range to -10?

1 Like

I made it that the NPC only can find you in a certain range

Code:

if distance < range then
				newTarget = character
			else
				newTarget = nil
			end

Oh wait, try swapping around the <

What the issue is here is something like a debounce that never gets reset.

Your heartbeat event checks if target is a character or nil however, you do not check again if target should be nil. So once it has found a character it is never checked if this character is out of range because target is always a character. It can be simply fixed by checking if the character still exists and if it gets out of range them you set target to nil

1 Like

Ok, i’ll try that later when i’m back home.

1 Like

I made a function that is called “reachable”, when the player is not reachable it is false, but when the player is reachable it is true.

Code:

local function reachable(target)
	-- Looking if the target reachable or not
	local distance = (target.HumanoidRootPart.Position - npc.HumanoidRootPart.Position).magnitude
	if distance < range then
		return true
	else
		return false
	end
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.