Help with enemy ai!

Hi everyone! Ive been trying to make it so that while an enemy chases a player, that player’s vision is changed and then changed back after the enemy loses the player, or while chasing, another player gets closer to the enemy, then the other player, then the closer player gets chased and has its vision changed, while the player thats farther away gets its vision reset back to normal!

But I haven’t found a way to do that without the enemy breaking, the server sending local spam, or lots of lag! I’ve spent approximately more than 6 hours changing the script, like changing the order, adding “checks,” and much more! and I’m about to go goddamn insane!

How can I achieve this?

Btw, it’s in lines 64 to 84.

This is as far as I’ve gotten so far!

local figure = script.Parent
local humanoid = figure.Enemy
local PathFindingService = game:GetService("PathfindingService")
local lv = figure.Parent.Parent
lv:GetPropertyChangedSignal("Parent"):Connect(function(newparent)
	if lv.Parent.Name == "CurrentLevel" then
		figure.PrimaryPart:SetNetworkOwner(nil)
	end
end)
local deb = false
local Tweenservice = game:GetService("TweenService")
local Tweeninfo = TweenInfo.new(0.25, Enum.EasingStyle.Exponential, Enum.EasingDirection.In, 0, false, 0)
local Value1 = {}
Value1.Range = 20.5
local Value2 = {}
Value2.Brightness = 40	
local Value11 = {}
Value11.Range = 17.5
local Tween1 = Tweenservice:Create(script.Parent.Torso.PointLight, Tweeninfo, Value1)
local Tween2 = Tweenservice:Create(script.Parent.Torso.PointLight, Tweeninfo, Value2)
local Tween11 = Tweenservice:Create(script.Parent.Torso.PointLight, Tweeninfo, Value1)
local function canSeeTarget(target)
	local origin = figure.HumanoidRootPart.Position
	local direction = (target.HumanoidRootPart.Position - figure.HumanoidRootPart.Position).Unit * 45--This is the distance of studs the smiler can see you
	local ray = Ray.new(origin, direction)

	local hit, pos = workspace:FindPartOnRay(ray, figure)

	if hit then
		if hit:IsDescendantOf(target) == true then
			return true
		elseif hit:IsDescendantOf(target) == false then	
			return false
		end
	else
		figure.Head.Lose:Play()
		return false
	end
end
local nearestTarget = nil
local dim = true
local Fplayer
local function findTarget()
	local maxDistance = 5000
	local players = game.Players:GetPlayers()
	local ColCornumb = Color3.fromRGB(255, 255, 255)
	local Densinumb = require(game.ReplicatedStorage.LightTable)[1]
	local Brignumb = 0.25
	local Contranumb = 1
	local Saturnumb = 1
	local Fovnumb = 80
	local Blurnumb = 5
	local LightBrignumb = 5
	local ChangeTime = 0.5
	local Fwd = "a"
	local Back = "b"
	for index, player in ipairs(players) do
		if player.Character then
			local target = player.Character
			local distance = (figure.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude			
			if distance < maxDistance and canSeeTarget(target) == true and target.Humanoid.Health ~= 0 then-- IVE BEEN WORKING ON THIS FOR 6 HOURS NOW AND 
				if nearestTarget == nil and Fplayer == nil then
					print(target.Name.." Has been spotted!")
					game.ReplicatedStorage.EffectEvent:FireClient(player, Fwd, ColCornumb, Densinumb, Brignumb, Contranumb, Saturnumb, Fovnumb, Blurnumb, LightBrignumb, ChangeTime)
					Fplayer = player
					figure.Head.Lose:Stop()
					figure.Head.Scream.Playing = true
				end	
				maxDistance = distance
				nearestTarget = target
				Tween1:Play()
			elseif distance >= maxDistance or canSeeTarget(target) == false or target.Humanoid.Health == 0 then
				if nearestTarget ~= nil and player == Fplayer then			
					local np = game.Players:GetPlayerFromCharacter(nearestTarget)
					nearestTarget = nil
					Fplayer = nil
					game.ReplicatedStorage.EffectEvent:FireClient(np, Back, 0, 0, 0, 0, 0, 0, 0, 0, ChangeTime)
					print(target.Name.." Has lost the enemy!")
					figure.Head.Lose:Play()
					figure.Head.Scream.Playing = false
				end	
				Tween11:Play()
			end
		end
	end	
	return nearestTarget
end--																											I WANT TO SCREAM
local function attack(target)
	local distance = (figure.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
	if distance > 4.5 then --This is the distance of studs the Smiler can hit you at.
		humanoid:MoveTo(target.HumanoidRootPart.Position)
	else
		if not target:FindFirstChild("ForceField") and deb == false then
			deb = true
			target.Humanoid.Health = target.Humanoid.Health - 12.5 --This is the amount of damage the Smiler does.
			if target.Humanoid.Health <= 0 then
				figure.Head.Lose:Stop()
				--print("LoseStop")
				local killSounds = {figure.Head.Kill1, figure.Head.Kill2, figure.Head.Kill3}
				local randomNum = math.random(1, #killSounds)
				killSounds[randomNum]:Play()
			end
			local sounds = {figure.Head.Hit1, figure.Head.Hit2, figure.Head.Hit3}
			local randomNum = math.random(1, #sounds)
			sounds[randomNum]:Play()
			script.Parent.Torso.PointLight.Range = 75
			script.Parent.Torso.PointLight.Brightness = 1000
			Tween1:Play()
			Tween2:Play()
			task.wait(0.25)
			deb = false
		end
	end
end

local function getPath(destination)
	local pathParams = {
		["AgentHeight"] = 5.5,
		["AgentRadius"] = 2.5,
		["AgentCanJump"] = true
	}
	local path = PathFindingService:CreatePath(pathParams)

	path:ComputeAsync(figure.HumanoidRootPart.Position, destination.Position)

	return path
end

local function walkTo(destination)
	local path = getPath(destination)

	if path.Status == Enum.PathStatus.Success then	
		for index, waypoint in pairs(path:GetWaypoints()) do
			local target = findTarget()
			if target then
				if target.Humanoid.Health > 0 then
					--print("Target Found: "..target.Name)
					attack(target)
					break
				else
					figure.Head.Scream.Playing = false
				end
			else
				humanoid:MoveTo(waypoint.Position)
				humanoid.MoveToFinished:Wait()
			end
		end
	else
		humanoid:MoveTo(destination.Position - (figure.HumanoidRootPart.CFrame.LookVector*8))--idk
	end
end

local function patrol()
	local waypoints = script.Parent.BaseSmilerWaypoints:GetChildren()
	local randomNum = math.random(1, #waypoints)
	walkTo(waypoints[randomNum])
end

while true do
	task.wait(0.25)--smilers reaction time
	patrol()
end
1 Like