I am developing a tower defense style game. When the towers shoot, they shoot at random enemies in range, and it doesn't get the one that's closest to the end. I have tried if functions and it still doesn't get the first one. The code below gets an enemy in range that exists. However, it always shoots the enemy that is the farthest away from the end when in fact I want the opposite.
local closestpart for n,e in pairs(workspace.Game.Enemies:GetChildren()) do if e ~= nil then local mag = (tower.PrimaryPart.Position-e.PrimaryPart.Position).magnitude if mag <= script.Parent.Range.Value then closestpart = e end end end
I have a source value, which says where it is on the map, but I cant seem to find out how to get that to make the towers ALWAYS shoot the first enemy that is in range.
Well, the best idea to do this is if the tower defense is a constant distance, make a speed value for each "monster" or whatever they are then add another value which counts how long they've existed. Then take the product of time and speed and divide it by the total distance of the track. This is the percentage of how far they're done with the track. After doing so, just compare that percentage.
local closestpart while true do for n,e in pairs(workspace.Game.Enemies:GetChildren()) do if e~= nil then local mag = (tower.PrimaryPart.Position-e.PrimaryPart.Position).magnitude if mag <= script.Parent.Range.Value then closestpart = e end end end end