I'm starting a 2D game where I want all the letters A-Z displayed in a random position and, then, the player collects them all in the correct order. I need to randomly instantiate the letters without overlapping. I use C#.
Randomly pick a box that hasn't been chosen yet, then randomly place the item within that grid space. The space between the boxes is enough so that items placed on the edge of a box doesn't intersect with an item placed on the edge of an adjacent box. This can be implemented pretty simply with a list and a bit of math.
Try, and try again
Randomly place the items, after each placement, check for overlap. If there's an overlap, remove the item and choose a new random location until you've found one that doesn't overlap.
Try, and move
Randomly place the items, after each placement, check for overlap. If there's an overlap, move the new item away from the existing item until it fits or goes out of bounds. If it goes out of bounds, try placing it again.
Randomly generate the objects with physics and gravity. Allowing them to drop into a container, letting the physics system keep track of keeping them separated based on their colliders.
Uniform and wiggle
Place all the items uniformly on a grid, in random order, then change their positions by a small random amount, ensuring that doing so doesn't cause them to overlap.
It's not the cleanest method, but an easy starting point would be to make a
char array filled with all the letter, then randomize the order. Create an array of
Vector3 points that can contain the letters (obviously at least 26 points). Then instantiate an object containing the letter from the next
char value randomly to one of the
Vector3 points. That might be an object that is given the next
char value as a
char which works with a script on the object to display that letter.