0

Targeting system is off and targets the newest found enemy?

P_4rio 15
3 days ago

Hello this might be a bit complicated and I'm not that very good at math so I had to follow tutorials obviously anyways I'm making a tower defense game and my targeting codes makes the towers target the newest found enemy instead of the enemy in front of all the other zombies.

I saw nothing about this since tower defense games are very uncommon in Roblox so I would like help!

local tower = script.Parent

local level = tower.Level

local damage = tower.Damage.Value

local firerate = tower.Firerate.Value / 10

local range = tower.Range.Value

local candetect = tower.CanDetect.Value

while true do
wait(firerate)

level = tower.Level

damage = tower.Damage.Value

firerate = tower.Firerate.Value / 10

range = tower.Range.Value

candetect = tower.CanDetect.Value

local target = nil
local humanoid = nil

for i, v in pairs(workspace.Zombies:GetChildren()) do -- Makes a loop checking for the enemies in the zombies folder
if candetect == true then -- detects if hidden detection is on
humanoid = v:FindFirstChild("Enemy") or v:FindFirstChild("Hidden") -- if it's on then set targeting to zombies with humanoids named: "Enemy" or "Hidden"
elseif candetect == false then
humanoid = v:FindFirstChild("Enemy") -- if it's off then set targeting to zombies with humanoids named: "Enemy"
end
local torso = v:FindFirstChild("Torso") -- gets the torso of the enemy so it can create bullets to do damage

if humanoid and torso and humanoid.Health > 0 then -- checks if enemy has a humanoid a torso and has health above 0
if (torso.Position - tower.HumanoidRootPart.Position).magnitude <= range then -- range calculation
target = torso -- sets the target
end
end
end

if target then
local torso = target

tower.Sound:Play()
tower:SetPrimaryPartCFrame(CFrame.new(tower.HumanoidRootPart.Position, Vector3.new(target.Position.X, target.Position.Y, target.Position.Z)))
local bullet = game.ReplicatedStorage:FindFirstChild("Bullet"):Clone()
bullet.Damage.Value = damage
bullet.Parent = workspace
bullet.Position = target.Position
end
end


Yes thats my code for how the towers are being handled (seperate script for handling upgrades)

0
I think first you need to understand what "FindFirstChild" does https://developer.roblox.com/en-us/api-reference/function/Instance/FindFirstChild rodrigo455 558 — 3d
0
I think first you need to understand what "FindFirstChild" does https://developer.roblox.com/en-us/api-reference/function/Instance/FindFirstChild rodrigo455 558 — 3d
0
I understand what it is for... I am using it to get the humanoids and other bunch-o-stuff. P_4rio 15 — 3d