Enemy walking between players

I’m currently fixing up the AI from my game and while testing this happend with the enemys:


This is the player finding code:

local function FindTarget()
	local Distance = nil
	local nearestTarget = nil
	local MaxDistance = EnemyHumanoid.MaxVisionDistance.Value
	
	for _, Player in pairs(Players:GetPlayers()) do
		if Player.Character and Player.Character.HumanoidRootPart then
			local Target = Player.Character
			Distance = (Enemy.HumanoidRootPart.Position - Target.HumanoidRootPart.Position).Magnitude

			if Distance <= MaxDistance and Player.Character.Humanoid.Health > 0 then
				nearestTarget = Target
				MaxDistance = Distance
			else
				nearestTarget = nil
			end
		end
	end
	
	return nearestTarget
end
1 Like

I believe that the problem lies within the move code and not the target finding code. If you are using pathfinding, I believe that sometimes it can be a little behind where the player is, or it could also be registering not to touch the HumanoidRootPart and therefore stays a few studs away from the player. Try having the AI move a little farther than where the player is if the player is moving so it will catch up instead of staying behind the player.