Search code examples
randomxnaspritetexture2d

How can I draw 50 of the same sprite in random locations in XNA?


I am currently working on a school project and missed a class where the instructor explained how to do this without a massive amount of code.

Here is the assignment:

Create an XNA application shows 50 animated sprites accelerating downward. When a sprite hits the bottom of the window, make it bounce. Spawn each sprite in a random location such that the sprite is always completely in the window. Limit the Y component of the random location to be between 0 and 300. Lastly, make it so the sprites reset to their original location upon a press of the space bar.

This is a link to an example image, rep isn't high enough for inserting images

http://hypergrade.com/grader/file_download.php?id=132

I have a single sprite drawn and animated, I just need some guidance on randomly generating locations for the same Texture2D.


Solution

  • you should use Random class.

     // Make one instance of random, the seed is the milliseconds, other way random always returns the same sequence of random numbers.
     static readonly Random rnd = new Random(DateTime.Nom.Milliseconds);
    
     List<Sprite> Sprites = new List<Sprite>(50); 
     public void Update()
     {
          //Add new sprites with a 90% or probability 
          if (Sprites.Count<50 && rnd.Next(100) > 90)
          {
              Sprite sprite = new Sprite();
    
              // This X calculation makes the sprite not to get out of the screen at both sides
              sprite.Pos.X = (float) ( (0.1f + 0.8f * rnd.NextDouble()) * GraphicsDevice.Viewport.Width);
              sprite.Pos.Y = (float) ( rnd.NextDouble() * 300 );
    
              Sprites.Add(Sprite);
          }
     }
    

    Of course de Sprite class depends on you.. :)