Enemy NPC Runs away From Player?

Hi, I’m having some difficulty with the enemy NPC in my game. Before it would chase the player just fine and follow the player around and damage it. Now it glitches and runs away from the player or glitches. Here’s how it looks like.
https://i.gyazo.com/35b3828957b0ad051eda17dc9d079564.mp4
https://i.gyazo.com/eff9bebc8c76b318351379bea71b129e.mp4

This is the NPC follow script,

local function findPlayer()
	for i,v in pairs(game.Players:GetPlayers()) do
		if not v.Character then return end
		if v.Character:FindFirstChildOfClass("Humanoid") then
			if v.Character:FindFirstChild("HumanoidRootPart") then
				local Hum = script.Parent:FindFirstChild("Humanoid")
				local vsRoot = v.Character:FindFirstChild("HumanoidRootPart")
				if Hum and vsRoot then
					if script.Parent:FindFirstChild("HumanoidRootPart") then
						local Root = script.Parent:FindFirstChild("HumanoidRootPart")
						if (Root.Position - vsRoot.Position).Magnitude <= 50 then
							Hum:MoveTo(vsRoot.Position)
							if script.Parent:FindFirstChild("Follow") then
								script.Parent:FindFirstChild("Follow").Value = true
							end
						else
							Hum:MoveTo(Oldpos)
							if script.Parent:FindFirstChild("Follow") then
								script.Parent:FindFirstChild("Follow").Value = false
							end
							return Hum,true
						end
					end
				end
			end
		end
	end
end


spawn(function()
	while true do
		wait()
		if script.Parent:FindFirstChild("Humanoid").Health > 0 then
			findPlayer()
		end
	end
end)

Any way to fix this? Any help is appreciated. Thanks.
1 Like

I would personally recommend that you fire the function, findPlayer() in this case, check to see if it returns the Humanoid / true, and then move the NPC.

Formatting your code would really help us to be able to better read your code. Please make sure to do so when posting code to the forums. Add three backticks before and after code to add it to a code block.

```lua
-- Hello!
```

That being said, before getting into the grit, I notice that your code severely lacks the use of variables where most appropriate to be used. Remember that if you intend to use something often, you should assign a variable to it.

Another thing is that your code doesn’t explicitly follow the closest player, only the first within 50 studs. If you take a look at legacy follow code you’ll notice a max distance is gradually decreased as a closer player is found in order to determine who’s closest or a list of player distances to the NPC are collected, sorted by closest and the first entry is returned.

Take a gander at your code and see if you’re able to poke out small issues like this and try finding which area is the problem, then try again. Is it the follow code or the return code?

1 Like

Is your NPC trying to follow itself?