【问题标题】:Unity3d Box Collider VertexUnity3d Box Collider 顶点
【发布时间】:2012-07-20 13:26:50
【问题描述】:

如何在 Unity3d 的世界空间中获取盒子碰撞器的顶点? (具有正确的旋转和比例)。仅仅在对象上做局部世界是行不通的。

obj.transform.localToWorldMatrix.MultiplyPoint3x4(extents);我尝试过为其他角落做类似的事情。

【问题讨论】:

  • 您能否具体说明一下您的需求。边界是轴对齐的,因此旋转并不真正相关。边界更改以保持对象的正确边界框。当您旋转所述对象时,边界不仅会随之旋转,因为这不会产生正确的 AABB。

标签: transform local unity3d


【解决方案1】:

由于您可以轻松获得BoxCollider's centre and extents,因此您可以通过从中心添加或减去范围轻松获得局部顶点位置,然后使用Vector3.TransformPoint()之类的方法将其转换为全局世界空间

以下脚本在每次 Update() 调用时打印附加到与脚本相同的 GameObject 的 BoxCollider 的每个顶点的全局位置。

using System.Collections;
public class DebugPrintColliderVertices : MonoBehaviour
{
const uint NUM_VERTICES = 8;

private BoxCollider boxCollider;
private Transform[] vertices;

void Awake()
{
    boxCollider = (BoxCollider)this.gameObject.GetComponent(typeof(BoxCollider));

    if (boxCollider ==  null)
    {
        Debug.Log ("Collider not found on " + this.gameObject.name + ". Ending script.");   
        this.enabled = false;
    }

    vertices = new Transform[NUM_VERTICES];
}

void Update()
{
    Vector3 colliderCentre  = boxCollider.center;
    Vector3 colliderExtents = boxCollider.extents;

    for (int i = 0; i != NUM_VERTICES ; ++i)
    {
        Vector3 extents = colliderExtents;

        extents.Scale (new Vector3((i & 1) == 0 ? 1 : -1, (i & 2) == 0 ? 1 : -1, (i & 4) == 0 ? 1 : -1));

        Vector3 vertexPosLocal = colliderCentre + extents;

        Vector3 vertexPosGlobal = boxCollider.transform.TransformPoint(vertexPosLocal);

        // display vector3 to six decimal places
        Debug.Log ("Vertex " + i + " @ " + vertexPosGlobal.ToString("F6"));
    }       
}
}

请注意,BoxCollider 的大小乘以它所附加的 GameObject 的 transform.scale。我没有在所述脚本中包含该计算,但从这一点开始,找到整体旋转/比例应该相当简单。

【讨论】:

  • GetCompnent 是 Component 的一个方法。 this.gameObject 是多余的。您也没有使用 GetComponent 的泛型。让它看起来像这样: boxCollider = GetComponent();此外,“顶点”不是一个词。
  • GetComponent 也是 GameObject link 的一个方法。我知道引用 this.gameObject 是多余的,但选择将其显示为该脚本所附加的游戏对象的关联,以防提出问题的用户不熟悉它的关联。
猜你喜欢
  • 2017-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-21
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多