Reputation: 15
I am creating a game in XNA and wish to have multiple sprites drawn at random positions. The problem I have is that the sprites appear to redraw at a new position each time the Draw() function is called. This is making them flash around the screen randomly. I want them to draw once and stay in that position.
I have created a List to hold the sprites:
List<Texture2D> kiwis = new List<Texture2D>();
Then in the LoadContent() function I have added sprites to the list:
kiwi = Content.Load<Texture2D>("Sprites/kiwi");
if (kiwis.Count() < 4)
{
kiwis.Add(kiwi);
}
Then in Draw(), I have:
foreach (Texture2D kiwi in kiwis)
{
spriteBatch.Draw(kiwi, kiwiPosition, Color.White);
}
This is the kiwiPosition Vector2:
kiwiPosition = new Vector2(random.Next(30, 610), random.Next(30, 450));
Thanks in advance :)
Upvotes: 0
Views: 1835
Reputation: 43300
In addition to my comment, insert and replace with the following as required
public class Fruit
{
private Vector2 pos;
public Vector2 Position
{
get{return pos;}
set{pos = value;}
}
public Texture2D Texture {get;set;}
public Fruit(Texture2D tex, Vector2 pos)
{
Position = pos;
Texture = tex;
}
}
List<Fruit> kiwis = new List<Fruit>();
kiwi = Content.Load<Texture2D>("Sprites/kiwi");
if (kiwis.Count() < 4)
{
kiwis.Add(new Kiwi(kiwiTex,
new Vector2(random.Next(30, 610), random.Next(30, 450)));
}
foreach (Fruit kiwi in kiwis)
{
spriteBatch.Draw(kiwi.Texture, kiwi.Position, Color.White);
}
The difference between this approach and your current approach, is that your position will only get set once instead of once per frame
Upvotes: 2