Distance Problem

For some unknown reason, my distance function isn’t working. Basically, the thing I want to create is a knife attack for an NPC and in order to do that, I need to figure out how close the NPC is to the character, problem is it always prints “its worked” before the NPC reaches the character(and to give you some extra insight, yes the NPC has a follow script)

This is a section of the module:

function gangsterai.Weaponry(char)
	local gangster = workspace:WaitForChild(" ")
	local humanoidrootpart = gangster.HumanoidRootPart
	local characterhumanoidrootpart = char.HumanoidRootPart
	local debounce = false
	local distance = (characterhumanoidrootpart.Position.Magnitude - humanoidrootpart.Position.Magnitude)
	
	if distance <=5 or distance >=-5 then
		if debounce == false then
			debounce = true
			print("it worked!")
		end
	end
end

And yes, I have tried a different version and I believe the problem with this version is it doesn’t call the function again, I’ve tried using RenderStepped but me not knowing how to use it nearly crashed my game with it. This version’s behaviour simply just doesn’t print it at all. Anyways, here it is:

function gangsterai.Weaponry(char)
	local gangster = workspace:WaitForChild(" ")
	local humanoidrootpart = gangster.HumanoidRootPart
	local characterhumanoidrootpart = char.HumanoidRootPart
	local debounce = false
	
	
	if (gangster.Torso.Position - char.Torso.Position).Magnitude < 5 then
			print("it worked!")
	end
end

I may respond the next day as it is night right now.

Here is the script that calls the module(it works perfectly fine but just in case it is related to the problem)

  local module = require(script.Parent.GangsterAi)
game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		module.Follow(char)
			module.Weaponry(char)
	end)
end)

That’s because of

if distance <=5 or distance >=-5 then

even if the distance is 100 this condition will be true. Just do distance <=5 and use math.abs for the calculated distance:

local distance = math.abs((characterhumanoidrootpart.Position.Magnitude - humanoidrootpart.Position.Magnitude))

Turns out the problem was about the function running once, thanks for your help anyways

Yup that was the other problem, but math.abs is definitely needed for distance