Good Design

Some Recent Thoughts

In grid-based games, effective object placement is key to ensuring a seamless and engaging experience for players. The SquareSpawner script is designed to dynamically spawn squares in a controlled manner, ensuring no overlap or undesirable patterns, such as 2x2 blocks. It employs a grid-like spawning logic while maintaining resource efficiency through object pooling.

The script begins by calculating the dimensions of the square prefab using its SpriteRenderer. This ensures accurate positioning of the squares in the grid. An initial row of squares is spawned horizontally at the start of the game, providing a structured baseline. To facilitate periodic spawning of squares, the script uses Unity’s InvokeRepeating() method. This allows for continuous spawning at defined intervals, ensuring the grid evolves dynamically as the game progresses. A HashSet tracks occupied positions, ensuring that subsequent squares adhere to placement constraints without overlap.

gif of the terrain generation only

A crucial aspect of this script is its ability to add randomness to square placement without compromising grid integrity. Each new square is spawned in one of four random directions—left, right, up, or down—from the last spawned square. The GetRandomDirection() method handles this logic, ensuring variability. Before placing a square, the script validates the chosen position using the IsValidPosition() method. This validation process ensures:

The position is not already occupied.

Placing a square at the chosen position does not create a 2x2 block, which could disrupt the visual and functional flow of the game.

If no valid position is found after a set number of attempts, the script skips spawning for that cycle, maintaining game stability.

To optimize performance, the script employs an object pooling mechanism. A Queue is used to manage active squares, ensuring that the number of instantiated squares remains within a predefined limit. When the pool size exceeds this limit, the script removes the oldest square from the game world. This is managed in the SpawnSquareAtPosition() method, which handles instantiation, updates the pool, and removes outdated objects. By reusing squares, the pooling system reduces the overhead associated with frequent instantiation and destruction, ensuring smooth performance even on resource-constrained platforms like mobile devices.