I am working on a tower defense styled game and so I made a tower script that gets the zombies within range of the tower and then does a "for i" loop to get which one is the furthest, but when I run the script it keeps targetting the wrong zombies, I tried several things to fix it but to no avail and I need some support.
Script: (Serverside)
--//Services
local players = game:GetService("Players")
local repStorage = game:GetService("ReplicatedStorage")
--//Variables
local tower = script.Parent
local towerHumanoidRootPart = tower:WaitForChild("HumanoidRootPart")
local towerAnimations = tower:WaitForChild("TowerAnimations")
local towerSoundEffects = tower:WaitForChild("TowerSoundEffects")
local towerStats = tower:WaitForChild("TowerStats")
local pathsFolder = workspace:WaitForChild("PathsFolder")
local function shoot()
while wait(.01) do
for i, v in pairs(pathsFolder:GetChildren()) do
local zombiesFolder = v:WaitForChild("Zombies")
for i, z in pairs(zombiesFolder:GetChildren()) do
local zombieHumanoidRootPart = z:WaitForChild("HumanoidRootPart")
if (zombieHumanoidRootPart.CFrame.p - towerHumanoidRootPart.CFrame.p).magnitude <= require(towerStats).Range then
local zombiesDistanceWalkedValues = {}
local zombieStats = z:WaitForChild("ZombieStats")
local zombieDistanceWalked = zombieStats:WaitForChild("DistanceWalked")
table.insert(zombiesDistanceWalkedValues, zombieDistanceWalked.Value)
local furthestDistance = 0
for i, d in pairs(zombiesDistanceWalkedValues) do
if d > furthestDistance then
furthestDistance = d
end
end
if zombieDistanceWalked.Value == math.max(furthestDistance) then
towerHumanoidRootPart.CFrame = CFrame.new(towerHumanoidRootPart.CFrame.p, zombieHumanoidRootPart.CFrame.p)
towerHumanoidRootPart.Orientation = Vector3.new(0, towerHumanoidRootPart.Orientation.Y, 0)
wait(require(towerStats).FireRate - .01)
end
end
end
end
end
end
--//Callers
shoot()

1 comment
Thanks, I changed the script based on what you said and it works just fine now.