TheMisteryMan
TheMisteryMan

Reputation: 55

2D Rotated rectangle contains point calculation

My issue is that I've been trying to check if a rectangle that is rotated by a certain amount of degrees contain a point, but I wasn't able to calculate that after many attempts with the help of some code samples and examples that I've found online.

What I got is the rectangle (X, Y, Width, Height, Rotation) and the point (X, Y) and I've been trying to create a simple function that lets me instantly calculate that, which would be something something like this:

public bool Contains(Rect Rectangle, float RectangleRotation, Point PointToCheck);

But as I mentioned, I wasn't able to do so, those mathematical calculations that include some formulas I found online are way too much for me to understand.

Could someone help me with calculating this? If you could provide the calculation in C# code form (not formulas) then that would be great! Thanks.

PS: Using the 2D Physics Engine that is available in Unity3D is not a option, my rectangle is not associated with a gameobject that I could attach a 2D collision component to, I need to do this mathematically without the involvement of gameobjects or components.

Edit: I forgot to mention, the rectangle is being rotated by the middle of the rectangle (center/origin).

Upvotes: 2

Views: 3484

Answers (1)

laptou
laptou

Reputation: 6981

Rather than checking if the point is in a rotated rectangle, just apply the opposite of the rotation to the point and check if the point is in a normal rectangle. In other words, change your perspective by rotating everything by -RectangleRotation, so that the rectangle does not appear rotated at all.

public bool Contains(Rect rect, float rectAngle, Point point)
{
    // rotate around rectangle center by -rectAngle
    var s = Math.Sin(-rectAngle);
    var c = Math.Cos(-rectAngle);

    // set origin to rect center
    var newPoint = point - rect.center;
    // rotate
    newPoint = new Point(newPoint.x * c - newPoint.y * s, newPoint.x * s + newPoint.y * c);
    // put origin back
    newPoint = newPoint + rect.center;

    // check if our transformed point is in the rectangle, which is no longer
    // rotated relative to the point

    return newPoint.x >= rect.xMin && newPoint.x <= rect.xMax && newPoint.y >= rect.yMin && newPoint.y <= rect.yMax;
}

Upvotes: 3

Related Questions