Public Group

# xna random number in 2d

This topic is 2095 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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

##### Share on other sites

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.

##### Share on other sites

Random r = new Random(DateTime.Now.Millisecond);
Vector2 randomVector = new Vector2(r.Next(0, SCREENWIDTH), r.Next(0, SCREENHEIGHT));


##### Share on other sites
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.

##### Share on other sites

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();
}


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.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 28
• 16
• 10
• 10
• 11
• ### Forum Statistics

• Total Topics
634111
• Total Posts
3015572
×