I made a Topic about how to fix the “First” targeting mode for my tower defense game I’m creating, but no one had answered it, so I made this topic instead. I want to get the distance between all of the parts (waypoints) in a folder, so I can determine the distance between an enemy and the exit. How do I do that? I know how to get the distance between the enemy and the waypoint its going to, but for some reason its not as efficient in practice as it is on paper. Any help I could get would be very much appreciated.
For reference, in the Waypoints folder, every waypoint is labled as such:
1, 2, 3, 4 … so on, so they’re in numerical order.
I know, but I’m wondering how I can loop that until it finds the distance between every part numerically in a folder and then connect it together.
For example: finding the distance between 1 to 2, and then 2 to 3, and so on, until the search comes up nil meaning it couldn’t find the next waypoint so it stops there.
You could simply add up all the distances between the waypoints.
local TotalDistance = 0
for i,v in ipairs(waypoints)
if waypoints[i - 1] then --// Previous one
local Distance = (v.Position - waypoints[i -1].Position).Magnitude
TotalDistance += Distance
end
end
You can just get the next point by getting the amount of waypoints there are. Such as using this method:
local Waypoints = {} -- Table of the waypoints
local Distances = {}
Amount = #Waypoints
function Check()
for i = 1, Amount-1 do -- subtract so you are able to get the last one in a pair.
local point = Waypoints[i]
local next_point = Waypoints[i+1]
local Distance = (point-next_point).Magnitude
table.insert(Distances,Distance) -- add to the table for checking purposes
if #Distances>=2 and Distances[i-1]<Distance then return end
end
end
This does seem to work, but do you think you could add or alter a piece of the script to make it so it stops counting after a certain waypoint, for example, which one the enemy is closest to? Otherwise this works great.
Here is what i have right now in my script. Is there any way to combine the function and the Distance to waypoint to make it so it detects which enemy is closer to the exit, or where the number is smaller depending on such?
local function FindDistanceToExit(mob)
local map = workspace.Map:FindFirstChildOfClass("Folder") -- where its finding waypoints
local MobMovingTo = mob.MovingTo.Value -- waypoint mob is moving to
local DistanceToWaypoint = (mob.HumanoidRootPart.Position - map.Waypoints[mob.MovingTo.Value].Position).Magnitude -- distance mob is from said waypoint
local TotalDistance = 0
local waypoints = map.Waypoints:GetChildren()
for i, v in ipairs(waypoints) do
if waypoints[i - 1] then
local Distance = (v.Position - waypoints[i-1].Position).Magnitude
TotalDistance += Distance
end
end
print(TotalDistance)
end