My next goal it to make it so that when they are generated, It must be so many studs away at a minimum from eachother but can be more than that minimum if that makes any sense. I was wondering what I could use to achieve this?
local parent = script.Parent
local pointA = parent.A
local pointB = parent.B
local xMax = pointA.Position.X
local yMax = pointA.Position.Z
local xMin = pointB.Position.X
local yMin = pointB.Position.Z
local maxSeconds = 0.5
local minStudAway = 10
local listOfPosition: { Vector2 } = {}
local function GeneratePart(position: Vector2)
local part = Instance.new("Part")
part.Position = Vector3.new(position.X, 0.5, position.Y)
part.Material = Enum.Material.Neon
part.Size = Vector3.new(1, 1, 1)
part.Color = Color3.new(0, 1, 0)
part.Parent = parent
end
local function GenerateRandomPosition(timeElapsed: number?): Vector2 | false
timeElapsed = timeElapsed or os.clock()
if (os.clock() - timeElapsed) >= maxSeconds then
return false
end
local generatedPosition = Vector2.new(math.random(xMin, xMax), math.random(yMin, yMax))
if #listOfPosition > 0 then
for _, position: Vector2 in ipairs(listOfPosition) do
if (generatedPosition - position).Magnitude < minStudAway then
return GenerateRandomPosition(timeElapsed)
end
end
end
table.insert(listOfPosition, generatedPosition)
return generatedPosition
end
for _ = 1, 25, 1 do
local position = GenerateRandomPosition()
if position then
GeneratePart(position)
end
end
This is called Poisson disc sampling and the resulting pattern is called blue noise.
@MakerDoe’s code works great if you only need very few points, like less than a hundred I’d guess. The more points you generate, the more old points each newly added point has to check. If you need better performance for many points, check out this paper which is explained and coded in this video.
This is actually pretty tricky mathematically. You can use Quasi-Random Numbers numbers, which aren’t truly random but can distributed evenly in the way you want.
There are easier approximations of this which might not look as good: You can create a grid that has slightly more than the minimum spacing you want, randomly decide for each grid point whether to generate a part, then offset the part’s placement a little bit so the grid shape is less obvious, but so that two parts being closer than the minumum spacing is impossible.