GUI Follow Object On-Screen

I wrote some code that’s supposed to position a gui element over an object, however whenever the object isn’t in the camera view the element is supposed to stop and remain in the camera view but still follow the object. The code I wrote works on the x axis, that is it works as I explained it should, however, on the y axis for some reason the movement is inverted - if I move the object up the element goes down - not only that but it also sometimes just isn’t following the object correctly and if the object goes out of the screen it will restart at the bottom of the screen and follow it. The element will be offset while I didn’t manipulate any of the values for that to happen. Can anyone tell me how to fix this?

Here is my code:

var texture : Texture2D;
var angle : float;
var objective : GameObject;
var desiredPos : Vector2;
var size : Vector2;
var minimumX : float;
var maximumY : float;
var maximumX : float;
var minimumY : float;
var rect : Rect;
var pivot : Vector2;
var screenPos : Vector2;
var distance : float;
var dDistance : int;
var unit : String;

function Update () {
	
	screenPos = Camera.main.WorldToScreenPoint (objective.transform.position);
    desiredPos.x = ClampPosition (screenPos.x, minimumX, maximumX);
    desiredPos.y = screenPos.y;
    
    if(desiredPos.y > maximumY){
    
    	desiredPos.y -= maximumY;
    	
    }else
    
    if(desiredPos.y < minimumY){
    	 
    	
    	desiredPos.y += minimumY;
    	
    }
   	
   	rect = new Rect(desiredPos.x, desiredPos.y, size.x, size.y);
    pivot = new Vector2(rect.xMin + rect.width * 0.5f, rect.yMin + rect.height * 0.5f);

}

function ClampPosition (pos : float, min : float, max : float){
	
	if (pos < min)
	pos += min;
	
	return Mathf.Clamp (pos, min, max);
	
}

function OnGUI()
{
    
    var matrixBackup : Matrix4x4 = GUI.matrix;
    GUIUtility.RotateAroundPivot(angle, pivot);
    GUI.DrawTexture(rect, texture);
    GUI.matrix = matrixBackup;
    
}

See: Unity - Scripting API: Camera.WorldToScreenPoint,
it says, that : The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight).

and GUI (0,0) is top left. thats why it’s inverted. to flip u can use

rect = new Rect(desiredPos.x, Screen.height - desiredPos.y, size.x, size.y);