Hello!
So I’m making a game similar to Bloons TD 5 or Tower Defense on ROBLOX. I have a wave script which spawns enemies each round, and I’ve run into an issue; The towers don’t shoot the first npc, instead they shoot the closest one and I don’t know how to fix this.
Here is my code:
local turn = script.Parent.Turn
local stats = script.Parent.Statistics
local damage = stats.Damage
local range = stats.Range
local fireRate = stats.FireRate
while wait(fireRate.Value) do
local target = nil
for i,v in pairs(workspace.TestMap:GetChildren()) do
local human = v:FindFirstChild("Humanoid")
local torso = v:FindFirstChild("Torso")
if human and torso and human.Health > 0 then
if (torso.Position - turn.Hit.Position).magnitude <= range.Value then
target = torso
end
end
end
if target then
turn:SetPrimaryPartCFrame(CFrame.new(turn.PrimaryPart.Position, target.Position))
local beam = Instance.new("Part")
beam.BrickColor = BrickColor.new("Bright red")
beam.FormFactor = "Custom"
beam.Material = "Neon"
beam.Transparency = 0.25
beam.Anchored = false
beam.Locked = true
beam.CanCollide = false
local distance = (target.Position - turn.Hit.Position).magnitude
beam.Size = Vector3.new(0.5, 0.5, 2)
beam.Parent = script.Parent
beam.CFrame = CFrame.new(turn.Hit.CFrame.p, target.Position) * CFrame.new(0, 0, -distance / 2)
beam.Velocity = beam.CFrame.lookVector * 250
local db = false
beam.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and hit.Parent == target.Parent and db == false then
db = true
hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health - damage.Value
game:GetService("Debris"):AddItem(beam, 0.01)
end
end)
game:GetService("Debris"):AddItem(beam, 2)
end
end
Any help is appreciated!
Thanks.