【问题标题】:How does InverseTransformPoint work? Unity C#InverseTransformPoint 是如何工作的?统一 C#
【发布时间】:2018-10-04 14:01:19
【问题描述】:

来自Unity scripting API

将位置从世界空间转换到局部空间。

但我不明白它在下面的块中是如何做到的

private Vector3 PlaceOnCircle(Vector3 position) {
    Ray ray = Camera.main.ScreenPointToRay (position);
    Vector3 pos = ray.GetPoint (0f);

    // Making 'pos' local to... ?
    pos = transform.InverseTransformPoint (pos);

    float angle = Mathf.Atan2 (pos.x, pos.z) * Mathf.Rad2Deg;
    pos.x = circle.radius * Mathf.Sin (angle * Mathf.Deg2Rad);
    pos.z = circle.radius * Mathf.Cos (angle * Mathf.Deg2Rad);
    pos.y = 0f;

    return pos;
}

它是让 'pos' 本地化还是本地化到拥有这个脚本的游戏对象?

为什么 InverseTransformPoint 的参数是变量本身?

pos = transform.InverseTransformPoint(); 会使'pos' 成为上述变换的局部变量难道不够吗?

【问题讨论】:

  • 函数的参数是点,假设在世界空间坐标中,您要从中计算局部坐标(函数的结果)。应用该函数的变换是本地参考系,将从中计算新的 x、y 和 z 坐标。因此,在这种情况下,它将“pos”(世界坐标)替换为相对于该脚本所附加到的当前游戏对象的局部坐标。

标签: c# unity3d coordinates transform coordinate-systems


【解决方案1】:

如果你分解将全局空间/世界空间位置转换为局部空间的神奇代码,那么这里是解释:

transform.InverseTransformPoint (pos);
  1. transform:transform 表示脚本所在的对象 随附的。它是您要将世界空间转换为本地空间的参考点。它可以是场景中的任何对象。
  2. InverseTransformPoint:根据step 1对象将世界空间位置转换为局部空间的神奇功能。
  3. pos:要转换为本地空间的世界空间位置。但是哪个本地空间?您在第 1 步中定义的那个。

【讨论】:

    【解决方案2】:
    private Vector3 PlaceOnCircle(Vector3 position)
    {
        // Cast a ray from the camera to the given screen point
        Ray ray = Camera.main.ScreenPointToRay (position);
    
        // Get the point in space '0' units from its origin (camera)
        // The point is defined in the **world space**
        Vector3 pos = ray.GetPoint (0f);
    
        // Define pos in the **local space** of the gameObject's transform
        // Now, pos can be expressed as :
        // pos = transform.right * x + transform.up * y + transform.forward * z
        // instead of
        // Vector3.right * x + Vector3.up * y + Vector3.forward * z
        // You can interpret this as follow:
        // pos is now a "child" of the transform. Its coordinates are the local coordinates according to the space defined by the transform
        pos = transform.InverseTransformPoint (pos);
    
        // ...
    
        return pos;
    }
    

    【讨论】:

      【解决方案3】:

      将位置从世界空间转换到局部空间。

      这意味着给定一个 Transform 对象,您将从变换调用 InverseTransformPoint 方法,并使用一个表示世界空间中位置的 Vector,此函数将从包含该函数的对象返回一个局部空间位置尊重,在你的情况下,“转换”。

      例如,您可以使用孩子来称呼它:

      Vector3 pos = transform.getChild(0).InverseTransformPoint(aWorldPosition);
      

      这将为子 0 生成本地空间中的位置。

      【讨论】:

        猜你喜欢
        • 2012-06-02
        • 1970-01-01
        • 2010-10-12
        • 2022-10-18
        • 1970-01-01
        • 2010-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多