How do i improve and optmize my code?

How do I optimize my edited version of kangeroojack’s soldier AI code? Sorry I’m a beginner.

–Body variables
local myHuman = script.Parent:WaitForChild(“Humanoid”)
local myTorso = script.Parent:WaitForChild(“Torso”)
local myHead = script.Parent:WaitForChild(“Head”)
local neck = myTorso:WaitForChild(“Neck”)
local headWeld = myTorso:WaitForChild(“Head Weld”)
local rArm = script.Parent:WaitForChild(“Right Arm”)
local lArm = script.Parent:WaitForChild(“Left Arm”)
local lShoulder = myTorso:WaitForChild(“Left Shoulder”)
local rShoulder = myTorso:WaitForChild(“Right Shoulder”)
local lArmWeld = myTorso:WaitForChild(“Left Arm Weld”)
local rArmWeld = myTorso:WaitForChild(“Right Arm Weld”)

–Fix network issues
for i,v in ipairs(script.Parent:GetDescendants()) do
if v:IsA(“BasePart”) and v:CanSetNetworkOwnership() then
v:SetNetworkOwner(nil)
end
end

–FX Sounds–
local whizsnds = {“rbxassetid://7025110285”, “rbxassetid://7025109937”, “rbxassetid://7025110680”, “rbxassetid://5361944601”}
local htisnds = nil
local debris = game:GetService(“Debris”)

local reloadanim = script.Parent.ReloadAnim
local reloadtrack = myHuman:LoadAnimation(reloadanim)
local NewBulletBeam = game.ReplicatedStorage.Miscs.Projectiles.NewBullet.Beam0

–M4 Variables
local m4 = script.Parent:WaitForChild(“M4”)
local m4Weld = m4:WaitForChild(“M4 Weld”)
local barrel = script.Parent:WaitForChild(“Barrel”)
local aimer = script.Parent:WaitForChild(“Aimer”)
local aimerWeld = aimer:WaitForChild(“Aimer Weld”)

local MuzzleFlash = barrel:WaitForChild(“Attachment”):WaitForChild(“Fire”)
local Smoke = barrel:WaitForChild(“Attachment”):WaitForChild(“Smoke”)
local Spark = barrel:WaitForChild(“Attachment”):WaitForChild(“Spark”)

–Sounds

local equipSound = m4:WaitForChild(“Equip”)
local fireSound = m4:WaitForChild(“Fire”)
local reloadSound = m4:WaitForChild(“Reload”)
local hurtSound = myHead:WaitForChild(“Hurt”)

local reloading = false
local weaponAimed = false
local weaponCool = true
local m4Equipped = false

local fullMag = 30
local mag = fullMag

local allies = {script.Parent.Name,“Civilian”, “Rifleman”, “RPG Soldier”}
local potentialTargets = {}

function checkDist(part1,part2)
return (part1.Position - part2.Position).Magnitude
end

function checkSight(target)
local ray = Ray.new(myTorso.Position, (target.Position - myTorso.Position).Unit * 100)
local part,position = workspace:FindPartOnRayWithIgnoreList(ray, {script.Parent})
if part then
if part:IsDescendantOf(target.Parent) then
return true
end
end
return false
end

function strafe(target)
myHuman.AutoRotate = false
if checkDist(target, myTorso) < 25 or not checkSight(target) then
if math.random(0,1) == 1 then
myHuman:Move(myTorso.CFrame.RightVector * 5)
else
myHuman:Move(-myTorso.CFrame.RightVector * 5)
end
wait(0.5)
end
end

function findTarget()
local dist = 200
local target = nil
potentialTargets = {}
local seeTargets = {}
for _,v in ipairs(workspace:GetChildren()) do
local human = v:FindFirstChild(“Humanoid”)
local torso = v:FindFirstChild(“Torso”) or v:FindFirstChild(“HumanoidRootPart”)
if human and torso and v.Name ~= script.Parent.Name then
if (myTorso.Position - torso.Position).magnitude < dist and human.Health > 0 then
for i,x in ipairs(allies) do
if x == v.Name then
break
elseif i == #allies then
table.insert(potentialTargets,torso)
end
end
end
end
end
if #potentialTargets > 0 then
for i,v in ipairs(potentialTargets) do
if checkSight(v) then
table.insert(seeTargets,v)
end
end
if #seeTargets > 0 then
for i,v in ipairs(seeTargets) do
if (myTorso.Position - v.Position).magnitude < dist then
target = v
dist = (myTorso.Position - v.Position).magnitude
end
end
else
for i,v in ipairs(potentialTargets) do
if (myTorso.Position - v.Position).magnitude < dist then
target = v
dist = (myTorso.Position - v.Position).magnitude
end
end
end
end
return target
end

function pathToLocation(target)
myHuman.AutoRotate = true
local path = game:GetService(“PathfindingService”):CreatePath()
path:ComputeAsync(myTorso.Position, target.Position)
local waypoints = path:GetWaypoints()

for _,waypoint in ipairs(waypoints) do
	if waypoint.Action == Enum.PathWaypointAction.Jump then
		myHuman.Jump = true
	end
	myHuman:MoveTo(waypoint.Position)
	delay(0.5,function()
		if myHuman.WalkToPoint.Y > myTorso.Position.Y then
			myHuman.Jump = true
		end
	end)
	local moveSuccess = myHuman.MoveToFinished:Wait()
	if not moveSuccess or checkSight(target) then
		break
	end
end

end

function walkRandom()
myHuman.AutoRotate = true
local randX = math.random(-100,100)
local randZ = math.random(-100,100)
local goal = myTorso.Position + Vector3.new(randX, 0, randZ)
local path = game:GetService(“PathfindingService”):CreatePath()
path:ComputeAsync(myTorso.Position, goal)
local waypoints = path:GetWaypoints()

if path.Status == Enum.PathStatus.Success then
	for i,waypoint in ipairs(waypoints) do
		if waypoint.Action == Enum.PathWaypointAction.Jump then
			myHuman.Jump = true
		end
		myHuman:MoveTo(waypoint.Position)
		delay(0.5,function()
			if myHuman.WalkToPoint.Y > myTorso.Position.Y then
				myHuman.Jump = true
			end
		end)
		local moveSucess = myHuman.MoveToFinished:Wait()
		if not moveSucess then
			break
		end
		if i % 5 == 0 then
			if findTarget() then
				break
			end
		end
	end
else
	wait(2)
end

end

function drawM4()
if m4Equipped == false then
m4Equipped = true
equipSound:Play()

	--Right Arm Setup
	rShoulder.Part1 = nil
	rArm.CFrame = aimer.CFrame* CFrame.new(1.25,0.05,-0.65) * CFrame.Angles(math.rad(80),math.rad(0),math.rad(-10))
	rArmWeld.Part1 = rArm
	
	--Left Arm Setup 
	lShoulder.Part1 = nil
	lArm.CFrame = aimer.CFrame * CFrame.new(-0.35,0.05,-1.48) * CFrame.Angles(math.rad(84),math.rad(-3),math.rad(28))
	lArmWeld.Part1 = lArm
	
	--M4 Setup
	m4Weld.Part0 = nil
	m4.CFrame = aimer.CFrame * CFrame.new(0.65,0.37,-2.22) * CFrame.Angles(math.rad(-90),0,0)
	m4Weld.Part0 = aimer
end

end

function yieldM4()
if weaponAimed == true then
weaponAimed = false
resetHead()
end
if m4Equipped == true then
m4Equipped = false
equipSound:Play()

	--Right ARm setup
	rArmWeld.Part1 = nil
	rShoulder.Part1 = rArm
	
	--Left Arm Setup
	lArmWeld.Part1 = nil
	lShoulder.Part1 = lArm
	
	--M4 Setup
	m4Weld.Part0 = nil
	m4.CFrame = myTorso.CFrame * CFrame.new(0,0,0.6) * CFrame.Angles(math.rad(-90),math.rad(-60),math.rad(90))
	m4Weld.Part0 = myTorso
end

end

function reloadM4()
if weaponAimed == true then
weaponAimed = false
resetHead()
end
if m4Equipped == true then
m4Equipped = false
equipSound:Play()

	--Right ARm setup
	rArmWeld.Part1 = nil
	rShoulder.Part1 = rArm

	--Left Arm Setup
	lArmWeld.Part1 = nil
	lShoulder.Part1 = lArm

	--M4 Setup
	m4Weld.Part0 = nil
	m4.CFrame = rArm.CFrame * CFrame.new(0,-1.5,-.5) * CFrame.Angles(math.rad(-180),0,0)
	m4Weld.Part0 = rArm
end

end

function aim(target)
if weaponAimed == false then
neck.C0 = neck.C0 * CFrame.Angles(0,math.rad(-15),0)
end
weaponAimed = true
for i=0,1,0.1 do
wait()
local look = Vector3.new(target.Position.X,myTorso.Position.Y,target.Position.Z)
myTorso.CFrame = myTorso.CFrame:Lerp(CFrame.new(myTorso.Position,look),i)
if reloading == false then
aimerWeld.Part1 = nil
aimer.CFrame = aimer.CFrame:Lerp(CFrame.new(aimer.Position,target.Position),i)
aimerWeld.Part1 = aimer
end
end
end

function resetHead()
neck.C0 = neck.C0 * CFrame.Angles(0,math.rad(15),0)
end

function shoot(target)
if weaponCool == true and reloading == false then
weaponCool = false

	local shot
	if checkDist(target,myTorso) > 70 then
		shot = 1
	else
		shot = 4
	end
	for i = 1, shot do
		wait(0.09)
		mag = mag - 1 
		
		MuzzleFlash:Emit(1)
		Smoke:Emit(1)
		Spark:Emit(5)
		
		local pointlight = barrel.Muzzle:Clone()
		pointlight.Parent = barrel
		pointlight.Enabled = true
		game:GetService("Debris"):AddItem(pointlight, 0.03)
		
		local bullet = Instance.new("Part",workspace)
		bullet.Size = Vector3.new(0.1,0.1,1)
		bullet.Transparency = 1
		bullet.CFrame = barrel.CFrame
		bullet.CanCollide = false
		bullet.Touched:Connect(function(obj)
			if not obj:IsDescendantOf(script.Parent) and obj.Parent.Name ~= script.Parent.Name then 
				local human = obj.Parent:FindFirstChild("Humanoid")
				if human then
					if obj.Name == "Head" then
						human:TakeDamage(15)
					else
						human:TakeDamage(10)
					end
				end
				
				htisnds = {"rbxassetid://3744371342", "rbxassetid://1565734259", "rbxassetid://3744371584", "rbxassetid://3744371091","rbxassetid://1565837588", "rbxassetid://1565836522", "rbxassetid://3744371864", "rbxassetid://1565734495" }
				local rndhitsnd = Instance.new("Sound", human.Parent)
				rndhitsnd.SoundId = htisnds[math.random(1, #htisnds)]
				rndhitsnd.Volume = 1
				rndhitsnd:Play()

				debris:AddItem(rndhitsnd, 1)
				
				bullet:Destroy()
			end
		end)
		fireSound:Play()
		
		local spread = Vector3.new(math.random(-shot,shot)/80,math.random(-shot,shot)/80,math.random(-shot,shot)/80)
		
		local bv = Instance.new("BodyVelocity",bullet)
		bv.MaxForce = Vector3.new(math.huge,math.huge,math.huge)
		bv.Velocity = (aimer.CFrame.LookVector + spread) * 500
		
		local s = Instance.new("Sound",bullet)
		s.Volume = 0.7
		s.PlaybackSpeed = 1
		s.Looped = false
		s.SoundId = whizsnds[math.random(1, #whizsnds)]
		s:Play()
		
		local a1 = Instance.new("Attachment",bullet)
		a1.Position = Vector3.new(0,0.05,0)
		local a2 = Instance.new("Attachment",bullet)
		a2.Position = Vector3.new(0,0,8)
		
		local b = Instance.new("Beam",bullet)
		b.Texture = "rbxassetid://2650206619"
		b.Attachment0 = a1
		b.Attachment1 = a2
		b.Color = NewBulletBeam.Color
		b.Transparency = NewBulletBeam.Transparency
		b.Segments = 50
		b.FaceCamera = true
		b.Enabled = true
		b.Width0 = .7
		b.Width1 = .7
		
		aimerWeld.Part1 = nil
		aimer.CFrame = aimer.CFrame * CFrame.Angles(math.rad(math.random(1,4)/4),0,0)
		aimerWeld.Part1 = aimer
		
		debris:AddItem(bullet, 5)
	end
	
	if mag <= 0 then
		reload()
		htisnds = nil
	end
	
	delay(0.05, function()
		weaponCool = true
		htisnds = nil
	end)
end

end

function reload()
if weaponAimed == true then
resetHead()
weaponAimed = false
end

if m4Equipped == true then
	reloadM4()
	reloadtrack:Play()
	reloadSound:Play()
	reloading = true
	wait(3)
	drawM4()
	reloading = false
	mag = fullMag
end

end

function main()
local target = findTarget()
if target then
if checkSight(target) then
if checkDist(myTorso,target) > 1 then
drawM4()
aim(target)
shoot(target)
end

		if checkDist(myTorso,target) < 25 then
			strafe(target)
		end
	else
		if weaponAimed == true then
			weaponAimed = false
			resetHead()
			spawn(function()
				for i=0,1,0.1 do
					wait()
					aimerWeld.Part1 = nil
					aimer.CFrame = myTorso.CFrame * CFrame.new(0,0.5,0) * CFrame.Angles(math.rad(-35),0,0)
					aimerWeld.Part1 = aimer
					if weaponAimed then
						break
					end
				end
			end)
		end
		pathToLocation(target)
	end
else
	yieldM4()
	walkRandom()
end

end

while wait() do
main()
end

1 Like

Hey, sorry to not give you feedback but there’s a category called Code Review specifically tailored towards optimizing and giving feedback on code. I think that creating this post there would get more attention and makes more sense in terms of category sorting.

1 Like