0

下面的代码是为障碍物生成随机位置。障碍物从右向左移动,所以我使用它的 x 坐标向左移动。当障碍物到达屏幕左侧时,它再次放置在某个随机位置。但这里的问题是,有时障碍物放置在同一位置或距离太近。

 public void Randomize() 
 {
    int random = rand.Next(1,200);

    switch (random) 
    { 
        case 200:
            if (Texture.crabrect.X < 0)
              Texture.crabrect.X = rand.Next(1000,1500);
            break;
        case 12:
           if (Texture.samosarect.X < 0)
              Texture.samosarect.X = rand.Next(1000, 2000);
            break;
        case 10:
            if (Texture.mirchirect.X < 0)
              Texture.mirchirect.X = rand.Next(1800,3000);
            break;
        case 80:
            if (Texture.mushroomrect.X < 0)
              Texture.mushroomrect.X = rand.Next(1000, 2000);
            break;
        case 195:
            if (Texture.laddoorect.X < 0)
              Texture.laddoorect.X = rand.Next(1000, 2000);
            break;
        case 56:
            if (Texture.stonerect.X < 0)
              Texture.stonerect.X = rand.Next(1000, 2000);
            break;
        case 177:
            if (Texture.cactusrect.X < 0)
              Texture.cactusrect.X = rand.Next(1000, 2000);
            break;
    } 
 }
4

2 回答 2

3

使用距离公式查看两个对象是否彼此靠近。

这是一个示例,使用Obstacle类来简化事情。

public void Randomize()
{
   int random = rand.Next(1,WIDTH);  
   thisObstacle = new Obstacle(); //Blah, make your obstacle.
   thisObstacle.rect = new Rectangle(random, Y,WIDTH, HEIGHT);

   foreach (Obstacle obstacle in obstacles)
   {
        //If less than 100 pixels distance, make the obstacle somewhere else
        if (GetDistance(thisObstacle.rect, obstacle.rect) < 100)
        {
             Randomize();
             return;
        }
   }
   //If we didn't get near an obstacle, place it
        //Do whatever you do
}

private static double GetDistance(Rectangle point1, Rectangle point2)
{
     //Get distance by using the pythagorean theorem
     double a = (double)(point2.X - point1.X);
     double b = (double)(point2.Y - point1.Y);
     return Math.Sqrt(a * a + b * b);
}
于 2013-10-24T17:31:58.397 回答
2

你为什么不把你的障碍放在进步中?
我的意思是,你随机化第一个障碍物的位置,然后添加一个默认偏移量,然后为你的障碍物随机化另一个位置。通过这种方式,您可以确定不会在同一位置放置任何障碍物,而无需检查先前的障碍物。

于 2013-10-24T22:32:55.820 回答