如何使用 C# 在 Unity2D 中以特定半径围绕特定点生成对象

0 c# unity-game-engine

我尝试制作一款类似于“开锁游戏”的游戏。然而,我很难在圆的边界周围随机生成一个点,但不在圆内。有关更多详细信息,我想仅在圆的边界生成游戏对象,而不是在圆的每个位置生成游戏对象。请帮助我:<非常感谢,祝您有美好的一天!p/s:我只是 Unity 引擎和语法的初学者。如果您能给我一些关于如何自学团结的建议,那就太好了。太感谢了

小智 6

首先,我真的很喜欢点积。我在参考对象周围随机放置了一个位置(在本例中transform.position)。randomPos然后在参考对象之间采取方向。计算的点积Vector3.Dot()randomPos取和之间的角度,transform.forward得到点积的结果。使用 Cos 和 Sin 函数计算 x 和 z 值。dotProductAngle点积角度始终给出 0 到 180 的值,因此我通过乘以 为 z 轴赋予随机性(Random.value > 0.5f ? 1f : -1f)。如果你不这样做,给定的随机位置将始终在玩家的前面。

3D空间

private void SpawnSphereOnEdgeRandomly3D()
        {
            float radius = 3f;
            Vector3 randomPos = Random.insideUnitSphere * radius;
            randomPos += transform.position;
            randomPos.y = 0f;
            
            Vector3 direction = randomPos - transform.position;
            direction.Normalize();
            
            float dotProduct = Vector3.Dot(transform.forward, direction);
            float dotProductAngle = Mathf.Acos(dotProduct / transform.forward.magnitude * direction.magnitude);
            
            randomPos.x = Mathf.Cos(dotProductAngle) * radius + transform.position.x;
            randomPos.z = Mathf.Sin(dotProductAngle * (Random.value > 0.5f ? 1f : -1f)) * radius + transform.position.z;
            
            GameObject go = Instantiate(_spherePrefab, randomPos, Quaternion.identity);
            go.transform.position = randomPos;
        }
Run Code Online (Sandbox Code Playgroud)

3D 示例

UnitySpawnObjectOnEdgeRandomly3D

二维空间

private void SpawnSphereOnEdgeRandomly2D()
{
    float radius = 3f;
    Vector3 randomPos = Random.insideUnitSphere * radius;
    randomPos += transform.position;
    randomPos.y = 0f;
    
    Vector3 direction = randomPos - transform.position;
    direction.Normalize();
    
    float dotProduct = Vector3.Dot(transform.forward, direction);
    float dotProductAngle = Mathf.Acos(dotProduct / transform.forward.magnitude * direction.magnitude);
    
    randomPos.x = Mathf.Cos(dotProductAngle) * radius + transform.position.x;
    randomPos.y = Mathf.Sin(dotProductAngle * (Random.value > 0.5f ? 1f : -1f)) * radius + transform.position.y;
    randomPos.z = transform.position.z;
    
    GameObject go = Instantiate(_spherePrefab, randomPos, Quaternion.identity);
    go.transform.position = randomPos;
}
Run Code Online (Sandbox Code Playgroud)

二维示例

UnitySpawnObjectOnEdgeRandomly2D

我希望这可以帮助你