VG:Random Fun

From MyProjectFun
Jump to: navigation, search

Randomness makes our games more fun, so here's a few tips on adding random.

Let's say you want to choose between a five options in a random way. Sadly, we can't just give our computer some dice or say "Hey, pick one of these." Thus, we need to use random.

If we want to choose between five options (i.e. Spawning one of five power-ups or choosing one of five targets), then we can do something that looks like the following. I'm going to assume I want to choose some sprite (to either shoot at or copy).

// Set up a variable to store the sprite we choose
Sprite RndSprite;
// Get a random number between 1 and 5
int choice = This.Game.RandInt(1, 6);
// If we rolled a 1
if ( choice == 1 )
  // Choose our first sprite
  RndSprite = This.Game.FindSprite( "Sprite1" );
// If we rolled a 2
if ( choice == 2 )
  // Choose our second sprite
  RndSprite = This.Game.FindSprite( "Sprite2" );

And so on. After we decide which sprite RndSprite is, then we could copy it, or we could use This.Follow( RndSprite ); to have a sprite target that RndSprite.

This had a slight error in it in my original post. To get a random number between 1 and 5, we need to use This.Game.RandInt(1, 6); since the second parameter is a number that the generated number must be less than.

The original post has been edited to fix this issue.

Another problem arises! If we're destroying our random sprites, then we might not be able to find them later on. To fix this, we need to add some protection when we use our RndSprite.

Instead of just

// Follow our random sprite
This.Sprite.Follow( RndSprite , 5.0f , 0.0f );

We want to do something like

// If our RndSprite exists
if ( RndSprite != null )
  // Follow it
  This.Sprite.Follow( RndSprite , 5.0f , 0.0f );
// Otherwise
  // Nowhere to go, so delete me
Personal tools
Game Design
Multimedia Production
VG Programming