Site hosted by Angelfire.com: Build your free website today!
Point Inside a 2D Box (Non-Rotated) In 2D space:
By: Christopher Bartlett
Take a look at Solutions Page for other solutions.

Given:

  • A 2d Box aligned to the X and Y axises.
  • A point.

Asked to Write Code for following:

  • How to test if point is inside Box.

Assumptions:

  • none

Steps to Solve:

  1. Basic Idea is to find out if the point is inside the Box.
  2. Start by finding Xmax and Xmin for box sides and same for Ymax and Ymin.
  3. Then test if points X value is between Xmax and Xmin of box. If it is then test points Y value to the Boxes Ymax and Ymin and if so the point is inside the Box.
  4. CODE
Some Notes:

Could speed up if you allready stored the triangle's normal.
If your line is a unit vector and speed then multiply unit vector with speed to make the line's vector.
Have not tested code but should work.

CODE
Code uses:

  • Everything is compares.
  • // Start Code
    // must include at least these
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct fpoint_tag
    {
       float x;
       float y;
    } fpoint;
    
    int check_point_in_box(fpoint boxLR, fpoint boxLL, fpoint boxUL, fpoint boxUR, fpoint point)
    {
       float Xmin, Xmax, Ymin, Ymax;
       int answer=FALSE;
    
       // Find Min and Maxs
       if( boxLR.x < boxLL.x )
       {
          Xmin = boxLR.x;
          Xmax = boxLL.x;
       }
       else
       {
          Xmin = boxLL.x;
          Xmax = boxLR.x;
       }
       if( boxLR.y < boxLL.y )
       {
          Ymin = boxLR.y;
          Ymax = boxLL.y;
       }
       else
       {
          Ymin = boxLL.y;
          Ymax = boxLR.y;
       }
    
       // Now compare points X to boxes Xmax and Xmin
       if(point.x >= Xmin && point.x <= Xmax)
       {
       // pass first part now test Y
          {
             if(point.y >= Ymin && point.y <= Ymax) answer=TRUE;
          }
       }
       return answer;
    }
    
    // End Code
    
    
    All Material within this article is Copyrighted © 2000 by Christopher Bartlett, All rights reserved.
    Use is Granted for Learning. Last Revised on January 20th, 2000 (1-20-00).
    Web: The House of Bartlett Contact: houseofbartlett@angelfire.com Visits: