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));
}
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 forz
instead of0
the position with a certain distance in front of the camera. – derHugo