Display multiple sprites [Solved]

How to display multiple sprites by using a sprite class?

Page 1 of 1

9 Replies - 15862 Views - Last Post: 14 March 2010 - 08:50 AM

#1 Hellbroth  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 190
  • Joined: 15-August 09

Display multiple sprites [Solved]

Posted 11 March 2010 - 03:28 PM

Hello everyone till now i have a sprite class that i can create an object sprite and just draw it.
But i can't find a way on display multiple sprites without manualy creating new sprite objects everytime.


Here is my sprite class :

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace WindowsGame33
{
    class Sprite
    {
        public Texture2D spriteTexture;
        public Vector2 spritePosition;
        public Point frameSize = new Point(46, 46);

        public void LoadContent(ContentManager theContentManager, string theAssetName)
        {
            spriteTexture = theContentManager.Load<Texture2D>(theAssetName);
        }

        public void Draw(SpriteBatch theSpriteBatch)
        {
            theSpriteBatch.Draw(spriteTexture, spritePosition, new Rectangle(0,0,
                frameSize.X,
                frameSize.Y),
                Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
        }
    }
}



I tried to use arrays but it didn't work. I have seen many people use the List<> thing but i don't know how to use it and couldn't find any tutorial about it.

Any ideas anyone?

This post has been edited by Hellbroth: 13 March 2010 - 05:39 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Display multiple sprites [Solved]

#2 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 945
  • View blog
  • Posts: 6,342
  • Joined: 18-October 08

Re: Display multiple sprites [Solved]

Posted 11 March 2010 - 07:41 PM

Check out my Asteroids tutorials here on DIC. The show how to create and track multiple asteroids and bullets using a List<T>.

Also, I have a tutorial on the basics of List<T> in the C# section.

Tutorial on List<T>
http://www.dreaminco...wtopic98806.htm

This post has been edited by SixOfEleven: 11 March 2010 - 07:41 PM

Was This Post Helpful? 0
  • +
  • -

#3 Hellbroth  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 190
  • Joined: 15-August 09

Re: Display multiple sprites [Solved]

Posted 13 March 2010 - 01:12 PM

View PostSixOfEleven, on 11 March 2010 - 06:41 PM, said:

Check out my Asteroids tutorials here on DIC. The show how to create and track multiple asteroids and bullets using a List<T>.

Also, I have a tutorial on the basics of List<T> in the C# section.

Tutorial on List<T>
http://www.dreaminco...wtopic98806.htm


I read your tutorial but i am still having a problem :/

so what i should do is

List<Sprite> spriteList = new List<Sprite>();   //that creates my list of sprites



then i want to create 4 sprites so i initialise them with a for loop

protected override void Initialize()
        {
            for (int i = 0; i < 5; i++)
            {
                spriteList.Insert(i, sprite); 
            }


            base.Initialize();
        }




So now i am stucked i can't find a way to load my graphics for each of this sprite objects and how to display them :S

The only thing i am trying to do is display for example 4 sprites in my screen without having to create them manualy. I thought i won't be hard and i should just use the for loop but now i am totaly confused.

This post has been edited by Hellbroth: 13 March 2010 - 01:13 PM

Was This Post Helpful? 0
  • +
  • -

#4 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Display multiple sprites [Solved]

Posted 13 March 2010 - 03:17 PM

The list simply holds a collection of sprites. You still need to make them, and handle the methods yourself. If you want to create a list from a single sprite, you can do something like this:

In the Game1 class (or whatever)...
// Create a list to store the sprites.
List<sprite> sprites = new List<Sprite>();



This goes in LoadContent method, after sprite has been created and loaded...
// Add a sprite to the list.
// This can also be put inside a for-loop to create several sprites.
sprites.Add(sprite);



Place this code in the Draw method...
foreach(Sprite sprite in sprites)
{
    spriteBatch.Begin();
    sprite.Draw(spriteBatch);
    spriteBatch.End();
}



This will fill a list with references to the already created Sprite named sprite, which has already been loaded, and then draws each sprite in the list to the screen.
Was This Post Helpful? 0
  • +
  • -

#5 Hellbroth  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 190
  • Joined: 15-August 09

Re: Display multiple sprites [Solved]

Posted 13 March 2010 - 04:47 PM

That didn't help me at all.

I can create single object and display them manualy but i want to do it with a loop to create but itself as many as i want.
Was This Post Helpful? 0
  • +
  • -

#6 Hellbroth  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 190
  • Joined: 15-August 09

Re: Display multiple sprites [Solved]

Posted 13 March 2010 - 05:37 PM

At last i did it :D thanx to XNA Creators i knew that array was what i needed.
But thanx for your time guys :)

Here is the solution

GameObject Class
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;

namespace WindowsGame37
{
    class GameObject
    {
        public Texture2D sprite;
        public Vector2 position;
        public float rotation;
        public Vector2 center;
        public Vector2 velocity;
        public bool alive;
        public Point currentFrame = new Point(0, 6);
        public Point sheetSize = new Point(3, 21);
        public Point frameSize = new Point(32,32);

        public GameObject(Texture2D loadedTexture)
        {
            rotation = 0.0f;
            position = Vector2.Zero;
            sprite = loadedTexture;
            center = new Vector2(sprite.Width / 2, sprite.Height / 2);
            velocity = Vector2.Zero;
            alive = false;
            currentFrame = new Point(0, 6);
            sheetSize = new Point(3, 21);
            frameSize = new Point(48,48);
        }
    }
}



Game1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace WindowsGame37
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        GameObject[] enemies;
        const int maxEnemies = 3;
        const float maxEnemyHeight = 0.1f;
        const float minEnemyHeight = 0.5f;
        const float maxEnemyVelocity = 5.0f;
        const float minEnemyVelocity = 1.0f;
        Random random = new Random();
        Rectangle viewportRect;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 100);
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            enemies = new GameObject[maxEnemies];
            for (int i = 0; i < maxEnemies; i++)
            {
                enemies[i] = new GameObject(Content.Load<Texture2D>("enemy"));
            }
            viewportRect = new Rectangle(0, 0,
                graphics.GraphicsDevice.Viewport.Width,
                graphics.GraphicsDevice.Viewport.Height);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();


            UpdateEnemies();

            base.Update(gameTime);
        }

        public void UpdateEnemies()
        {
            foreach (GameObject enemy in enemies)
            {
                if (enemy.alive)
                {
                    enemy.position += enemy.velocity;
                    enemy.currentFrame.X++;
                    if (enemy.currentFrame.X >= enemy.sheetSize.X)
                        enemy.currentFrame.X = 0;
                    if (!viewportRect.Contains(new Point(
                        (int)enemy.position.X,
                        (int)enemy.position.Y)))
                    {
                        enemy.alive = false;
                    }
                }
                else
                {
                    enemy.alive = true;
                    enemy.position = new Vector2(
                        viewportRect.Right,
                        150);
                    enemy.velocity = new Vector2(
                        MathHelper.Lerp(
                        -minEnemyVelocity,
                        -maxEnemyVelocity,
                        (float)random.NextDouble()), 0);
                }

            }
        }


        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();
            foreach (GameObject enemy in enemies)
            {
                if (enemy.alive)
                {
                    spriteBatch.Draw(enemy.sprite, enemy.position, new Rectangle(enemy.currentFrame.X * enemy.frameSize.X,
                        enemy.currentFrame.Y * enemy.frameSize.Y,
                        enemy.frameSize.X,
                        enemy.frameSize.Y),
                        Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
                       
                        
                        
                }
            }
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}



And here is the picture

Posted Image

So now i can produce multiple enemies and they can animate too :D i am so happy now.
Was This Post Helpful? 0
  • +
  • -

#7 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Display multiple sprites [Solved]

Posted 13 March 2010 - 07:11 PM

Oh, I misread you post. I thought you wanted to create several sprites from a single instance.

Anyway, what SixOfEleven shows how to do in his tutorials, using lists, is essentially the same thing as what you're doing now.

Personally, I prefer lists over arrays in most situations because of the added functionality (and ease of use). Later, you might even look into creating your own type of collections.
Was This Post Helpful? 0
  • +
  • -

#8 Hellbroth  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 190
  • Joined: 15-August 09

Re: Display multiple sprites [Solved]

Posted 13 March 2010 - 08:13 PM

View PostlesPaul456, on 13 March 2010 - 06:11 PM, said:

Oh, I misread you post. I thought you wanted to create several sprites from a single instance.

Anyway, what SixOfEleven shows how to do in his tutorials, using lists, is essentially the same thing as what you're doing now.

Personally, I prefer lists over arrays in most situations because of the added functionality (and ease of use). Later, you might even look into creating your own type of collections.



Yes you are completely right about the list and i am aware of that but for now i just couldn't understand
how to do it with list.
Finaly now i have several enemies on my game the only think left is learn about AI which i have no clue where i can find ai for fighting games or games like metal slug :/
Was This Post Helpful? 0
  • +
  • -

#9 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 945
  • View blog
  • Posts: 6,342
  • Joined: 18-October 08

Re: Display multiple sprites [Solved]

Posted 13 March 2010 - 11:08 PM

Your topic says solved, but did you look at the asteroids tutorials I did? They show how to create multiple objects in the game using List<T>. There is a rather basic sprite class that I use for the asteroids in the game. The asteroids can have many different Texture2D for the images. That is basically what you are trying to accomplish here. I show how to load all of the Texture2D into an array and create the asteroids using the array and tracking them in a List<T>. I recommend that you check them out.

Part 1: http://www.dreaminco...topic100575.htm
Part 2: http://www.dreaminco...topic101073.htm
Part 3: http://www.dreaminco...topic101358.htm
Part 4: http://www.dreaminco...topic102997.htm
Was This Post Helpful? 0
  • +
  • -

#10 Hellbroth  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 190
  • Joined: 15-August 09

Re: Display multiple sprites [Solved]

Posted 14 March 2010 - 08:50 AM

Sure why not :) to be fair i only read the first one i didn't notice there was more than one.
Sorry i have many things in my mind i will give it a look as soon as i can.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1