VG:Creating a specific quantity (VG2)

From MyProjectFun
Jump to: navigation, search

In my game, I want to be able to place a sprite by clicking the mouse, and I can place up to ten of them. When I place another after that, I want the oldest sprite to delete so that there are only ten sprites still. How do I do this?

What you want is an array to hold your sprites as you make them, and once it's full, delete the earliest created sprite and replace it with your new one. We'll need three things: An array, a counter, and a constant. The array holds your sprites, the counter tells you how many sprites you've made, and the constant keeps track of the maximum number of sprites you can make.

// Data for sprite arraypublic static int numSprites = 0;public const int maxSprites = 10;public static Sprite[] mySprites = new Sprite[maxSprites];

With those set up, we just have to update our array and counter after we spawn a sprite. Here's about how that works:

// If I click the mouse
if (This.Game.IsMouseTriggered(0))
  // Code to copy and place sprite...
  // Update Sprite array
  // If we have too many sprites
  if (numSprites >= maxSprites)
    // Delete the oldest sprite
    mySprites[numSprites % maxSprites].Delete();
  // Add our new sprite
  mySprites[numSprites % maxSprites] = BulletCopy;
  // Increment our sprite count
Personal tools
Game Design
Multimedia Production
VG Programming