Im totally new at this and have a question. I worked with an exercise in school and at home but I can't figure out how to do it.
The thing is I want to draw a single sprite at 10 random positions on the screen without using a special sprite class. My problem is that after they are drawn they vanish again.
Solved it, thanks for all the help!
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D turtleTexture;
int counter = 0;
Random randomera = new Random();
int x;
int y;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
/// <summary>
/// </summary>
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
turtleTexture = Content.Load<Texture2D>(@"Images/turtle_50x38");
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
/*
if(counter < 10)
{
x = randomera.Next(600);
y = randomera.Next(400);
counter++;
}
*/
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
if (counter < 10)
{
for (int i = 0; i < 10; i++)
{
spriteBatch.Draw(turtleTexture, new Vector2(randomera.Next(600), randomera.Next(400)),
Color.Black);
counter++;
}
}
spriteBatch.End();
base.Draw(gameTime);
}
}
}
If you want to have your sprites on the same random positions all the time and still clearing your viewport (for example, you may want to render other content) you may just reset the random seed every frame to the same value:
protected override void Draw(GameTime gameTime)
{
randomera = new Random(seed);
GraphicsDevice.Clear(Color.White);
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
if (counter < 10)
{
for (int i = 0; i < 10; i++)
{
spriteBatch.Draw(turtleTexture, new Vector2(randomera.Next(600), randomera.Next(400)),
Color.Black);
counter++;
}
}
spriteBatch.End();
base.Draw(gameTime);
}
where the seed should be randomly generated in your Initialize()
method, and not be changed after that.
You may also just initialize list with predefined coords:
List<Vector2> coords = Enumerable.Range(0, 10).Select(i => new Vector2(randomera.Next(600), randomera.Next(400)).ToList();
and use this list in your drawing routine:
for (int i = 0; i < 10; i++)
{
spriteBatch.Draw(turtleTexture, coords[i],
Color.Black);
}
You are calling Clear
in your draw method
GraphicsDevice.Clear(Color.White);
This will clear the screen.
Remove this line and it will keep the previous drawn stuff.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With