问题描述
我在运行时生成了许多立方体并将一些照片应用于它们(这是一种 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,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);
另一方面,我会查看并检查边界框的所有面,以检查体积的过度扩展是否是对称的。同时绘制中心,以尝试缩小问题的范围并检查它是否更多在范围内或仅在中心。
据我所知,这是获得的边界框的一个错位的中心,但为此,一侧的超出体积应该在另一侧缺少,所以如果这不是问题,那可能是一个有趣的更新,可以朝着解决方案迈进。