0
votes

I have a mobile game with a BAR on the top of the screen. The bar and it's game objects are in canvas with "Screen Space - Overlay" mode plus a Canvas Scaler with scale mode of "Scale with Screen Size" and match equals "Match width or height".

I am animating a game object to the position of an object inside of this and the object is going completely of the screen (really far way).

I am trying to get the position of the object using code below.

Even so, the position being returned is complete of the screen. Any idea what I am doing wrong?

    public Vector3 getObjectPosition()
{
    // Getting my CANVAS
    Camera cam = Camera.main;
    GameObject canvasOverlayObject = GameObject.Find("CanvasOverlay");
    Canvas canvas = canvasOverlayObject.GetComponent<Canvas>();

    //Manual scalling the CANVAS
    float canvasScaleX = Screen.width / canvasOverlayObject.GetComponent<CanvasScaler>().referenceResolution.x;
    float canvasScaleY = Screen.height / canvasOverlayObject.GetComponent<CanvasScaler>().referenceResolution.y;

    return Camera.main.ScreenToWorldPoint(new Vector3(transform.position.x / canvas.scaleFactor, transform.position.y / canvas.scaleFactor, 0));
}
1
In Camera.main.ScreenToWorldPoint(new Vector3(transform.position.x / canvas.scaleFactor, transform.position.y / canvas.scaleFactor, 0)); you nowhere use any of the before calculated values .. and note that you should always pass in a value for z instead of 0 the position with a certain distance in front of the camera.derHugo
Thanks for your tip derHugo, this was a key to find the answer.Neliosam

1 Answers

0
votes

No scaling was needed even using the scaled canvas, just passed the gameobject.tranform.position as the parameter.

public Vector3 getPosition()
{
    Camera cam = Camera.main;
    GameObject canvasOverlayObject = GameObject.Find("CanvasOverlay");
    Canvas canvas = canvasOverlayObject.GetComponent<Canvas>();

    Vector3 rawPosition = Camera.main.ScreenToWorldPoint(gameObject.transform.position);

    return rawPosition;
}