How to make mob always follow closest Player?

I have a script that makes a mob follow the closest player. (PlayerToFollow is constantly updated)

while true do
	local pathfindingservice = game:GetService("PathfindingService")
	wait(0.5)
	local humanoid = script.Parent.Humanoid
	local torso = script.Parent.Torso.Position

	local path = pathfindingservice:CreatePath()

	local part = game.Players[script.Parent.PlayerToFollow.Value].Character.HumanoidRootPart.Position

	path:ComputeAsync(torso,part)
	local waypoints = path:GetWaypoints()
	for i, waypoint in pairs(waypoints) do
		humanoid:MoveTo(waypoint.Position)
		humanoid.MoveToFinished:Wait(0.4)
		
	end
end

However, there is one problem with this: The spider won’t take into account whether the player moved or not. So, if the waypoints were to be set, and the player moved, the spider would go to the player’s previous position, not the player’s current one.

Also, there is another problem. If there are two players, if the spider is chasing one player, even if the other player is closer, the other player will be ignored. How can I change the script so these two scenarios don’t happen?

1 Like