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;
}