下面的函数 FindEmptySpace() 会在一个区域中查找随机的空白空间。它通过在该区域内选择随机坐标,检查那里是否已经存在任何东西,然后循环这个过程,直到成功找到一个没有任何东西的位置,然后返回它来实现这一点。
它工作得很好,但我刚刚意识到,如果没有可用空间,这可能会陷入永无休止的循环。但是该函数如何知道何时没有可用的空白空间并返回错误?
static function FindEmptySpace ()
{
var sphereRadius = 2.0;
while ( true )
{
var spawnPos = RandomPoint(); // Get random position within level bounds
if ( !Physics.CheckSphere( spawnPos, sphereRadius ) ) // Check if area is empty
break;
}
return spawnPos; // Return empty location
}
最佳答案
我根据Renan的建议重写了它,现在循环到边界的边缘,如果我们再次到达起点,我们还没有找到任何东西并返回null。
未经测试,但我认为这是一个很好的解决方案。
static function CheckForEmptySpace ()
{
var bounds = GameController.levelAttributes.bounds;
var sphereRadius = 2.0;
var startingPos = Vector3( Random.Range(bounds.xMin, bounds.xMax), 0, Random.Range(bounds.yMin, bounds.yMax) );
// Loop, until empty adjacent space is found
var spawnPos = startingPos;
while ( true )
{
if ( !Physics.CheckSphere( spawnPos, sphereRadius ) ) // Check if area is empty
return spawnPos; // Return location
else
{
// Not empty, so gradually move position down. If we hit the boundary edge, move and start again from the opposite edge.
var shiftAmount = 2;
spawnPos.z -= shiftAmount;
if ( spawnPos.z < bounds.yMin )
{
spawnPos.z = bounds.yMax;
spawnPos.x += shiftAmount;
if ( spawnPos.x > bounds.xMax )
spawnPos.x = bounds.xMin;
}
// If we reach back to a close radius of the starting point, then we didn't find any empty spots
var proximity = (spawnPos - startingPos).sqrMagnitude;
var range = shiftAmount-0.1; // Slight 0.1 buffer so it ignores our initial proximity to the start point
if ( proximity < range*range ) // Square the range
{
Debug.Log( "An empty location could not be found" );
return null;
}
}
}
}
关于unity-game-engine - 用于在区域中查找空白空间的函数,如果没有找到,如何返回错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18874950/