我认为最好用一些伪代码解释一下:
std::vector<Yes> objs;
//The Yes Class constructor: Yes(x,y)
//Let's imagine I instantiated this vector with one object somewhere appropriately
void inSomeFunction()
{
for(int i = 0; i < 20; ++i)
{
int randX = rand() % mapWidth;
int randY = rand() % mapHeight;
for(int j = 0; j < objs.size(); ++j)
{
if(randX > x + threshold, for all objects in my vector && randY > y + threshold, for all objects in my vector)
{
objs.push_back(Yes(randX,randY));
}
}
}
}
因此,我有一个窗口,其尺寸为mapWidth和mapHeight,我基本上只是在尝试制作20个在xy平面上彼此不重叠的对象。
我还想确保randX和randY不重叠,而且与所有其他现有对象也相距某个阈值距离。假设我的阈值= 20,那么我想确保randX和randY不在向量中任何/所有现有对象周围的半径为20的圆中。
为了清楚起见,示例:第一个Yes对象位于(x,y)=(10,20)并且我的阈值= 20,我想创建第二个对象,以randX和randY作为参数,并将其推入我的向量中;但是,我要确保点(randX,randY)不在半径20的圆中,并以(10,20)为中心,这是我的第一个对象的坐标。该程序既可以生成另一个随机(x,y),也可以仅生成randX和randY来满足我想要的条件,但是当我创建更多对象时,我需要它继续检查向量中的所有对象。
我想知道如何做到这一点?同样为了更清晰起见,它适用于游戏。我正在尝试在2D地图中生成多个建筑物,但我显然不希望它们重叠或彼此靠近。我将如何实现这一目标?
我将其分解为较小的功能。
像这样:
bool overlaps(const Yes& thing, int x, int y)
{
// See if (x, y) overlaps 'thing' in whichever way is appropriate.
}
bool overlaps_any(const std::vector<Yes>& things, int x, int y)
{
for (const Yes& thing : things)
{
if (overlaps(thing, x, y))
{
return true;
}
}
return false;
}
void inSomeFunction(std::vector<Yes>& objs)
{
for(int i = 0; i < 20; ++i)
{
int x = 0;
int y = 0;
do {
x = rand() % mapWidth;
y = rand() % mapHeight;
} while (overlaps_any(objs, x, y));
objs.push_back(Yes(x,y));
}
}
可能有更有效的方法,但是由于您只生成一次地图,因此我现在不必担心效率。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句