简体   繁体   中英

In C# XNA, how do I display my sprites in random places every time the game loads?

I am having trouble with loading my sprites in random places when the game loads, I have currently got them set in specific positions as shown below:

BlackBallRectangle = new Rectangle(150, 300, 25,25);
BlackBallRectangle2 = new Rectangle(500, 400, 25, 25);
BlueBallRectangle = new Rectangle(500, 150, 25, 25);
GreenBallRectangle = new Rectangle(100, 500, 25, 25);
OrangeBallRectangle = new Rectangle(180, 200, 25, 25);
PinkBallRectangle = new Rectangle(260, 260, 25, 25);
RedBallRectangle = new Rectangle(300, 450, 25, 25);
YellowBallRectangle = new Rectangle(550, 300, 25, 25);

I have created a Random Randome = new Random(); but I am unsure if this is needed. Any help would be great as I need them to be in random places for each level

You have to make use of Random .

Random Randome = new Random();
BlackBallRectangle = new Rectangle(Randome.Next(0, 150), Randome.Next(0, 300), 25, 25);
BlackBallRectangle2 = new Rectangle(Randome.Next(0, 500), Randome.Next(0, 400), 25, 25);
// the same thing for others

This Randome.Next(0, 150) generate a value between 0 and 150 . You can replace minValue and maxValue to match your needs.

Note: If you make same instance of the class with the Random property, I recommend you to mark it as static , otherwise there are chances to generate for same clases type same set of values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM