Check if a position is inside a rectangular shaped area?
I need to now if a certain position is inside a certain rectangular shaped area. I have looked inside the docs for something like this and I came across this: Rect.Contains() and this BoxColider.
Rect.Contains
only works for 2D spaces and the BoxColider
seems a bit like a over kill for my scenario since I only need to know if a certain position x is inside area y. So I am thinking of implementing my own class. I have the following structure in mind:
RectangleArea r = new RectangleArea(new Vector3(1, 1, 1), Quaternion.Euler(0, 45, 0), 10, 10, 10);
if(r.Contains(new Vector3(1, 1, 1))) {
// We are inside
}
The RectangleArea
needs a position a rotation and a width, height and depth. With these parameters the class will construct its 3D rectangular shaped area and I can call the Contains
method on it.
Question 1: should I implement my own class? Or is there something available in Unity that I am missing?
Question 2: I am having a hard time figuring out the maths behind the
RectanleArea
class. The first thing is to construct a rectangular area in 3D space from a: position, rotation, width, height and dept how can i do that? The second part is theContains
method how can i see is a position is inside the area?
Answer by MadDevil · Oct 09, 2015 at 11:08 AM
@anjanus
you can use bound function provided by unity, to check whether your point is inside a rectangular space or not.
Thank you for your response, I have looked at the Bounds
struct and it seems it should work for my problem. But how do I use this struct? I have the position rotation and the width, height and depth of the area how do I make a Bounds
object of it? Since Bounds
only accept a center and a size vector?
you can make a box collider with specific size and position as your requirements, and then you can check collider.bounds to know if the object is inside or not.
void Update() { if(transform.collider.bounds.Contains(_point.position)) { print("Inside"); } }
I don't have access to a Transform
so I need to make the Bounds
object myself. Do you have any clue on how to do that with the parameters I got?