Search code examples
vectorxnaxna-4.0

XNA - check if Vector2 is inside Rectangle


What's the best method to check if a Vector2 is inside a Rectangle?

myRect.contains(myVector2) does not work, because it expects a Point or a Rectangle.

I know I could cast the the Vector2 to a Point or even to a Rectangle with a size of 1/1, but I am unsure about performance.

What are your experiences?


Solution

  • While there may be additional execution time in casting vs creating a point like Point(myVector2.X, myVector2.Y), the implications are most likely too small for you to ever notice (generally should avoid premature optimization)

    Go with whatever looks cleanest and easier to maintain. If it were me I'd probably just create the new point in the method call...

    You could also write an extension method.

        public static Point Origin(this Vector2 v)
        {
            //original proposal
            //return new Point( (int)v.X, (int)v.Y );
    
            //better! does correctly round the values
            return new Point( Convert.ToInt32(v.X), convert.ToInt32(v.Y));
        }
    

    Then you could do something like this rect.Contains(vec.Origin)

    Something to remember, though: this method will not actually check if the vector is contained in the rectangle, this will only check if the origin is. Remember, a vector is direction and magnitude.