首页 > 解决方案 > 在圆形形成中生成的对象的移位旋转 - Unity C#

问题描述

我在一个圆圈中生成了一系列立方体/圆柱体,而不是直接在先前生成的对象上执行相同的操作 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
        //[] [] [] []
        //  [] [] [] []
        //[] [] [] []
        //  [] [] [] []

    }

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

标签: c#algorithmunity3dprocedural-generation

解决方案


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

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;
    }
}

推荐阅读