【问题标题】:Unity get corners of GameObjectUnity 获取 GameObject 的角点
【发布时间】:2019-08-12 20:31:04
【问题描述】:

我正在使用.GetWorldCorners 来查找棕榈树图像的右上角和左下角。但是,我返回的值与实际角落不同。此外,当我移动Image 时,角会改变位置,远离Image,而不是与它完全一起移动。我试过transform.postion 有同样的问题。

private void OnDrawGizmos()
{
    Vector3[] corners = new Vector3[4];
    GetComponent<RectTransform>().GetWorldCorners(corners);

    var bottomLeft = corners[0];
    var topRight = corners[2];

    Gizmos.color = new Color(0, 1, 0, 0.5f);
    Gizmos.DrawCube(topRight, bottomLeft);
    //Gizmos.DrawCube(new Vector2(this.transform.position.x - 0.5f, this.transform.position.y + 0.5f), new Vector2(this.transform.position.x + 0.5f, this.transform.position.y - 0.5f));
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您向 Gizmos.DrawCube 提供了错误的输入,它期望中心作为第一个参数,大小作为第二个参数。所以正确的代码是:

    private void OnDrawGizmos()
    {
        Vector3[] corners = new Vector3[4];
        GetComponent<RectTransform>().GetWorldCorners(corners);
    
        var center = (corners[0] + corners[2]) / 2;
        var size = corners[2]- corners[0];
    
        Gizmos.color = new Color(0, 1, 0, 0.5f);
        Gizmos.DrawCube(center, size);
    }
    

    【讨论】:

      【解决方案2】:

      来自Docspublic static void DrawCube(Vector3 center, Vector3 size);

      您似乎正在绘制立方体,其中心位于图像的右上角,大小等于图像的左下角位置。

      相反,试试

      Vector3 size = topRight - bottomLeft;
      Gizmos.DrawCube(bottomLeft + size * 0.5f, size);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 2015-01-25
        • 1970-01-01
        • 2015-10-25
        • 1970-01-01
        • 2016-07-15
        相关资源
        最近更新 更多