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.
voidOnGUI(){
Vector2 targetPos;
targetPos =Camera.main.WorldToScreenPoint(transform.position);
GUI.Label(newRect(targetPos.x -30,Screen.height- targetPos.y -30,120,20), monsterName +"");
}
Clamp the X and Y to 0 and height/width
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.
GUI.Box(new Rect(Mathf.Clamp(targetPos.x, 0, Screen.width), Mathf.Clamp(Screen.height- targetPos.y, 0, Screen.height), 60, 20), curHp + "/" + maxHp);
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