質問

Currently making a simple game in C# and I have my object appearing in the middle of the screen, now I have made a list for that object but was wondering how do I make the object appear like 10 times randomly on the screen? I am guessing a for each loop of some kind?

object1 = new List<Gem>();
object2 = new List<Gem>();

Above is just where I have made a list for that class where the object is stored. So again just trying to figure out how to make this object appear in random positions on the screen x10.

役に立ちましたか?

解決

Assuming your Gem class like:

class Gem
{
  public int X {get;set;}     
  public int Y {get;set;}
  // information about color/type/whatever
}

You can do something like:

//make sure to have single instance of `Random` for class/whole program
Random rnd = new Random(); 
var gems = Enumerable.Range(1,10) // 10 items
  .Select(i => new Gem {  // create new Gem
     X = rnd.Next(1, 100), // set position to random value 1-100, adjust to 
     Y = rnd.Next(1, 100), // desired width/height ranges
  })
  .ToList();// convert enumerable to list.

他のヒント

so lets say I have an IMAGE object that can be rendered to the screen with an XNA style call:

 renderer.draw(IMAGE,COORD,COLOR);

use:

for(int x = 0; x < 10; x++)
{
      renderer.draw(IMAGE,new COORD(rand.Next(IMAGE.WIDTH,SCREEN.SIZE.WIDTH - IMAGE.width),rand.Next(IMAGE.HEIGHT,SCREEN.SIZE.HEIGHT - IMAGE.HEIGHT)),COLOR);
}

you only need one instance of image but maybe a list of coordinates.

your logic object 'GEM' should not contain the image itself but be used to tell the render where to draw your one instance of the gem image.

if you can produce some of your rendering code and some of the GEM code I could help you a lot more

and the funky math will keep your gem from rendering outside the screen

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top