• Advertisement
Sign in to follow this  

xna random number in 2d

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
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 this post


Link to post
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();
   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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement