I am scripting a Mine Spawner
in a tower defense game.
To get a random position within the Mob Path
I am using the Waypoints
that run the Mob movements as reference points.
Currently, the mines only spawn along the X-Axis
OR Z-Axis
For reference, this is every Plot
within the Spawner Range, and every Waypoint
within range:
Here is the script that handles the spawner; it may not be coded as well as it should be:
Summary
local mathPoints = {}
--check if points have same X position or same Z position
for i, point in ipairs(points) do
local x = point.Position.X
local z = point.Position.Z
if not mathPoints[x] then
mathPoints[x] = {}
end
table.insert(mathPoints[x], point)
if not mathPoints[z] then
mathPoints[z] = {}
end
table.insert(mathPoints[z], point)
end
local minePosition
--check if points are in a straight line
local function newPoint()
for _, pointList in pairs(mathPoints) do
if #pointList >= 3 then
local firstPoint = pointList[math.random(#pointList)].Position
local isStraight = true
for i, point in ipairs(pointList) do
if i > 1 then
local direction = (point.Position - firstPoint).Unit
local dotProduct = math.abs(direction:Dot((pointList[i-1].Position - firstPoint).Unit))
if dotProduct < .99 then -- not within 2 degrees of each other, so not straight line
isStraight = false
break;
end
end
end
if isStraight then
--get random location between 2 points
minePosition = firstPoint + (pointList[#pointList].Position - firstPoint) * math.random()
break;
end
end
end
end
while true do
--spawn mine every 5 seconds
wait(1)
if minePosition then
print(minePosition)
local newMine = mine:Clone()
newMine.Parent = tower
newMine.PrimaryPart.Position = minePosition
end
newPoint()
end
This is the MathPoints
Table, based off of the towers position in the images above:
Summary
{
[-110.8000030517578] = ▼ { [1] = 4.5},
[-120.1999969482422] = ▼ {[1] = 4.2, [2] = 4.3, [3] = 4.4, [4] = 4.5},
[-35.49999618530273] = ▼ {[1] = 2.2, [2] = 1.2, [3] = 4.2},
[-38.49999618530273] = ▼ {[1] = 3.2},
[-45.89999389648438] = ▼ {[1] = 1.2},
[-62.60000228881836] = ▼ {[1] = 4.3},
[-69.99999237060547] = ▼ {[1] = 2.2},
[-86.69999694824219] = ▼ {[1] = 4.4},
[-96.09999847412109] = ▼ {[1] = 3.2}
Would anyone know how I can recode the script to spawn along both the X and Z axis?