Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Getting the exact 2D screen position for a 3D object

Discussion in 'Scripting' started by cmh322, Mar 3, 2010.

  1. cmh322

    cmh322

    Joined:
    Apr 3, 2009
    Posts:
    70
    How do I get the exact 2D screen position for an object in 3D world space? I'd like to position a GUITexture such that it is directly over a 3D object that is being displayed in the 3D world.

    I have tried using Camera.WorldToViewportPoint, but it doesn't seem to accurately use the Z coordinate. My camera view is at an angle over a field, and the Z modifies the depth of the object, which should actually impact the y of the viewport space. In short, if I place a GUITexture at the coordinates returned by WorldToViewportPoint, it is not over the 3D object.

    Any ideas? Thanks!
     
  2. cerebrate

    cerebrate

    Joined:
    Jan 8, 2010
    Posts:
    261
    for minDraw, you should probably have this at the very least the minimum draw distance for the camera(0.1). I increase the value so it doesn't clutter my view when they're within a certain distance, but this is entirely optional.
    Code (csharp):
    1. for (var lof in lfodeadList){
    2.         var screenPos2 = camera.WorldToScreenPoint(lof.position);
    3.        
    4.         if (screenPos2.z >= minDraw  screenPos2.z <= 2000.0  !Physics.Linecast(transform.position, lof.transform.position, notificationLayerMask)) {
    5.             screenPos2 = EGUI.ScreenToGUI(screenPos2);
    6.             rectpos2 = new Vector2(screenPos2.x, screenPos2.y);
    7.             GUI.Label(Rect(rectpos2.x - 16, rectpos2.y - 15, playerDeadTex.width, playerDeadTex.height), playerDeadTex);
    8.         }
    9.     }
    EGUI helper function:
    Code (csharp):
    1. static function ScreenToGUI(screenCoord : Vector3) : Vector3{
    2.     var scrnHght = Screen.height;
    3.     if (screenCoord.y >= scrnHght){
    4.         screenCoord.y = -1 * (screenCoord.y - scrnHght);
    5.     }
    6.     else{
    7.         screenCoord.y = Mathf.Abs(screenCoord.y - scrnHght);
    8.     }
    9.     return screenCoord;
    10. }