So, I made an NPC that follows you if you're touching a part. But when it stops getting touched, it waits about 30 seconds to stop following you. Here's the script:

part = game.Workspace.AttackPart
touched = false

part.Touched:Connect(function(hitPart)
	if hitPart.Parent:FindFirstChildOfClass("Humanoid") then
		touched = true
	end
end)
part.TouchEnded:Connect(function(hitPart)
	if hitPart.Parent:FindFirstChildOfClass("Humanoid") then
		touched = false
	end
end)

local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = 100
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x]
		if (temp2.className == "Model") and (temp2 ~= script.Parent) and touched == true then
			temp = temp2:findFirstChild("HumanoidRootPart")
			human = temp2:findFirstChild("Humanoid")
			local nothuman = temp2:findFirstChild("NotHuman")
			if (temp ~= nil) and (human ~= nil) and (human.Health > 0) and (nothuman == nil) and touched == true then
				if (temp.Position - pos).magnitude < dist then
					torso = temp
					dist = (temp.Position - pos).magnitude
				end
			end
		end
	end
	return torso
end

while true do
	wait()
	local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
	if target ~= nil and touched == true then
		script.Parent.Humanoid:MoveTo(target.Position, target)
	end
end

5 comments

0

I see you're new on this platform. This webpage works the same as any other forum, using upvotes (and answer acceptance) to reward the efforts of the Programmers who aided you. You left an answer unaccepted from your previous question, please do not do that again.

0

The 'findNearestTorso' function is also poorly written, and obviously deprecated; borrowed from an outdated source.

0

Though 'MoveTo' is asynchronous, it will remain adjusting the called-upon Humanoid's Position to match the specified Vector3 until it is reached. The debounce is affective, but it won't halt the process—notice how the NPC stops when it reaches where you used to be.

0

What you could do to solve the problem, is making another method call telling the Humanoid to move to itself. This would effectively stop it in its tracks.

0

thanks, I'll try that out