function AngleBetweenVectors(o,V)return math.acos(o:Dot(V)/(o.Magnitude*V.Magnitude))end return function(o)local V=nil local q=o.MaxDetectionRange for J,g in pairs(game.Players:GetPlayers())do if g.Character and g.Character:FindFirstChild("\072\117\109\097\110\111\105\100\082\111\111\116\080\097\114\116")then local J=(g.Character.HumanoidRootPart.Position-o.HumanoidRootPart.Position).magnitude if J<q and math.deg(AngleBetweenVectors(o.HumanoidRootPart.CFrame.lookVector,g.Character.HumanoidRootPart.Position-o.HumanoidRootPart.Position))<=o.MaxDetectionAngle/2 then q=J V=g.Character end end end o.ClosestEnemy=V if o.ClosestEnemy then o:AddAggro(o.ClosestEnemy,1e-07)return true else return false end end
--[[
	
	Detects if an enemy is close by and if the agent can see the enemy.
	
	This will return the currently selected target if one is present
]]

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 -- 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)]]
				and 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, 0.0000001) -- we're adding a tiny aggro amount so that damages will take priority
		return true
	else
		--print("EnemyIsNearby,",false)
		return false
	end
end
