I am making a tower defense game, and I made a target system that targets the zombie which is closest to the base. But the problem is sometimes the tower attacks the closest zombie to it, not the base.
Here’s the video and the code inside the tower:
robloxapp-20231129-1922197.wmv (4.1 MB)
local turret = script.Parent
local waypoints = game.Workspace.Waypoints
local zombies = game.Workspace.Zombies
local function gettotalrange(zombie)
local range = 0
for i=zombie.NextWayPoint.Value,#waypoints:GetChildren() do
if i==1 then
range+=(waypoints[i].Position-Vector3.new(zombie.HumanoidRootPart.Position.X,waypoints[i].Position.Y,zombie.HumanoidRootPart.Position.Z)).Magnitude
elseif i ~= #waypoints:GetChildren() then
range+=(waypoints[i-1].Position-waypoints[i].Position).Magnitude
end
end
return range
end
local function getclosestzombie()
local zom = nil
local distance = math.huge
for _,zombie in pairs(zombies:GetChildren()) do
if zombie and zombie:FindFirstChild("HumanoidRootPart") and zombie:FindFirstChild("Humanoid") and zombie:FindFirstChild("Humanoid").Health ~= 0 then
if (zombie.Hidden.Value == false and turret.Hidden.Value == false) or turret.Hidden.Value == true then
if (Vector3.new(zombie.HumanoidRootPart.Position.X,turret.Union.Position.Y,zombie.HumanoidRootPart.Position.Z)-turret.Union.Position).Magnitude < turret.Range.Value then
local getrange = gettotalrange(zombie)
if getrange < distance then
distance = getrange
zom = zombie
end
end
end
end
end
return zom
end
while wait() do
local zombie = getclosestzombie()
if zombie then
zombie.Humanoid.Health -= turret.Damage.Value
turret.Union.CFrame = CFrame.new(turret.Union.Position,zombie.HumanoidRootPart.Position)
turret.Union.E:Play()
local line = Instance.new("Part",game.Workspace)
line.BrickColor = BrickColor.new("New Yeller")
line.Anchored = true
line.CanCollide = false
local dist = (zombie.HumanoidRootPart.Position-turret.Union.Position).Magnitude
line.Size = Vector3.new(0.1,0.1,dist)
line.CFrame = CFrame.new(turret.Union.Position,zombie.HumanoidRootPart.Position) * CFrame.new(0,0,dist/-2)
game:GetService("Debris"):AddItem(line,0.01)
wait(turret.FireRate.Value)
end
end