Check a Point on a Line

Started by
6 comments, last by delbogun 22 years, 8 months ago
How do I check if (x,y) is on the line (x1,y1)- (x2,y2)?
Advertisement
well, you could get the y-intercept form of the line and just plug in the x and y values. If the two sides are equal then the point is on the line.

My Homepage
How many Microsoft employees does it take to screw in a light bulb?
None, they just declare drakness as a new standard.
My HomepageSome shoot to kill, others shoot to mame. I say clear the chamber and let the lord decide. - Reno 911
Make the following check:

  x1 - x      x2 - x------  ==  ------y1 - y      y2 - y  


Of course, it may not be exactly accurate, but then you can check it with a tolerance value.

~ Dragonus
thanks, the algorithm seems to work
but when i implement it in my game, it doesn''t work... probably wrong with implemention. i have to check it out and try to figure out what i did wrong...
Are you accounting for roundoff error? The effects of it (as yucky as it really is) might be present. I know I got hit with that yesterday. I was converting DMS (degrees-minutes-seconds) into decimal degrees and then back again, and it just doesn''t understand that, when I convert 20 minutes into 1/3°, that it''s supposed to give me 20'' back. Instead I get 19.99999999999999974152 or something to that effect. Thus, my GUI kept displaying 19''60".

You''ll want to do something similar to this:

  if(fabs(v - (int)v) > .9999999){  v = (int)v;  if(v >= 0) v++;  else v--;}else if(fabs(v - (int)v) < 0.0000001)  v = (int)v;  


~ Dragonus
The equation for a line whose segment is (x1,y1)-(x2,y2) has the following equation:

(y-y1)=(y2-y1)/(x2-x1)*(x-x1)

which can be rearranged to:

(x2-x1)*(y-y1)-(y2-y1)*(x-x1)=0

So, you can plug an arbitrary x,y coordinate into the above equation, and if you get a 0(or very close to zero), then the point is on the line.

Of course, that's the line, which is infinite, and extends beyond the segment.

The line segment is bounded by a box that can be described with (x1,y1) and (x2,y2). You can check if x,y is within that box and on the line by doing this:

if((x<=x2 || x<=x1) && (x>=x1 || x>=x2) && (y>=y1 || y>=y2) && (y<=y1 || y<=y2) && fabs((x2-x1)*(y-y1)-(y2-y1)*(x-x1))<0.001)
{
//point is on the line, or close enough
}


Get off my lawn!

Here''s a sample program demonstrating point on a line.

Get off my lawn!

thankyou very much... i got it to work..
thanks to both of you

This topic is closed to new replies.

Advertisement