Search Unity

Calculating World position of screen's corners?

Discussion in 'Scripting' started by bronxbomber92, Mar 4, 2008.

  1. bronxbomber92

    bronxbomber92

    Joined:
    Nov 11, 2006
    Posts:
    888
    Is this the correct way to do this?
    To add some context, these positions will be used to place box collider around the screen.

    Code (csharp):
    1. // Screens coordinate corner location
    2.     var upperLeftScreen = Vector3(0, Screen.height, ship.transform.position.y );
    3.     var upperRightScreen = Vector3(Screen.width, Screen.height, ship.transform.position.y);
    4.     var lowerLeftScreen = Vector3(0, 0, ship.transform.position.y);
    5.     var lowerRightScreen = Vector3(Screen.width, 0, ship.transform.position.y);
    6.    
    7.     //Corner locations in world coordinates
    8.     var upperLeft = camera.ScreenToWorldPoint(upperLeftScreen);
    9.     var upperRight = camera.ScreenToWorldPoint(upperRightScreen);
    10.     var lowerLeft = camera.ScreenToWorldPoint(lowerLeftScreen);
    11.     var lowerRight = camera.ScreenToWorldPoint(lowerRightScreen);
     
  2. CoherentInk

    CoherentInk

    Joined:
    Jul 16, 2006
    Posts:
    216
    Looks right to me!
     
  3. bronxbomber92

    bronxbomber92

    Joined:
    Nov 11, 2006
    Posts:
    888
    Hmm, it doesn't work though...
     
  4. CoherentInk

    CoherentInk

    Joined:
    Jul 16, 2006
    Posts:
    216
  5. bronxbomber92

    bronxbomber92

    Joined:
    Nov 11, 2006
    Posts:
    888
    Fixed it!

    Here's what I did:
    Code (csharp):
    1. // Screens coordinate corner location
    2.     var upperLeftScreen = Vector3(0, Screen.height, depth );
    3.     var upperRightScreen = Vector3(Screen.width, Screen.height, depth);
    4.     var lowerLeftScreen = Vector3(0, 0, depth);
    5.     var lowerRightScreen = Vector3(Screen.width, 0, depth);
    6.    
    7.     //Corner locations in world coordinates
    8.     var upperLeft = camera.ScreenToWorldPoint(upperLeftScreen);
    9.     var upperRight = camera.ScreenToWorldPoint(upperRightScreen);
    10.     var lowerLeft = camera.ScreenToWorldPoint(lowerLeftScreen);
    11.     var lowerRight = camera.ScreenToWorldPoint(lowerRightScreen);
    12.     upperLeft.y = upperRight.y = lowerLeft.y = lowerRight.y = ship.transform.position.y
    where
    Code (csharp):
    1. depth = (ship.transform.position.y-camera.transform.position.y);
     
unityunity