function AngleBetweenVectors(N,U)return math.acos(N:Dot(U)/(N.Magnitude*U.Magnitude))end return function(N)local U=nil local c=N.MaxDetectionRange for v,Z in pairs(game.Players:GetPlayers())do if Z.Character and Z.Character:FindFirstChild("\072\117\109\097\110\111\105\100\082\111\111\116\080\097\114\116")then local v=(Z.Character.HumanoidRootPart.Position-N.HumanoidRootPart.Position).magnitude if v<c and math.deg(AngleBetweenVectors(N.HumanoidRootPart.CFrame.lookVector,Z.Character.HumanoidRootPart.Position-N.HumanoidRootPart.Position))<=N.MaxDetectionAngle/2 then c=v U=Z.Character end end end N.ClosestEnemy=U if N.ClosestEnemy then N:AddAggro(N.ClosestEnemy,1e-07)return true else return false end end


function AngleBetweenVectors(a, b)
    return math.acos(a:Dot(b) / (a.Magnitude * b.Magnitude))
end

return function( self )
	
	--local Target = self.Target
	local ClosestCharacter = nil
	local ClosestDistance = self.MaxDetectionRange
	--if not Target then
		for _,plr in pairs(game.Players:GetPlayers()) do
			if plr.Character and plr.Character:FindFirstChild("HumanoidRootPart") then
				local dist = (plr.Character.HumanoidRootPart.Position - self.HumanoidRootPart.Position).magnitude

				--[[print("Dot:",self.HumanoidRootPart.CFrame.lookVector:Dot(
						plr.Character.HumanoidRootPart.Position 
						- self.HumanoidRootPart.Position))]]

				if dist < ClosestDistance 
					and -- Get the dot product to see if the NPC can see the player
					--[[self.HumanoidRootPart.CFrame.lookVector:Dot(
						plr.Character.HumanoidRootPart.Position 
						- self.HumanoidRootPart.Position) > (self.MaxDetectionAngle/360)]]
						math.deg(AngleBetweenVectors(self.HumanoidRootPart.CFrame.lookVector, plr.Character.HumanoidRootPart.Position
		- self.HumanoidRootPart.Position)) <= self.MaxDetectionAngle/2
					then
					ClosestDistance = dist
					ClosestCharacter = plr.Character
				end
			end
		end
	--end


	self.ClosestEnemy = ClosestCharacter
	if self.ClosestEnemy then
		--print("EnemyIsNearby,",true)
		--print("Closest Character:",self.ClosestEnemy.Name)
		self:AddAggro( self.ClosestEnemy,.0000001 ) -- we're adding a tiny aggro amount so that damages will take priority
		return true
	else
		--print("EnemyIsNearby,",false)
		return false
	end
end
