I have created a grid and have multiple spawning objects on the grid. How could I prevent from a new spawing object to spawn over an existing object.
Here is the code I use to setup my random reference to my grid:
math.randomseed( os.time() )
local function shuffleTable( t )
local rand = math.random
assert( t, “shuffleTable() expected a table, got nil” )
local iterations = #t
local j
for i = iterations, 2, -1 do
j = rand(i)
t[i], t[j] = t[j], t[i]
end
end
shuffleTable( spawnRandomX )
shuffleTable( spawnRandomY )
for i = 1, 9 do
print( spawnRandomX[i] )
end
for i = 1, 5 do
print( spawnRandomY[i] )
end
And this is how I setup the grid (Both of these I learned in tutorials modifing as needed):
for vVal = 1, 4 do
for hVal = 1, 8 do
idx = idx + 1
square = display.newImageRect(“images/Square.png”, 64, 64)
square.x = (hVal * 65)-23
square.y = vVal * 65
square:addEventListener ( “tap”, squareTapped )
squares[idx] = square
squares[idx].idx = idx
end
end
later in the program a run this, which allows me to drop an object on to the grid:
squareNewBack.x = spawnRandomX[math.random(1,8)]
squareNewBack.y = spawnRandomY[math.random(1,4)]
and then change it slightly to spawn another one:
squareNewBack2.x = spawnRandomX[math.random(1,8)]
squareNewBack2.y = spawnRandomY[math.random(1,4)]
My problem is some times they want to occupy the same location on the grid. How can I account for the position of the objects already on the grid so that any spawning object finds a random open spot?
Is there a better way for me to make a grid for this?
Mahalo (thanks),
Kaleo