Search code examples
c++geometryrectangles

Point inside rectangle given sides and center


I'm given rectangle by it's height(h) and width(w), and it's center O(x0,y0). I need to calculate if given point A(x,y) is inside that rectangle. It is parallel to x and y axis. All values are real.

I came up with following test but for some reason website on which I'm testing the code is not working for all examples. Could someone point me in the right direction.

#include <iostream>
#include <cmath>
using namespace std;
int main(){
    long x,y,x0,y0,r,h,w;
    scanf("%ld",&x);
    scanf("%ld",&y);
    scanf("%ld",&x0);
    scanf("%ld",&y0);
    scanf("%ld",&h);
    scanf("%ld",&w);
    if((x0+w/2.0>=x)&&(x0-w/2.0<=x)&&(y0+h/2.0>=y)&&(y0-h/2.0<=y))
        printf("inside a rectangle");
    else
        printf("outside a rectangle");
}

Thanks in advance.


Solution

  • After OP's Edit:

    The rectangle's side are parallel to x axis and y-axis. Then also it is possible to get the co-ordinates and apply the below mentioned algorithm.

    Centre -- (x0,y0)
    A -- (x0-w/2,y0-h/2)
    B -- (x0-w/2.y0+h/2)
    C -- (x0+w/2,y0+h/2)
    D -- (x0+w/2,y0-h/2)
    

    So all you have to do is, Apply the algorithms provided below.

    More simply we can do this,

    if( 2*x <= 2*x0+w && 2*x >= 2*x0-w && 2*y <= 2*y0+h && 2*y >= 2*y0-h)
    // it's inside
    

    Before OP's edit

    Your logic is wrong. It may say a point inside rectangle to be outside of it. (For any rectangle this is wrong - OP didn't mention the condition of being sides parallel to x-y axes)

    There is a simple way and cleaner way to do this for rectangle. Find the Area of the rectangle.

    Suppose it's A.

    Now if the point P lies inside ABCD then

    area of PAB+PBC+PCD+PDA = A
    

    For better thing do this with ,

    AB.Bc+BC.CD+CD.DA+DA.AB = 2*AB*BC
    

    or even better make a square of both side

    LHS^2 = 4*AB^2*BC^2
    

    Now you will just multiply and check it. One drawback of this solution is for large values of side length you have a chance of overflow.

    Another method would be to consider the projections.

    If point is inside of the rectangle then the projection of the corner of rectangle to point, on two of it's side must be less than the corresponding sides. You can check the projection length using dot products.

    For example if P is the point and ABCD is rectangle check,

    if AP's projection on AB has greater than zero length but less than the length of AB. Check the same with BC and BP and check if length is greater than zero and less than BC or not.

    This two condition makes sure that your point lies inside the rectangle.