简体   繁体   中英

Unity get corners of GameObject

I am using .GetWorldCorners to find the top right and the bottom left of palmtree images. 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. I have tried the transform.postion with same issue.

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. 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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM