TD attack system loop feedback and improvements

Heya!
I’ve got this part of a script for my tower defense game’s tower’s attacking and I was wondering what I could improve to make it

  1. More performant
    or
  2. More readable and efficient.

(mainly around the part that revolves around “burst” attacks!)

runService.Heartbeat:Connect(function(deltaTime)
	for _, tower in module.Towers do -- attack loop
		
		tower.TimePassed += deltaTime
		if tower.TimePassed < tower.WaitTime then continue end
		
		local target = tower:Attack()
		
		if tower.Stats["BurstCount"] then
			tower.BurstStep += 1
			
			if tower.BurstStep >= tower.Stats["BurstCount"] then -- all burst depleted
				tower.BurstStep = 0
				tower.WaitTime = target and tower.Stats.Rate or 0.1
				
			else -- still has burst
				if target then
					tower.WaitTime = tower.Stats.BurstRate or 0.1
				else
					tower.BurstStep = 0
					tower.WaitTime = 0.1
				end
			end
		else
			tower.WaitTime = target and tower.Stats.Rate or 0.1
		end
		
		tower.TimePassed = 0
	end
end)

Thanks a lot!

There is not much you can do from what I can see, maybe you could create a function to manage the attacks, to make it easier to edit.

local function handleAttacks(tower)
	local target = tower:Attack()
	if tower.Stats["BurstCount"] then
		tower.BurstStep += 1

		if tower.BurstStep >= tower.Stats["BurstCount"] then -- all burst depleted
			tower.BurstStep = 0
			tower.WaitTime = target and tower.Stats.Rate or 0.1

		else -- still has burst
			if target then
				tower.WaitTime = tower.Stats.BurstRate or 0.1
			else
				tower.BurstStep = 0
				tower.WaitTime = 0.1
			end
		end
	else
		tower.WaitTime = target and tower.Stats.Rate or 0.1
	end
end

runService.Heartbeat:Connect(function(deltaTime)
	for _, tower in module.Towers do -- attack loop
		tower.TimePassed += deltaTime
		if tower.TimePassed < tower.WaitTime then continue end

		handleAttacks(tower)
		tower.TimePassed = 0
	end
end)
1 Like