Trouble choosing a random spawn location in 2D tile based platformer

Hi everyone,

I'm in the middle of creating a 2D tile based game. Just a minor problem I am encountering: I have a CSV file which is read into an array for the level map - this all works fine. I am have a second CSV file with the same number of rows/columns which holds numbers to represent spawn points for weapon power ups. I want the power ups to randomly appear, but only at one of a few specific locations, basically at one of the tiles where the value is '2'.

The problem is I am trying to randomly pick a tile by using a do ... while loop, which is proving to be very costing, slowing the game to a halt until the loop finds a valid tile. I'm not very good at explaining this but hopefully you understand what I mean, anyway heres the code (bear in mind this is my first time programming a game so my code may be somewhat novice :-):

From the top:

//represents the number of rows and columns in the csv file/map
private static int MapTileRow = 20;

private static int MapTileColumn = 26;


Later in the code:

bool SpawnPointFound = false;
int x, y;

do
{
Random RandomTile = new Random();
x = RandomTile.Next(MapTileRow);
y = RandomTile.Next(MapTileColumn);

if (WeaponSpawnArray[x, y] == 2)
{ SpawnPointFound = true;}
}
while (!SpawnPointFound);


Are there any more efficient ways of doing this I was thinking perhaps of, when reading in the CSV file, storing the co-ordinates of each '2' tile in another array, and then just picking one of these coordinates from the array at random, but I couldn't think of a way to implement it.

Many thanks in advance for any help.



Answer this question

Trouble choosing a random spawn location in 2D tile based platformer

  • Airmax

    Never mind, I found that putting the Random RandomTile = new Random(); outside the do loop stopped the pause. My bad! Still, if there are any more efficient ways to do this I'd be very willing to hear.
  • 13thGhost

    Why not just keep a HashTable of spawn points and generate the random number based on the number of elements in the HashTable

            private Hashtable spawnPoints;    //filled elsewhere
            private Random rnd = new Random();

            private Vector2 GetSpawnPoint()
            {
                Vector2 pt;
                
                int index = rnd.Next(0, spawnPoints.Count);

                pt = new Vector2(((Vector2)spawnPoints[index]).X, ((Vector2)spawnPoints[index]).Y);

                return pt;
            }

    Using a Hashtable would allow you to do lookups using the ContainsValue method. You could use a List<Vector2> object as well if you don't need to do lookups.



  • Trouble choosing a random spawn location in 2D tile based platformer