gpt4 book ai didi

unity3d - 找一个区域有空位的函数,没找到怎么报错?

转载 作者:行者123 更新时间:2023-12-02 08:38:30 24 4
gpt4 key购买 nike

下面的函数 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
}

最佳答案

我按照任南的建议改写了,现在循环到边界的边缘,如果再次到达起点,什么都没找到,返回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;
}
}
}
}

关于unity3d - 找一个区域有空位的函数,没找到怎么报错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18874950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com