简体   繁体   中英

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 Y to make models sit on the heightmap. Any thoughts?

在循环外部创建随机变量,仅在内部使用next,还对初始化程序使用随机种子,例如:

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

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