Reputation: 65
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));
}
Upvotes: 0
Views: 2011
Reputation: 65
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;
}
Upvotes: 0