2
votes

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.
1
I can see how test2 would fail. Do you have a screen shot of the results of test1? Also, which way is the camera pointing? How close is the near clip plane?rhughes
If have noticed that the Z position for the WorldToScreenPoint seems to be wrong? Could this be the reason that my coordinates are off?Kokodoko

1 Answers

2
votes

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;