📜  如何获得物体边缘的世界位置? - C# (1)

📅  最后修改于: 2023-12-03 15:09:14.945000             🧑  作者: Mango

如何获得物体边缘的世界位置?

要获取物体边缘的世界位置,需要使用物体的Mesh数据和Transform组件。具体步骤如下:

  1. 获取物体的Mesh数据
MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
Mesh mesh = meshFilter.mesh;
  1. 获取物体的边界数据
Bounds bounds = mesh.bounds;
  1. 获取物体的Transform组件
Transform transform = gameObject.transform;
  1. 计算物体边缘的世界位置
Vector3 cornerPos1 = transform.TransformPoint(bounds.min.x, bounds.min.y, bounds.min.z);
Vector3 cornerPos2 = transform.TransformPoint(bounds.min.x, bounds.min.y, bounds.max.z);
Vector3 cornerPos3 = transform.TransformPoint(bounds.min.x, bounds.max.y, bounds.min.z);
Vector3 cornerPos4 = transform.TransformPoint(bounds.min.x, bounds.max.y, bounds.max.z);
Vector3 cornerPos5 = transform.TransformPoint(bounds.max.x, bounds.min.y, bounds.min.z);
Vector3 cornerPos6 = transform.TransformPoint(bounds.max.x, bounds.min.y, bounds.max.z);
Vector3 cornerPos7 = transform.TransformPoint(bounds.max.x, bounds.max.y, bounds.min.z);
Vector3 cornerPos8 = transform.TransformPoint(bounds.max.x, bounds.max.y, bounds.max.z);

将以上八个向量分别代表物体边缘的八个角的世界位置。

完整代码片段如下:

MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
Mesh mesh = meshFilter.mesh;
Bounds bounds = mesh.bounds;
Transform transform = gameObject.transform;
Vector3 cornerPos1 = transform.TransformPoint(bounds.min.x, bounds.min.y, bounds.min.z);
Vector3 cornerPos2 = transform.TransformPoint(bounds.min.x, bounds.min.y, bounds.max.z);
Vector3 cornerPos3 = transform.TransformPoint(bounds.min.x, bounds.max.y, bounds.min.z);
Vector3 cornerPos4 = transform.TransformPoint(bounds.min.x, bounds.max.y, bounds.max.z);
Vector3 cornerPos5 = transform.TransformPoint(bounds.max.x, bounds.min.y, bounds.min.z);
Vector3 cornerPos6 = transform.TransformPoint(bounds.max.x, bounds.min.y, bounds.max.z);
Vector3 cornerPos7 = transform.TransformPoint(bounds.max.x, bounds.max.y, bounds.min.z);
Vector3 cornerPos8 = transform.TransformPoint(bounds.max.x, bounds.max.y, bounds.max.z);

这样,我们就可以通过以上代码,获取到物体边缘的世界位置了。