c# - 在圆形形成中生成的对象的移位旋转 - 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
//[] [] [] []
// [] [] [] []
//[] [] [] []
// [] [] [] []
}
我以为我对这一切的数学理解相对较好,但我在实现这个新功能时遇到了麻烦。我尝试了很多方法,例如将旋转变量乘以欧拉,但是使用这个变量很挑剔,而且它似乎很容易影响我的对象的方向,所以它们不再堆叠在一起并且结构分崩离析。
解决方案
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;
}
}
推荐阅读
- android - 启动画面仅在首次启动时运行,不会在后续启动时运行
- typescript - 从 Typescript 中的调用函数抛出时无法捕获错误
- python - 在python3中将多个数字转换为字母
- python-3.x - 在 ec2 Ubuntu 实例上启动 Jupyter Notebook
- python - 将代码从当前文件复制到另一个 python 文件
- java - 我正在从文件中读取 if 循环或为什么循环没有选择第一个按钮“7”而是获取所有其余部分
- python-3.x - 一种在带有元组的列表中查找重复项的有效方法,总结元组的值并删除使用的重复元组
- r - 线性模型的自举残差
- vexflow - 如何在 VexFlow 中渲染配乐?
- node.js - 尽管 zip 文件中有一个有效的包文件,但由于缺少 package.json 节点未能部署