嘿,我搜索了一下,发现了一个非常强大的库,它或多或少直接提供了您正在寻找的内容,甚至积极支持 Unity 类型:
几何3锐利 https://github.com/gradientspace/geometry3Sharp
Unity 项目的实现非常简单
然后您可以简单地计算给定数组的定向边界框的边缘Vector3
像这样的点:
using UnityEngine;
using g3;
public class Example : MonoBehaviour
{
// Just for the demo I used Transforms so I can simply move them around in the scene
public Transform[] transforms;
private void OnDrawGizmos()
{
// First wehave to convert the Unity Vector3 array
// into the g3 type g3.Vector3d
var points3d = new Vector3d[transforms.Length];
for (var i = 0; i < transforms.Length; i++)
{
// Thanks to the g3 library implictely casted from UnityEngine.Vector3 to g3.Vector3d
points3d[i] = transforms[i].position;
}
// BOOM MAGIC!!!
var orientedBoundingBox = new ContOrientedBox3(points3d);
// Now just convert the information back to Unity Vector3 positions and axis
// Since g3.Vector3d uses doubles but Unity Vector3 uses floats
// we have to explicitly cast to Vector3
var center = (Vector3)orientedBoundingBox.Box.Center;
var axisX = (Vector3)orientedBoundingBox.Box.AxisX;
var axisY = (Vector3)orientedBoundingBox.Box.AxisY;
var axisZ = (Vector3)orientedBoundingBox.Box.AxisZ;
var extends = (Vector3)orientedBoundingBox.Box.Extent;
// Now we can simply calculate our 8 vertices of the bounding box
var A = center - extends.z * axisZ - extends.x * axisX - axisY * extends.y;
var B = center - extends.z * axisZ + extends.x * axisX - axisY * extends.y;
var C = center - extends.z * axisZ + extends.x * axisX + axisY * extends.y;
var D = center - extends.z * axisZ - extends.x * axisX + axisY * extends.y;
var E = center + extends.z * axisZ - extends.x * axisX - axisY * extends.y;
var F = center + extends.z * axisZ + extends.x * axisX - axisY * extends.y;
var G = center + extends.z * axisZ + extends.x * axisX + axisY * extends.y;
var H = center + extends.z * axisZ - extends.x * axisX + axisY * extends.y;
// And finally visualize it
Gizmos.DrawLine(A, B);
Gizmos.DrawLine(B, C);
Gizmos.DrawLine(C, D);
Gizmos.DrawLine(D, A);
Gizmos.DrawLine(E, F);
Gizmos.DrawLine(F, G);
Gizmos.DrawLine(G, H);
Gizmos.DrawLine(H, E);
Gizmos.DrawLine(A, E);
Gizmos.DrawLine(B, F);
Gizmos.DrawLine(D, H);
Gizmos.DrawLine(C, G);
// And Here we ca just be amazed ;)
}
}
当然还有类似的东西
orientedBoundingBox.Box.Contains(Vector3d)
用于确定给定点是否位于该框中。
只因为鲁兹姆问:
当然,您可以稍微更改上面的脚本以仅使用实际的网格顶点:
public MeshFilter[] meshFilters;
private void OnDrawGizmos()
{
var vertices = new List<Vector3>();
foreach (var meshFilter in meshFilters)
{
// have to multiply the vertices' positions
// with the lossyScale and add it to the transform.position
vertices.AddRange(meshFilter.sharedMesh.vertices.Select(vertex => meshFilter.transform.position + Vector3.Scale(vertex, meshFilter.transform.lossyScale)));
}
var points3d = new Vector3d[vertices.Count];
for (var i = 0; i < vertices.Count; i++)
{
points3d[i] = vertices[i];
}
// ...
// From here the code is the same as above
看起来基本一样