下面的代码是生成障碍物的随机位置。障碍物从右向左移动,因此我使用其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;
}
}
答案 0 :(得分: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);
}
答案 1 :(得分:2)
为什么不把障碍放在进步中? 我的意思是,你随机化第一个障碍物的位置,然后你添加一个默认的偏移量,然后为你的障碍物随机化另一个位置。通过这种方式,您可以确保在不检查先前的障碍物的情况下,您不会在同一位置放置任何障碍物。