[英]Unity get corners of GameObject
I am using .GetWorldCorners
to find the top right and the bottom left of palmtree images. 我正在使用
.GetWorldCorners
查找.GetWorldCorners
图像的右上角和左下角。 However the values I get returned are different to the actual corners. 但是,我得到的值与实际角点不同。 Also when I move the
Image
the corners change position away from the Image
rather than move exactly with it. 同样,当我移动
Image
,拐角也会从Image
移开位置,而不是与Image
精确移动。 I have tried the transform.postion
with same issue. 我已经尝试了
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));
}
You are providing wrong input to Gizmos.DrawCube , it expects center as first and size as second arguement. 您向Gizmos.DrawCube提供了错误的输入,它期望居中为第一,而大小为第二。 So the correct code is:
因此正确的代码是:
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);
}
From the Docs : public static void DrawCube(Vector3 center, Vector3 size);
从文档开始 :
public static void DrawCube(Vector3 center, Vector3 size);
You seem to be drawing your cube with it's centre positioned at the top right of your Image, with a size equal to the Image's bottom left corner position. 您似乎在绘制立方体,其中心位于图像的右上角,大小等于图像的左下角位置。
Instead, try 相反,尝试
Vector3 size = topRight - bottomLeft;
Gizmos.DrawCube(bottomLeft + size * 0.5f, size);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.