Create a grid and spawn object to random spot onto grid?

I cant seem to find any tutorials on grid systems…

I have a square ‘play area’ (256 x256) in my scene , I want it to be a 4 x 4 grid , so it can hold 64 x 64 size sprites.

I want to spawn an object into a random tile of this grid, but only if there isn’t an object already in this tile.

How would I set it up this grid over my ‘play area’ ?
How would I spawn an object to random spot on this grid?

I don’t want my whole scene to be a grid, I just want the ‘play area’ square to be a grid.
So it will have all empty spots in the grid and then if I click a button I can spawn an object to a random spot on this 4 x 4 grid if that tile is free.

Also I would like to do it in a way where if I want to extend the size of this grid at a later stage in the level to say a 5 x 5 , its easily done with changing variables and it updates the grid visually and works the same.

Any help would be appreciated, thanks so much :slight_smile:

Here you need to think carefully :thinking:
You can create cells that are placed at a distance from each other using a custom object, and if X is greater than the end of the game zone, delete it. And create an object at the position of a random cell object. And move the cells away from each other.
Although this may be difficult. Then I can provide an example.

The easiest way would be to create a grid of objects like Node, pick the Node objects that aren’t in collision with the object(s) that that you want to add, pick a random Node, add an object at the Node.

This uses local variables but could use scene variables if you prefer.

You can add the Node objects through the editor or with events or external layouts or the rectangular flood fill extension.

In my example 50 is the X and Y starting position and 64 is the grid size. The repeat events create a 5x5 grid.

You can use a group object list instead for the Tile object that I used and it would pick the Nodes without any of the objects in the list.

An alternate more complex technique would be to use a structure of structures that had X and Y children. That would require an understanding of structures.

petlimpet: It’s not just spawning an object to a random grid position. The OP wants to spawn to a random empty spot on the grid.

Before anyone suggest a brute force approach. You could pick random locations until it finds a location that’s empty but that’s unpredictable and would require more attempts as more objects were added. It could guess an empty space on the 1st attempt or not until the 100th guess. If there was only 1 space left, it could take awhile before that spot was randomly chosen.

Sorry Keith…didn’t read it through…will get rid of that one!

1 Like