我正在使用.GetWorldCorners
查找palmtree图像的右上角和左下角。但是,我得到的值与实际角点不同。同样,当我移动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));
}
答案 0 :(得分:3)
您向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);
}
答案 1 :(得分:1)
从Docs:public static void DrawCube(Vector3 center, Vector3 size);
您似乎正在绘制的立方体的中心位于图像的右上角,其大小等于图像的左下角位置。
相反,尝试
Vector3 size = topRight - bottomLeft;
Gizmos.DrawCube(bottomLeft + size * 0.5f, size);