Search Unity

Figuring out the 2D "Screen" coordinate system

Discussion in '2D' started by omatase, Aug 31, 2014.

  1. omatase

    omatase

    Joined:
    Jul 31, 2014
    Posts:
    159
    I'm trying to better understand the 2D "screen" coordinate system in Unity. There's one particular problem I have been having that I can show as an example for one of the things I don't understand.

    In this example I have a prefab that I'm dynamically instantiating. When I do it asks for a Vector3. Although getting my prefab centered works fine and seems to make sense, when I try to align the prefab flush with the top of the window I have some unexpected results. The prefab is the rectangular box near the top of the screen shown in this image below.



    Here is the code I'm using.

    Code (CSharp):
    1. int unityUnits = 100;
    2.  
    3. Vector3 position = new Vector3((Screen.width / 2), (Screen.height) - ((TeamView.renderer.bounds.size.y * unityUnits) / 2), gameObject.layer);
    4.  
    5. var newTeam = (GameObject)Instantiate(TeamView, Camera.main.ScreenToWorldPoint(position), Quaternion.identity);
    Appreciate any help!
     
  2. velipekka

    velipekka

    Joined:
    Jun 2, 2014
    Posts:
    9
    Hi,

    2D is using the same coordinate system as 3D in unity.
    All sprites are just set to zero depth by default when working on the 2D mode.

    Here's a snippet that will set a sprite on top of the screen when using orthographic camera (default in 2D), and pivot point set to the centre of the Sprite.

    Code (CSharp):
    1. Vector2 screenTopPosition = Camera.main.ViewportToWorldPoint(new Vector2(0.5f, 1));
    2. float spriteHeightHalved = renderer.bounds.extents.y;
    3. transform.position = new Vector2 (screenTopPosition.x, screenTopPosition.y - spriteHeightHalved);
    spriteHeightHalved is not needed if you set the pivot to top from importer / Sprite Editor.
     
    Last edited: Sep 2, 2014
    perracolabs and omatase like this.
  3. omatase

    omatase

    Joined:
    Jul 31, 2014
    Posts:
    159
    Thanks velipekka, that helped.