rect.Contains right to left

Hi I have this code that works out if there are objects inside the rect and changes their color if they are.

However it only works when dragging from left to right and up to down, but not if I drag right to left or down to up.

I know that the problem is with this part…

var width : int = secondPos.x - originalPos.x;
var height : int = (Screen.height - secondPos.y) - (Screen.height - originalPos.y);
rect = Rect(originalPos.x, secondPos.y, width, height);

I just don’t know how to make it work in ALL directions. Here’s the full code for anyone who’s interested.

var DrawRect:boolean = false; 

private var originalPos : Vector2; 
private var secondPos : Vector2; 

private var rect : Rect; 


function Update () { 

if (Input.GetButtonDown("Fire1")) 
{ 

//drag box positions 
originalPos = Input.mousePosition;
} 
if(Input.GetButton("Fire1")) 
{ 
DrawRect = true; 
secondPos = Input.mousePosition; 
} 

if(Input.GetButtonUp("Fire1")) 
{ 
CreateBox(); 
} 
} 

function OnGUI() { 

if (DrawRect){ 
var width : int = secondPos.x - originalPos.x; 
var height : int = (Screen.height - secondPos.y) - (Screen.height - originalPos.y); 
rect = Rect(originalPos.x, secondPos.y, width, height); 
} 
} 
function CreateBox(){ 

    var circle = GameObject.FindGameObjectsWithTag ("circle"); 
    for (var circle in circle)  
    { 
        circleScreenPos = Camera.main.WorldToScreenPoint(circle.transform.position); 
        if (rect.Contains(circleScreenPos))
        { 
        // Send 'selected' messages etc to objects in here. 
      circle.renderer.material.color = Color.magenta; 
        }
    } 
    var square = GameObject.FindGameObjectsWithTag ("square");
    for (var square in square)
    {
        squareScreenPos = Camera.main.WorldToScreenPoint(square.transform.position); 
        if (rect.Contains(squareScreenPos))
        { 
        // Send 'selected' messages etc to objects in here. 
      square.renderer.material.color = Color.cyan;
    } 
 }
 DrawRect = false; 
}

If you drag left and/or up with the current code, you will get negative width/height values. The way to handle this is to use Mathf.Abs on the width and height. Then, use the lowest of the two X and Y positions of the two points to establish the top left corner:-

var x = Mathf.Min(originalPos.x, secondPos.x);
var y = Mathf.Min(originalPos.y, secondPos.y);
var width : int = Mathf.Abs(secondPos.x - originalPos.x);
var height : int = Mathf.Abs((Screen.height - secondPos.y) - (Screen.height - originalPos.y));
var rect = Rect(x, y, width, height);

Thanks Andeeee

Spot on as always.