Search Unity

Wrong Screen size

Discussion in 'Scripting' started by JPCannon, Dec 17, 2014.

  1. JPCannon

    JPCannon

    Joined:
    Sep 25, 2013
    Posts:
    37
    Hi. I have problem with new object in scene. Im setting it position, local, normal any type. I set x and y position on Screen.width and Screen.heigth. Problem is when I instatiate this objects in another resolutions. Once is over the screen, another time is on the half of screen :p I dont understand how it works. I want have object in the same point in any resolution.

    Code (CSharp):
    1. flameFloor.transform.position = new Vector3(Screen.width, Screen.height, flameFloor.transform.position.z);
    2.         Instantiate(flameFloor);
    Game is in 2D
     
    Last edited: Dec 17, 2014
  2. Coldcalifornian

    Coldcalifornian

    Joined:
    Feb 11, 2014
    Posts:
    14
    The key is Camera.ScreenToWorldPoint
    http://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

    Since the value of the resolution changes, you will need to normalize your screen position and deal in percentages not pixels.

    Here is a functional Demo:
    Code (CSharp):
    1. public class Example : MonoBehaviour {
    2.  
    3.     public GameObject yourPrefab;
    4.  
    5.     [Range(0.0f,1.0f)]
    6.     public float xPercentageOfScreen;
    7.  
    8.     [Range(0.0f,1.0f)]
    9.     public float yPercentageOfScreen;
    10.  
    11.     public float distanceFromTheMainCamera;
    12.  
    13.     void Update(){
    14.         if(Input.GetKey("i")){
    15.             InstantiateGOAtPoint();
    16.         }
    17.     }
    18.  
    19.     void InstantiateGOAtPoint(){
    20.         if(yourPrefab != null){
    21.             Instantiate(yourPrefab,PositionOfInstantiateGameObject(),Quaternion.identity);
    22.         }
    23.     }
    24.  
    25.     Vector3 PositionOfInstantiateGameObject () {
    26.         float xConvertedToCurrentResolution = xPercentageOfScreen * Screen.width;
    27.         float yConvertedToCurrentResolution = yPercentageOfScreen * Screen.height;
    28.  
    29.         Vector3 screenCoordinates = new Vector3(xConvertedToCurrentResolution,yConvertedToCurrentResolution,distanceFromTheMainCamera);
    30.         return Camera.main.ScreenToWorldPoint(screenCoordinates);  
    31.     }
    32. }
    Note that (0,0) is in the bottom left corner of the screen and (1,1) is in the top right.

    Hope that helps!
     
  3. JPCannon

    JPCannon

    Joined:
    Sep 25, 2013
    Posts:
    37
    Great thank, now works great! :D