我要在一个圆圈中生成一系列立方体/圆柱体,而不是直接在之前生成的对象之上执行相同的操作8次。这将创建一种由Unity元素构成的结构。

这是当前的样子:https://imgur.com/GCdCp2c

当前,对象每次都以完全相同的方式放置在彼此的顶部,因此对象被分成垂直的直线或某种类型的列。我想改变每个“图层”生成方式的旋转方式,使其几乎像是如何砌砖一样。

我在代码中留下了注释,希望可以提供进一步的视觉解释。

    public GameObject cylinder;
    int pieceCount = 15;
    Vector3 centerPos = new Vector3(0, -2.2f, 0);
    float radius = 1.21f;

    void Awake()
    {
        float angle = 360f / (float)pieceCount;

        for (int layers = 1; layers < 9; layers++)
        {
            for (int i = 0; i < pieceCount; i++)
            {
                Quaternion rotation = Quaternion.AngleAxis(i * angle, Vector3.up);

                Vector3 direction = rotation  * Vector3.forward;

                Vector3 position = centerPos + (direction * radius);
                Instantiate(cylinder, position, rotation);
            }
            centerPos.y += .6f;
        }
        //Currently the structure looks like this
        // [] [] [] []
        // [] [] [] []
        // [] [] [] []
        // [] [] [] []

        //Ideally something similar to this
        //[] [] [] []
        //  [] [] [] []
        //[] [] [] []
        //  [] [] [] []

    }


我以为我对这一切都比较了解数学,但是在实现此新功能时遇到了麻烦。我已经尝试了多种方法,例如将旋转变量乘以Eulers,但是使用此变量是很挑剔的,而且似乎很容易影响对象的方向,因此它们不再堆叠在一起,并且结构分崩离析。

最佳答案

您可以在交替层上添加0.5f * angle的偏移量。要获得交替,可以将偏移量设置为(layers % 2) * 0.5f * angle,其中layers从0开始:

void Awake()
{
    float angle = 360f / (float)pieceCount;

    for (int layers = 0; layers < 8; layers++)
    {
        float angleOffset = (layers % 2) * 0.5f * angle;
        for (int i = 0; i < pieceCount; i++)
        {
            Quaternion rotation = Quaternion.AngleAxis(i * angle + angleOffset, Vector3.up);

            Vector3 direction = rotation  * Vector3.forward;

            Vector3 position = centerPos + (direction * radius);
            Instantiate(cylinder, position, rotation);
        }
        centerPos.y += .6f;
    }
}

关于c# - 在圆阵中生成的对象的平移旋转-Unity C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59166474/

10-14 12:06
查看更多