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

Lock gui element to screen

Discussion in 'Scripting' started by jessee03, Apr 1, 2015.

  1. jessee03

    jessee03

    Joined:
    Apr 27, 2011
    Posts:
    729
    I was wondering if there's an easy way to lock a Gui element to the screen area when working with a system that calculates the gui element in world space. Right now I have labels hovering over enemies but would like it so the elements stay locked to the screen when reaching the edges of the screen. Right now if I'm facing the opposite direction of the target the gui elements will be floating in 3d space no where near the targets, only works correctly while facing them.

    Code (csharp):
    1.  
    2. voidOnGUI(){
    3. Vector2 targetPos;
    4. targetPos =Camera.main.WorldToScreenPoint(transform.position);
    5. GUI.Label(newRect(targetPos.x -30,Screen.height- targetPos.y -30,120,20), monsterName +"");
    6. }
    7.  
    8.  
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Clamp the X and Y to 0 and height/width
     
  3. jessee03

    jessee03

    Joined:
    Apr 27, 2011
    Posts:
    729
    I looked into the Clamp function and added it to my code. I managed to get the gui locked to the screen for the x / y 0 coordinated but not the other sides of the screen when using Screen.width and Screen.height. Also I still have the issue to where if I'm facing away from the targets that the gui objects float in 3d space no where near the objects.

    Code (csharp):
    1.  
    2. GUI.Box(new Rect(Mathf.Clamp(targetPos.x, 0, Screen.width), Mathf.Clamp(Screen.height- targetPos.y, 0, Screen.height), 60, 20), curHp + "/" + maxHp);
    3.  
     
  4. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    If you're facing away from the object in question then you have to invert the X and Y screen space coordinate. You can tell this by looking at the Z screen space coordinate. If it's less than 0 then the thing is behind the camera and X,Y needs to be -X, -Y