MasterC0de
MasterC0de

Reputation: 197

Positioning gameobject from canvas to a 3D gameobject (Unity 3D)

I'm a newbie in Unity, I can't figure out how to get the position of 3D GameObject relative to the Camera or the Canvas.

I know that Camera.main.ScreenPointToRay(target) can be used to get the position of a GameObject. Is there a way to get the Position of a GameObject on Camera View or Canvas?

I have already made an alternative solution by just

But I don't like both.

Upvotes: 0

Views: 6067

Answers (2)

David
David

Reputation: 16277

If you want to get the game object's position projected onto the canvas, use below code:

var pos = gameObject.transform.position;
var vec2 = RectTransformUtility.WorldToScreenPoint(camera, pos);
Debug.Log(vec2);

enter image description here

In another case, if you want to get the screen coordinate of a UI-game object, try below:

public static List<Vector2> GetScreenCoordinateOfUIRect(RectTransform rt)
{
    Vector3[] corners = new Vector3[4];
    rt.GetWorldCorners(corners);

    var output = new List<Vector2>();
    foreach (Vector3 item in corners)
    {
        var pos = RectTransformUtility.WorldToScreenPoint(null, item);
        output.Add(pos);
    }
    return output;      
}

In this way, you can get the screen points of a UI game object (who has a RectTransform component), with bottom left as origin. Note that this screen point is independent of the anchor points, in all anchor point settings, this function works!

Upvotes: 0

Droppy
Droppy

Reputation: 9721

I have recently spent some time with this very problem. My intention was to position a 2D arrow over a 3D world object and found using Camera.WorldToViewportPoint() and RectTransform.anchorMin/Max to be the best solution.

Note that viewpoint point is normalized (0.0 - 1.0) and not an absolute pixel position:

Vector3 screenPos = Camera.main.WorldToViewportPoint(someObject.transform.position);
arrowImage.rectTransform.anchorMin = screenPos;
arrowImage.rectTransform.anchorMax = screenPos;

Upvotes: 3

Related Questions