Kokodoko
Kokodoko

Reputation: 28128

How calculate screen position

I am trying to figure out how the 2D unit system in Unity works. My game screen is 800x450 pixels.

Say I want my object to be placed at 20,20 pixels from the left top (as it works in most 2D coordinate systems).

I have tried both "convert" methods of the camera, but both place my object at very strange locations, certainly not at 20,20 pixels from the left top.

My code:

    Vector3 test1 = Camera.main.ScreenToWorldPoint (new Vector3 (20, 20, 0));
    transform.position = test1;

    Vector3 test2 = Camera.main.WorldToScreenPoint (new Vector3 (20, 20, 0));
    transform.position = test2;

EDIT

I have made a test with getting the center of the screen in pixels. It calculates my Z position as 10, but my game is entirely flat. Everything is in 2D and I'm using the orthographic camera.

Code

Vector3 centerInPixels = Camera.main.WorldToScreenPoint (new Vector3 (0, 0, 0));
// this logs: 450,225,10
// so the pixel center is correct for 800x450, but the z is wrong.

Upvotes: 2

Views: 2125

Answers (1)

vsenik
vsenik

Reputation: 518

Coordinate system of screenspace is: bottom-left=(0,0), top-right (pixelWidth,pixelHeight). So as I understand you trying to place object to (20,pixelHeight-20). That would be

Vector3 test1 = Camera.main.ScreenToWorldPoint (new Vector3 (20, Camera.main.pixelHeight-20, camera.nearClipPlane));
transform.position = test1;    

Upvotes: 2

Related Questions