- Home /
Using rect.contains to check if gameobject is inside in worldspace
I have a gameobject that's spawning at a random position, and I want to check if that position is within the rect that I made using an if statement. This is the code being used for the rect and the gameobject position, etc:
private Vector3 startPos = Vector3.zero;
public Rect cameraArea = new Rect(-10f, 6f, 20f, -12f);
startPos = (new Vector2(Random.Range(-12f, 12f), Random.Range(-8f, 8f)));
if (cameraArea.Contains(startPos))
{
Debug.Log("say wat");
}
I'm also assigning a gameobject's position ("Empty") to the start position, and some other gameobjects ("marker") as the dimensions of the rect so I can see when the startPos is inside the rect- whether it is or not, the debug isn't getting called. Anyone know what I'm doing wrong? Any and all help appreciated!
Answer by cdnDave · Jun 15, 2016 at 08:03 PM
It looks like you're setting your Rect's height to a negative value (-12). I believe you either need to set the width and height values of the Rect to positive numbers or pass in true for the allowInverse argument of the Rect.Contains call.
if(cameraArea.Contains(startPos, true))
Ah, thanks! Once I made it a positive height and moved it down a bit to the same position it worked fine.