开发者

Odd draw behavior

In my xna game, I have a method to create the treasure chests in random locations on the map. The thing is, it draws them all in the same place. The random doesn't generate unique random numbers for the v3 points. However, if I debug and step through the method, it works perfectly.

void CreateTreasure()
    {
        for (int i = 0; i < 20; i++)
        {
            Random random = new Random();
            Treasure t = new Treasure(new Vector3((float)random.Next(0, 600), 0, (float)random.Next(600)));
            treasureList.Add(t);
        }
    }

and in the draw I loop through

foreach (Treasure t in treasureList)
        {
            DrawModel(treasure, Matrix.Identity * Matrix.CreateScale(0.02f) * Matrix.CreateTranslation(t.Position));
            PositionOnMap(ref t.Position);
        }

PositionOnMap just takes the position and adjusts the 开发者_StackOverflow中文版Y to make models sit on the heightmap. Any thoughts?


create the random outside your loop and only use next inside, also use random seed for the initializer like:

var random = new Random(Guid.NewGuid().GetHashCode());


You need to move Random outside of your loop. Right now, it will create a new Random instance each time. Since the default seed is time based, if this occurs quickly, the first call to Next() will always return the same value. Try this:

void CreateTreasure()
{
    // Just move this outside, so each .Next call is on the same instance...
    Random random = new Random();
    for (int i = 0; i < 20; i++)
    {
        Treasure t = new Treasure(new Vector3((float)random.Next(0, 600), 0, (float)random.Next(600)));
        treasureList.Add(t);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜