# assign multiple xy values to obj in for loop by math.random() with min distance between and confined

OK! This is like the third edit… I’ve deleted most of the code since it wasn’t helping. The problem is thus.

I’m going to assign dozens, maybe hundreds, of X and y coordinates inside a range of values through math.random(). The caveat is that the range must keep a distance from other X y values.

I’m scratching my head in scratchpad trying to figure out how to do this.

@xThomas here you go!
This uses a `while` loop to pick random places until it finds an empty spot. Each new object has to check the position of every other object, though, so higher numbers will take more time to finish

``````displayMode(FULLSCREEN)
function setup()
img = image(WIDTH,HEIGHT)
objects = {}
number = 100
maxDist = 50
for i = 1,number do
local x,y
local testDist = true
while testDist == true do
testDist = false
x,y = math.random(WIDTH),math.random(HEIGHT)
for ii,obj in pairs(objects) do
if vec2(x,y):dist(obj) < maxDist then testDist = true end
end
end
table.insert(objects,vec2(x,y))
setContext(img)
ellipse(x,y,maxDist)
setContext()
end
end

function draw()
background(40, 40, 50)
sprite(img,WIDTH/2,HEIGHT/2)
end
``````

@Dwinz: thanks!

Currently modifying the code to initialize my class instead of ellipse

Edit: I am/will be rewriting my StarSystem class to utilize a table that contains all the x,y values and for every pair of those, it will draw a star. Similar to how each 3 vertices in a mesh draws a triangle. Your code is valuable for the X,y positions, and I guess I’ll use the image thing too.