Reputation: 27
I am currently working on a platforming game and I am trying to draw 40 items in one screenstate, but I don't want to hard code them all. Here's what I've tried so far:
Sprite class:
class Sprite
{
//texture, position and color
public Texture2D texture;
public Vector2 position;
public Color color;
}
Definiton:
Sprite levelboxbg;
int LevelBoxX = 20;
Loading:
levelboxbg = new Sprite();
levelboxbg.texture = Content.Load<Texture2D>("LevelBoxBeta");
levelboxbg.position = new Vector2(0, 0);
levelboxbg.color = Color.White;
Execution:
public void DrawLevelBoxes(SpriteBatch spriteBatch)
{
for (int i = 0; i < 10; i++)
{
spriteBatch.Draw(levelboxbg.texture, new Vector2(LevelBoxX + 20 ,0), levelboxbg.color);
LevelBoxX += 20;
}
}
I then call the method in my draw function.
Visual studio has given me 0 errors for this and it will run; however, when I get to the screen where it's supposed to draw the boxes, it draws them all but only for a fraction of a second, then they dissipate.
Any help is greatly appreciated, thank you for taking the time to read this.
Upvotes: 1
Views: 699
Reputation: 1631
Your LevelBoxX goes to infinity, so the boxes are running out of the screen pretty fast. You can reset LevelBoxX just before the for-loop like so:
public void DrawLevelBoxes(SpriteBatch spriteBatch)
{
LevelBoxX = 20;
for (int i = 0; i < 10; i++)
{
spriteBatch.Draw(levelboxbg.texture, new Vector2(LevelBoxX + 20 ,0), levelboxbg.color);
LevelBoxX += 20;
}
}
Or just declare a local variable:
public void DrawLevelBoxes(SpriteBatch spriteBatch)
{
int counter = 20;
for (int i = 0; i < 10; i++)
{
spriteBatch.Draw(levelboxbg.texture, new Vector2(counter + 20 ,0), levelboxbg.color);
counter += 20;
}
}
Upvotes: 4