我按照 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;
}
}
}
}