0

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));
}
Neliosam
  • 73
  • 11
  • 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 Jul 28 '19 at 19:25
  • Thanks for your tip derHugo, this was a key to find the answer. – Neliosam Jul 30 '19 at 23:51

1 Answers1

0

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;
}
Neliosam
  • 73
  • 11
  • The reason why this works is that your object apparently already is a child of a `ScreenSpace - Overlay` canvas thus its position is in screen pixel coordinates. Getting `canvasOverlayObject` and `canvas` still makes no sense since they are never used and just use expensive and redundant API calls ;) – derHugo Oct 09 '19 at 21:23