Determining Whether A Point Is To the Left (Or Right) of A Ray (Line Segment), With C Code Example
© 2010 Darel Rex Finley. This complete article, unmodified, may be freely distributed for educational purposes.



Suppose you have a ray (directional line segment), and a point, like this:



And you want to determine whether the point is to the left of the ray — that is, if a person was standing on the starting point of the ray, and facing in the direction of the ray’s endpoint, would the third point be more to her left or her right?

All you need to do is rotate the whole coordinate system so that the ray is horizontal, and points in the positive direction along the X axis:





Now, it’s quite easy to tell — if the point is above the ray, it’s to the left. If the point is below the ray, it’s to the right. That was easy.

Here’s how to do it in C:


//  public-domain code by Darel Rex Finley,
//  2010.  See diagrams at http://
//  alienryderflex.com/point_left_of_ray


bool isPointLeftOfRay(double x, double y, double raySx, double raySy, double rayEx, double rayEy) {

  double  theCos, theSin, dist ;

  //  Translate the system so that the ray
  //  starts on the origin.

  rayEx-=raySx; rayEy-=raySy;
  x    -=raySx; y    -=raySy;

  //  Discover the ray’s length.
  dist=sqrt(rayEx*rayEx+rayEy*rayEy);

  //  Rotate the system so that the ray
  //  points along the positive X-axis.

  theCos=rayEx/dist;
  theSin=rayEy/dist;
  y=y*theCos-x*theSin;

  //  Return the result.
  return y>0.; }


Now here’s the same function, but stripped of unneeded calculations:

//  public-domain code by Darel Rex Finley,
//  2010.  See diagrams at http://
//  alienryderflex.com/point_left_of_ray


bool isPointLeftOfRay(double x, double y, double raySx, double raySy, double rayEx, double rayEy) {
  return (y-raySy)*(rayEx-raySx)
  >      (x-raySx)*(rayEy-raySy); }


Send me an e-mail!

Does the brace style in the above code sample freak you out?  Click here to see it explained in a new window.

Back to tutorials.