xna random number in 2d

Started by
3 comments, last by NickGravelyn 10 years, 11 months ago

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

If you see a post from me, you can safely assume its C# and XNA :)

Advertisement

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));
why are you trying to create a bounding box within the method that your creating a new random object? Your object class should already be able to create a bounding box for itself using the vector location that you provide for it. If you use the code code above provided by Andy474 and pass that into your call for a 'New Object' it should have it's bounding box otherwise the question your asking is not what your looking for.


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.

This topic is closed to new replies.

Advertisement