How would i go about making a tower like in tds/tb?

i making a small tower defense game, so far i finished the enemies, now i have to work on a simple tower that shoots, i tried using touched and touchended but it was very bad and laggy,
here is the old code:

local enemies = {}
local current = nil
local deb = true

while wait(0.5) do
	script.Parent.Touched:Connect(function(x)
		if x.Parent:FindFirstChild("Config") then
			if table.find(enemies, x.Parent) == nil then
				if deb == true then
					deb = false
					print(x.Parent.Name)
					table.insert(enemies, x.Parent)
					current = enemies[1]
					wait(1)
					deb = true
				end
			end
		end
		script.Parent.TouchEnded:Connect(function(x)
			table.remove(enemies, 1, x.Parent)
			current = nil
		end)
		if current ~= nil then
			print(current.Config.Health.Value)
			current.Config.Health.Value -= 2
			print(current.Config.Health.Value)
			wait(1)
		end		
	end)
end

how would i make a tower that actually is not laggy and works?

1 Like

I recommend using a region 3 for hitboxes, so you should use a RunService Heartbeat and then check if it’s an enemy. Then if so, you can create a line from the tower, to the enemy. (Gunshots), Idk what you’re doing atm, so. (Using a debounce) to make sure you don’t fire every heartbeat. (Too much parts.) Then destroy the parts after.

I also recommend using raycasts for the bullets

If the turret shoots bullets at the first enemy, you can just get the first enemy and remove a part of their health every time the turret fires.

You don’t need a bullet with a Touched event. Create a bullet purely for visuals. (preferably on the client)

This should be much more performant.