c# - 如何使用尽可能小的边界将多个立方体封装在一个更大的立方体中?
问题描述
我在运行时生成了许多立方体并向它们应用了一些照片(它是一种 VR 照片浏览器)。无论如何,我正在尝试使用所有小立方体中最小的边界框将它们全部封装在一个更大的立方体中。这就是我到目前为止所拥有的。
生成所有立方体后,我要做的第一件事是将它们全部集中在它们的父级上,以便用户可以相对于中心定位和旋转它们。
Transform[] children = GetComponentsInChildren<Transform>();
Vector3 newPosition = Vector3.zero;
foreach (var child in children)
{
newPosition += child.position;
child.parent = null;
}
newPosition /= children.Length;
gameObject.transform.position = newPosition;
foreach (var child in children)
{
child.parent = gameObject.transform;
}
然后我计算所有作为父级子级的立方体的边界。
Renderer[] meshes = GetComponentsInChildren<Renderer>();
Bounds bounds = new Bounds(transform.position, Vector3.zero);
foreach (Renderer mesh in meshes)
{
bounds.Encapsulate(mesh.bounds);
}
Bounds maximumScrollBounds = bounds;
然后我创建了一个新的较大的(红色/透明)立方体,它将封装所有较小的立方体并使用我之前计算的范围来计算它的比例。
GameObject boundingBox = GameObject.CreatePrimitive(PrimitiveType.Cube);
Destroy(boundingBox.GetComponent<Collider>());
boundingBox.GetComponent<Renderer>().material = Resources.Load("Materials/BasicTransparent") as Material;
boundingBox.GetComponent<Renderer>().material.color = new Color32(255, 0, 0, 130);
boundingBox.name = "BoundingBox";
boundingBox.transform.localScale = new Vector3(maximumScrollBounds.size.x, maximumScrollBounds.size.y, maximumScrollBounds.size.z);
boundingBox.transform.localPosition = maximumScrollBounds.center;
boundingBox.transform.SetParent(transform);
但问题是封装立方体总是有点太大,我不知道为什么。
我需要它基本上只能到达其中较小立方体的边缘。
解决方案
我会尝试的事情:
1.- 我相信Bounds.Encapsulate
在世界空间中检索中心。所以我认为:
boundingBox.transform.localPosition = maximumScrollBounds.center;
需要替换为:
boundingBox.transform.position = maximumScrollBounds.center;
2.- 相同,但只是为了提供尝试使用本地/全局空间的想法,我也会尝试:
boundingBox.transform.localPosition = boundingBox.transform.InverseTransformPoint(maximumScrollBounds.center);
另一方面,我会查看并检查边界框的所有面,以检查体积的过度延伸是否是对称的。还要绘制中心,以尝试缩小问题并检查它是否更多在范围内或仅在中心。
据我所知,这是获得的边界框的错误中心,但要做到这一点,一侧的超出体积应该在另一侧缺少,所以如果这不是问题,那可能是一个有趣的更新朝着解决方案前进。
推荐阅读
- javascript - 来自 Vue 的动画画布
- reactjs - What is the correct value for a `defaultProp` that corresponds to a `PropTypes.element`?
- python - "Could not connect to display" on EC2 Server
- matlab - 如何从 x,y,z,v 数据中获取切片图?
- php - How to get Apache and MySQL logs in PHP
- c++ - 如何解决代码中的“未声明的标识符”错误?
- google-apps-script - 如何在 AppMaker 的下拉小部件中手动设置值?
- javascript - 传递给 promise.then 的布尔值是什么意思
- javascript - Inline Javascript stoped adding class to element
- java - Time spent at a specific location using GPS sensor