jeudi 5 février 2015

XNA - Handling multiple objects (classes) for a star backgound [duplicate]


This question already has an answer here:




I recently 'migated' to XNA, and to practice, i'm making a space shooter game (classic oldschool yea).


I'm making a 'star-scrolling background' where the stars moves down (so much fx).


Each 'star' is a class which have some variables in it obviously, here is the class (comments are here to make it clearer (i hope so)):



// - "STAR" CLASS
public class Star
{
// - Declare these bad guys, in case i want to use them.
public ContentManager content;
public SpriteBatch spriteBatch;
public GraphicsDeviceManager graphics;

public Texture2D texture;
public Vector2 position;
public Vector2 velocity;

}


Let's say i'm working in the main 'Game.cs' class. When a star is created, it is stored in a List of stars, called 'listStar'



// - "GAME" CLASS
public List<Star> listStar = new List<Star>();


So far so good, i can create my stars:



// - "GAME" CLASS
protected override void Initialize()
{


for (int i = 0; i < 100; i++) //Let's say we want 100 stars :D
{
Random rnd = new Random();
int rndX = rnd.Next(5, roomWidth - 5); //room(Width|Height) is just the graphics.PreferredBackBuffer(Width|Height)
int rndY = rnd.Next(0, roomHeight - 5);
Star star = new Star();

//Let's pass these in case we want to use them.
star.content = Content;
star.spriteBatch = spriteBatch;
star.graphics = graphics;

//Initialize the 'real' stuff
star.texture = Content.Load<Texture2D>("star"); //White pixel as png (Yes, i could create it with code, but this is for the example.
star.position = new Vector2(rndX, rndY);
star.velocity = new Vector2(0, 3);

listStar.Add(star);
}


base.Initialize();
}


In the Update() method:



foreach (Star star in listStar)
{
star.position += star.velocity;
if (star.position.Y > roomHeight) star.position.Y = 0;
}


The Draw() method:



spriteBatch.Begin();
foreach (Star star in listStar)
{
spriteBatch.Draw(star.texture, star.position, Color.White);
}
spriteBatch.End();


Well, you will say to me that's fine ?? And i would say no, unfortunately.


Here is a screen of what is happening


http://ift.tt/1Fb96NB (Need rep for embedding, sorry :c)


With the debug window and watching the listStar list, the stars are overlapping.


My first guess was that it could be an issue with the random seed, not sure about that. What do you think ?


Sorry if the post may seems heavy but i want it to be clear and fix this issue if we can :D


Thanks :)


EDIT: This seems that only the first star in listStar (listStar[0]) has the "unique" position, the other white pixel in the black screen is the other 99 stars overlapping.





Aucun commentaire:

Enregistrer un commentaire