Question

Below code is to generate the random positions for the obstacles. Obstacles are moving from right to left,so i am using its x coordinate to move it in left direction. When obstacles reaches left side of screen it again placed at some random position. But here problem is that sometimes the obstacles are placed at same position or they are too close.

 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;
    } 
 }
Était-ce utile?

La solution

Use the distance formula to see if the two objects are to close to each other.

Here is an example, using an Obstacle class to simplify things.

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

Autres conseils

Why don't you place your obstacles in progression?
I mean, you randomize the position of the first obstacle, then you add a default offset and then randomize another position for your obstacle. In this way you are sure that you won't have any obstacle placed at the same position, without checking previous obstacles.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top