in reply to Check if line is straight

I'm confused, every line thru 2 points is straight.

Actually you are calculating with 3 points P, P1 and P2 with P=($x,$y)

Is your intention to check if the path P1-P2 and P-P1 are on the same straight line or what?

One approach:

A path is "straight" iff the two vectors are identical after normalization (i.e. shortened to length 1 and with same orientation)

To normalize them divide each component by the length of the vector.

In 2 dimensional space you get the length simply by applying Pythagoras...in higher dimension use the scalar product.

Another (easier)approach:

Calculate the normal vector n of P1-P2 (a normalized vector orthogonal to the line).

The scalar product (aka dot product) of n · (P-P1) == 0 iff P,P1 and P2 are collinear.

Don't wanna go deeper into details thats all school stuff...

Cheers Rolf

Replies are listed 'Best First'.
Re^2: Check if line is straight
by LanX (Saint) on May 16, 2011 at 01:26 UTC
    proof of concept second approach, normalization of orthogonal not necessary for dot product to become 0.

    UPDATE: Nota bene: only additions no divisions, which makes the code fast and secure from division by 0 problems.

    ($p1,$p2,$p3)=([2,2],[3,4],[4,6]); sub vector { my ($x1,$y1) = @{$_[0]}; my ($x2,$y2) = @{$_[1]}; my @v=( $x2-$x1, $y2-$y1 ); my @o=( -$v[1] , $v[0] ); return [@v],[@o]; } sub dot { my ($x1,$y1) = @{$_[0]}; my ($x2,$y2) = @{$_[1]}; return $x1*$x2 + $y1*$y2; } my ($v12,$o12)= vector($p1,$p2); # the test my ($v)= vector($p1,$p3); print dot ($o12,$v); # 0 because p3 is collinear with p1 ,p2

    Cheers Rolf

      Sorry for not being clear, I assumed that looking at the code will make it obvious which is clearly not the case, The problem i am trying to solve is that it is basically a join the dots application, There are fixed points say point 1 and point 2, when the mouse is moved from point 1 to point 2 i want to make sure the path is correct so I take the start x,y (point1) and end x, y(point2) and take the current position of the mouse (x,y) and make sure that the path is correct. my code works fine if there is a slope but if the points are vertical or horizontal (slope 0) then I was not sure how to make sure that the direction and path is correct( a slight deviation is ok). Hope this clears up the question