Im trying to create a random number within the bounds of my screen and when the player comes in contact with the object, a new random object will appear on the screen. I can't for the life of me figure out how to create a random Vector2 value tho -.- I want the random number to be generated within a method so I can also create a bounding box within the method for collision purposes
xna random number in 2d
I don't know what's tripping you up, the fact that you have 2 random number to generate, or the conversion from int to float?
This thread show you how to use the random class, and this one for the conversion.
Random r = new Random(DateTime.Now.Millisecond);
Vector2 randomVector = new Vector2(r.Next(0, SCREENWIDTH), r.Next(0, SCREENHEIGHT));
Random r = new Random(DateTime.Now.Millisecond); Vector2 randomVector = new Vector2(r.Next(0, SCREENWIDTH), r.Next(0, SCREENHEIGHT));
I would make two notes here:
1) The default constructor for Random already handles seeding by time; you don't need to do it yourself.
2) Because of #1, you want to reuse the same Random instance as much as possible. For example if you ran this:
for (int i = 0; i < 100; i++)
{
Random r = new Random();
someVectorList.Add(new Vector2(r.Next(0, ScreenWidth), r.Next(0, ScreenHeight));
}
You would find that quite a few (if not all) vectors would have the exact same values. This is because each new random instance would have the same seed and therefore generate the same sequence of numbers.
So in general you want to create one Random per method at the least, but most people generally just make one Random instance as a public static member on some type and reuse that everywhere.