Code Review on a Enemy Ai script

Include a standalone, bare-bones rbxl file with only the code you want reviewed.

  • Code Review is for reviewing specific parts of your code, and not your whole game.
  • Code Review is intended for improving already-working code. If you need help debugging your code, please use Help and Feedback > Scripting Support

This code works I just wanna know if i can improve anything about or if im missing something.

thanks,
HumanoidNPC.lua (17.9 KB)

local SmartEnemyAI3 = {}
SmartEnemyAI3.__index = SmartEnemyAI3

local ReplicatedStorage = game.ReplicatedStorage
local UIS = game:GetService("UserInputService")
local RS = game:GetService("RunService")
local PS = game:GetService("Players")
local tweenservice = game:GetService("TweenService")
local playerlist = game.Players:GetPlayers()
local Debris = game:GetService("Debris")

local RagdollService = require(game:GetService("ServerScriptService").RagdollStuff.RagdollService)
local Remotes: Folder = ReplicatedStorage:WaitForChild("Remotes")
local AnimateEvent = ReplicatedStorage["Visual/Sound Related"].ServerAnimations:WaitForChild("PlayAnimation")
local Server_Motors2 = Remotes:WaitForChild("ServertoServer_Motors")
local characterfolder = workspace:WaitForChild("Characters")
local SanityModule = require(game.ReplicatedStorage:WaitForChild("SanityModule"))
local NPCATTACK = game:GetService("ServerStorage").NPCAttackRelated.AttackingEvent
local NPCBLOCK = game:GetService("ServerStorage").NPCAttackRelated.BlockingEvent
local NPCROLL = game:GetService("ServerStorage").NPCAttackRelated.RollingEvent
local WUP = require(game.ServerScriptService.CombatRelated.Combat.WeaponUniqueProperties)

local DifficultyConfig = {
	[1] = { attackDelay = 1.2, blockChance = 0.1, parryChance = 0.1, RollChance = 0, heavyChance = 0.0025, Strafe = false},
	[2] = { attackDelay = 0.9, blockChance = 0.25, parryChance = 0.25, RollChance = 0.25, heavyChance = 0.05 , Strafe = false},
	[3] = { attackDelay = 0.6, blockChance = 0.75, parryChance = 0.5, RollChance = 0.5, heavyChance = 0.1, Strafe = true},
	[4] = { attackDelay = 0.6, blockChance = 1, parryChance = 1, RollChance = 1, heavyChance = 0.1, Strafe = true},-- Hard enemies are faster + smarter
}

function SmartEnemyAI3.new(character)
	local self = setmetatable({}, SmartEnemyAI3)
	
	-- Define Properties
	
	self.character = character
	self.Weapon = character:FindFirstChildOfClass("Tool")
	print(self.Weapon)
	self.Weapontype = self.Weapon:GetAttribute("WeaponType")
	self.MovementAnimations = ReplicatedStorage["Visual/Sound Related"].ServerAnimations.GeneralMovementAnimations
	self.WeaponAnimations = ReplicatedStorage["Visual/Sound Related"].ServerAnimations["General"..self.Weapontype.."Animations"]
	self.equipped = false
	self.isBlocking = false
	self.Humanoid = character:WaitForChild("Humanoid")
	self.HumanoidRootPart = character:WaitForChild("HumanoidRootPart")
	self.UniqueID = character:GetAttribute("UniqueID")
	self.Dashing = false
	self.DashingCooldown = false
	
	self.difficulty = self.character:GetAttribute("Difficulty")
	
	print(self.difficulty)

	self.config = DifficultyConfig[self.difficulty]

	self.State = "Idle"
	self.StateTimer = 0
	
	self.StateMachine = false
	
	self.WillBlock = nil
	self.WillRoll = nil
	self.WillParry = nil
	self.WillHeavy = nil
	
	self.AniWalk = self.MovementAnimations.Walk
	self.AniSprint = self.MovementAnimations.Sprint
	self.Froll = self.MovementAnimations.RollAnimation
	self.Broll = self.MovementAnimations.BackwardRollAnimation
	self.Idle = self.WeaponAnimations.Idle
	self.Block = self.WeaponAnimations.Blocking
	
	self.Counter = 0
	self.Limit = 5
	
	self.cooldown = 2
	self.timer = 0
	
	print(self.config)	
	
	self.AttackWindup = math.random(1, (self.config.attackDelay * 10)) / 10
	
	self.connections = {}
	
	self.alignorientation = Instance.new("AlignOrientation")
	self.alignorientation.Parent = self.HumanoidRootPart
	self.alignorientation.Mode = Enum.OrientationAlignmentMode.OneAttachment
	self.alignorientation.Attachment0 = self.HumanoidRootPart.RootAttachment
	self.alignorientation.PrimaryAxisOnly = true
	self.alignorientation.RigidityEnabled = true
	self.alignorientation.MaxTorque = 1000000
	self.alignorientation.Enabled = false
	
	self.linearVelocity = Instance.new("LinearVelocity")
	self.linearVelocity.Attachment0 = self.HumanoidRootPart.RootAttachment
	self.linearVelocity.ForceLimitMode = Enum.ForceLimitMode.PerAxis
	self.linearVelocity.MaxAxesForce = Vector3.new(25000,0,0)
	self.linearVelocity.RelativeTo = Enum.ActuatorRelativeTo.Attachment0
	self.linearVelocity.Parent = self.HumanoidRootPart
	self.linearVelocity.Enabled = false
	self.linearVelocity.Name = "Strafe"
	
	-- Start Events
	
	self.HumanoidRootPart:SetNetworkOwner(nil)
	
	self.Humanoid:UnequipTools(self.Weapon)
	
	self.Number = 0

	--self:loadAnimations()

	self:connectEvents()
	
	print(self.UniqueID.." Has been turned")

	return self
end

function SmartEnemyAI3:motor6d()
	if self.Weapon:FindFirstChildOfClass("Configuration") and self.Weapon:FindFirstChildOfClass("Configuration").Name == "6D_Config" then
		local Configuration: Configuration = self.Weapon:WaitForChild("6D_Config")
		for _, Motor_Config: Configuration in Configuration:GetChildren() do
			if Motor_Config:IsA("Configuration") then
				Server_Motors2:Fire(nil, self.character, self.Weapon)
			end
		end
	end
end

function SmartEnemyAI3:SyncToPlayer(player)
	AnimateEvent:FireClient(player, self.character, self.Idle, self.equipped)
end

function SmartEnemyAI3:RemoveConnections()
	if self.connections then
		for _, conn in ipairs(self.connections) do
			conn:Disconnect()
		end
		self.connections = {}
	end

	if self.Humanoid then
		for _, track in pairs(self.Humanoid:GetPlayingAnimationTracks()) do
			track:Stop()
		end
	end

	if self.linearVelocity and self.linearVelocity.Parent then
		self.linearVelocity.Enabled = false
		self.linearVelocity:Destroy()
	end
	if self.alignorientation and self.alignorientation.Parent then
		self.alignorientation.Enabled = false
		self.alignorientation:Destroy()
	end

	if self.Humanoid then
		self.Humanoid.WalkSpeed = 16 -- default
		self.Humanoid:Move(Vector3.new(0,0,0))
	end

	if self.Weapon and self.Humanoid then
		self.Humanoid:UnequipTools()
	end
end

function SmartEnemyAI3:connectEvents()
	
	local lastSpeedState = "Idle" 

	table.insert(self.connections, self.Humanoid.Running:Connect(function(speed)
		self.speed = speed

		local newSpeedState
		if speed >= 17.5 then
			newSpeedState = "Sprint"
		elseif speed > 1 then
			newSpeedState = "Walk"
		else
			newSpeedState = "Idle"
		end

		if newSpeedState ~= lastSpeedState then
			lastSpeedState = newSpeedState
			
			print("SpeedStateChanged")
			
			if newSpeedState == "Sprint" then
				AnimateEvent:FireAllClients(self.character, self.AniWalk, false, true)
				AnimateEvent:FireAllClients(self.character, self.AniSprint, false, true)
				AnimateEvent:FireAllClients(self.character, self.AniSprint, true, true)
			elseif newSpeedState == "Walk" then
				AnimateEvent:FireAllClients(self.character, self.AniWalk, false, true)
				AnimateEvent:FireAllClients(self.character, self.AniSprint, false, true)
				AnimateEvent:FireAllClients(self.character, self.AniWalk, true, true)
			else -- Idle
				AnimateEvent:FireAllClients(self.character, self.AniWalk, false, true)
				AnimateEvent:FireAllClients(self.character, self.AniSprint, false, true)
			end
		end
	end))
	
	table.insert(self.connections, self.character:GetAttributeChangedSignal("IsBlocking"):Connect(function()
		if self.character:GetAttribute("IsBlocking") == true then
			AnimateEvent:FireAllClients(self.character, self.Block, true, true)
		else
			AnimateEvent:FireAllClients(self.character, self.Block, false, true)
		end	
	end))
	
	table.insert(self.connections, self.character:GetAttributeChangedSignal("Ragdolled"):Connect(function()
		if self.character:GetAttribute("IsBlocking") == false then
			NPCBLOCK:Fire(self.character, false)
			for i,v in pairs(self.character.Humanoid:GetPlayingAnimationTracks()) do
				if v.Name ~= "Idle" then
					v:Stop()
				end
			end
		end
	end))
	
	table.insert(self.connections,self.Weapon.Equipped:Connect(function()
		self:motor6d()
		self.equipped = true
		task.defer(function()
			AnimateEvent:FireAllClients(self.character, self.Idle, true)
		end)
	end))

	table.insert(self.connections, self.Weapon.Unequipped:Connect(function()
		self.equipped = false
		task.defer(function()
			AnimateEvent:FireAllClients(self.character, self.Idle, false)
		end)
	end))
	
	table.insert(self.connections,PS.PlayerAdded:Connect(function(player)
		task.defer(function()
			self:SyncToPlayer(player)
		end)
	end))
	
	self.Humanoid:EquipTool(self.Weapon)
	
	table.insert(self.connections, RS.Heartbeat:Connect(function(dt)
		if self.Humanoid and self.Humanoid.Health > 0 and self.character.Parent then
			if self.StateMachine == true then
				self:FollowCharacter(dt)
			else
				self:UpdateState(dt)
			end
		elseif self.Humanoid.Health <= 0 or not self.character or self.character:GetAttribute("Loaded") == false then
			self:RemoveConnections()
		end
	end))
end

function SmartEnemyAI3:FindNearestCharacter()

	local nearestEnemy = nil
	local Enemydistance = nil
	local Enemydirection = nil

	for I, character in pairs(characterfolder:GetChildren()) do

		local rootPart = character:FindFirstChild("HumanoidRootPart")

		local character = character
		if character and character ~= self.character and character.Humanoid.Health > 0 and not character:GetAttribute("dead") and self.character:GetAttribute("Faction") ~= character:GetAttribute("Faction") and character:GetAttribute("Testing") == false then
			if rootPart ~= nil then
				local distanceVector = (character.HumanoidRootPart.Position - self.HumanoidRootPart.Position)
				if not nearestEnemy then
					nearestEnemy = character
					Enemydistance = distanceVector.Magnitude
					Enemydirection = distanceVector.Unit
				elseif distanceVector.Magnitude < Enemydistance then
					nearestEnemy = character
					Enemydistance = distanceVector.Magnitude
					Enemydirection = distanceVector.Unit
				end
			else

			end	
		end
	end
	return nearestEnemy, Enemydistance, Enemydirection
end

function SmartEnemyAI3:EnterState(newState)
	if self.State ~= newState then
		self.State = newState
		self.StateChanged = os.clock()
	end
end

function SmartEnemyAI3:RunState(dt, nearestEnemy, Enemydistance, Enemydirection)
	if not self.State then return end

	local stateFunc = self["State_"..self.State]
	if stateFunc then
		stateFunc(self, dt, nearestEnemy, Enemydistance, Enemydirection)
	end
end

function SmartEnemyAI3:State_Idle(dt)
	self.Humanoid.WalkSpeed = 0
	self.Humanoid:Move(Vector3.zero)
	self.alignorientation.Enabled = false
	self.linearVelocity.Enabled = false
	NPCBLOCK:Fire(self.character, false)
end

function SmartEnemyAI3:State_Chase(dt, enemy, distance, direction)
	if distance <= self.DistanceForAttack + 10 and not SanityModule:StunCheck(self.character) and not self.Dashing then
		self.Humanoid.WalkSpeed = 15
		self.Humanoid:Move(direction)
		NPCBLOCK:Fire(self.character, false)
		if self.AttackWindup <= 0 then
			self.AttackWindup = math.random(1, (self.config.attackDelay * 10)) / 10
			if math.random() < 0.5 then
				self.AttackWindup = 0
			end
		end

	elseif distance <= self.DistanceForAttack + 40 and not SanityModule:StunCheck(self.character) and not self.Dashing then
		self.Humanoid.WalkSpeed = 20
		self.Humanoid:Move(direction)
		NPCBLOCK:Fire(self.character, false)
	else
		self.alignorientation.Enabled = false
		self.linearVelocity.Enabled = false
		self.Humanoid:Move(Vector3.new(0,0,0))
	end
end

function SmartEnemyAI3:State_Attack(dt, enemy, distance, direction)
	if distance <= self.DistanceForAttack and not SanityModule:StunCheck(self.character) and not self.Dashing then

		self.alignorientation.Enabled = true
		if self.config.Strafe == true then
			self.linearVelocity.Enabled = true
		end

		local ComboCD  = self.character:GetAttribute("ComboCD")
		local Blocking = self.character:GetAttribute("IsBlocking")

		if SanityModule:StunCheck(enemy) or self.AttackWindup <= 0 then

			self.WillBlock = nil
			if self.WillHeavy == nil then
				if math.random() > self.config.heavyChance then
					self.WillHeavy = false
				else
					self.WillHeavy = true
				end
			end

			if not SanityModule:StunCheck(self.character) and not SanityModule:AttackStunCheck(self.character) and not SanityModule:ComboLag(self.character) and self.Humanoid.Health > 0 and self.equipped and not Blocking and not self.WillHeavy and not self.Dashing then
				if not enemy:GetAttribute("Ragdolled") then
					NPCATTACK:Fire(self.character, 1)
				end
			elseif not SanityModule:StunCheck(self.character) and not SanityModule:AttackStunCheck(self.character) and self.Humanoid.Health > 0 and self.equipped and not Blocking and self.WillHeavy and not self.Dashing then
				if not enemy:GetAttribute("Ragdolled") then
					NPCATTACK:Fire(self.character, 2)
				end
			else
				NPCBLOCK:Fire(self.character, false)
			end
			self.WillHeavy = nil
		else
			if self.AttackWindup > 0 then
				self.AttackWindup -= dt
			end
		end

		self.Humanoid.WalkSpeed = 0
		self.Humanoid:Move(direction)
	end
end

function SmartEnemyAI3:State_Defend(dt, enemy, distance, direction)
	if distance <= self.DistanceForAttack + 5 and not SanityModule:StunCheck(self.character) and not self.Dashing and (SanityModule:AttackStunCheck(enemy) and not SanityModule:StunCheck(enemy)) then
		self.alignorientation.Enabled = true
		self.linearVelocity.Enabled = true
		
		local function Dash()
			if not self.Dashing then
				self.Dashing = true
				self.DashingCooldown = true
				NPCBLOCK:Fire(self.character, false)
				AnimateEvent:FireAllClients(self.character, self.Broll, true, true)
				NPCROLL:Fire(self.character)
				local lv = Instance.new("LinearVelocity")
				lv.Parent = self.character.HumanoidRootPart
				lv.Attachment0 = self.character.HumanoidRootPart.RootAttachment
				lv.ForceLimitMode = Enum.ForceLimitMode.PerAxis
				lv.RelativeTo = Enum.ActuatorRelativeTo.World
				lv.VectorVelocity = self.character.HumanoidRootPart.CFrame.LookVector * -40
				lv.MaxAxesForce = Vector3.new(25000,25000,25000)
				task.wait(0.2)
				lv:Destroy()
				self.Dashing = false
				task.wait(3)
				self.DashingCooldown = false
			end
		end

		local function Block()
			if not self.isBlocking then
				self.isBlocking = true
				if self.WillParry then
					task.wait(0.1)
					if not SanityModule:StunCheck(self.character) and not SanityModule:AttackStunCheck(self.character) and self.Humanoid.Health > 0 and self.equipped and not self.character:GetAttribute("IsBlocking") and not self.Dashing then
						NPCBLOCK:Fire(self.character, true)
					end
				else
					NPCBLOCK:Fire(self.character, true)
				end
				self.isBlocking = false
			end
		end
		
		if self.WillBlock == nil then
			if math.random() < self.config.blockChance then
				self.WillBlock = true
				if math.random() < self.config.parryChance then
					self.WillParry = true
				else
					self.WillParry = false
				end
			else
				if math.random() < self.config.RollChance then
					self.WillRoll = true
				else
					self.WillRoll = false
				end
				self.WillBlock = false
			end
		end

		if not SanityModule:StunCheck(self.character) and not SanityModule:AttackStunCheck(self.character) and self.Humanoid.Health > 0 and self.equipped and self.WillBlock and not self.WillRoll and not self.Dashing then
			Block()
		elseif not SanityModule:StunCheck(self.character) and not SanityModule:AttackStunCheck(self.character) and self.Humanoid.Health > 0 and self.equipped and not self.WillBlock and self.WillRoll and not self.character:GetAttribute("RollSafeCD") and not self.Dashing and not self.DashingCooldown then
			Dash()
		end

		self.Humanoid.WalkSpeed = 5
		self.Humanoid:Move(direction)
	end
end

function SmartEnemyAI3:State_Backup(dt, enemy, distance, direction)
	self.Humanoid.WalkSpeed = 15
	self.Humanoid:Move(-direction)
end

function SmartEnemyAI3:UpdateState(dt)
	local Ragdoll = self.character:GetAttribute("Ragdolled")

	if not Ragdoll then
		self.HumanoidRootPart:SetNetworkOwner(nil)
	end

	local nearestEnemy, Enemydistance, Enemydirection = self:FindNearestCharacter()

	local head = self.character:FindFirstChild("Head")

	if head ~= nil and nearestEnemy ~= nil and nearestEnemy.Humanoid.Health > 0 then
		local vector1 = (nearestEnemy.Head.Position - head.Position).Unit
		vector1 = Vector3.new(vector1.X, 0, vector1.Z).Unit
		local elook = self.character.HumanoidRootPart.CFrame.LookVector
		elook = Vector3.new(elook.X, 0, elook.Z).Unit
		local dot = elook:Dot(vector1)

		local diff = nearestEnemy.HumanoidRootPart.Position - self.HumanoidRootPart.Position
		local angle = math.atan2(-diff.X, -diff.Z)
		self.alignorientation.CFrame = CFrame.Angles(0, angle, 0)

		if nearestEnemy:GetAttribute("Ragdolled") then
			self.DistanceForAttack = WUP[self.Weapon.Name].WeaponStandingRange + 3
		else
			self.DistanceForAttack = WUP[self.Weapon.Name].WeaponStandingRange
		end

		if nearestEnemy then

			if self.config.Strafe == true then
				self.Counter += dt
				self.timer -= dt

				if self.Counter >= self.Limit then
					self.linearVelocity.VectorVelocity = Vector3.new(math.random(-7.5,7.5), 0, 0)
					self.Counter = 0
				end
			end

			local Hrp = nearestEnemy.HumanoidRootPart
			
			if Ragdoll 
				or self.Humanoid.Health <= 0 
				or not nearestEnemy 
				or not nearestEnemy:FindFirstChild("Humanoid") 
				or self.Dashing
				or nearestEnemy.Humanoid.Health <= 0 
				or SanityModule:StunCheck(self.character) 
			then
				return self:EnterState("Idle")
			end
			
			if Enemydistance <= (self.DistanceForAttack - (self.DistanceForAttack / 4)) then
				self:EnterState("Backup")
			elseif Enemydistance <= self.DistanceForAttack + 5 and (SanityModule:AttackStunCheck(nearestEnemy) and not SanityModule:StunCheck(nearestEnemy)) then
				self:EnterState("Defend")
			elseif Enemydistance <= self.DistanceForAttack then
				self:EnterState("Attack")
			elseif Enemydistance <= self.DistanceForAttack + 40 then
				self:EnterState("Chase")
			end
		else
			self:EnterState("Idle")
		end
	end
	self:RunState(dt,nearestEnemy,Enemydistance,Enemydirection)
end

return SmartEnemyAI3
2 Likes

Briefly looked through the code. Won’t comment on implementation details, functionality, or optimization, but there are some nit picks to be made.

There’s a few unused variables at the top, like tweenservice, playerlist, and Debris.

Field names should have uniform capitalization. There seems to be a lot of field names which are both uppercase and lowercase.

Line 281 is an empty else clause.

Lines 269-284 could be refactored to greatly reduce nesting depth through the use of inverse conditions. (E..g. if rootpart == nil then continue) Another example is on line 387.

Variable names should follow the same capitalization format. See lines 260-263.

Spacing is a little odd. Most of the functions have no initial space, except for at lines 168, 259.

The UpdateState method on line 457 would benefit greatly from modularization: split it up into smaller methods or functions.

Avoid acronym variable names like RS and PS; UIS is a little more fine since there’s not much else it could refer to.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.