Find out where a vector intersects a horizontal (or vertical) line

Of course the line intersection method can be used but in case of horizontal or vertical lines a quicker solution is available.

Assume  the vector V1 defined by points P1 and P2. and the horizontal line is  through point P

The offset of the intersection is:

offset = \dfrac{P_y - P1_y}{P2_y - P1_y}

Lets say P1 is 10,10 P2 20,20 and P.y 0,15

In this case  (15-10)/(20-10)  is 0.5

If P1 and P2 is revered it will be (15-20)/(10-20) = -5/-10 = 0.5.

Note:
There is a  special case if the vector is parallel or on the horizontal line, in that case, there is no intersection. In that case, p2.y – p1y is zero. This situation must be checked since it will also prevent a division by zero. You probably also want to limit very small values of this value since it may result in very large (positive or negatively) offset values.

Vertical lines:
In case of a vertical line replace all .y above by x.

Calculating the intersection point:
The offset when the vector is hit is always >= 0.0 and <= 1.0,  otherwise, it is on the extended vector.

Calculating the intersection point on the(extended)  vector is trivial

x = p1_x +(p2_x-p1_x) * offset
y = p1_y +(p2_y-p1_y) * offset

Lastest update in December 2019, inital post in June 2011

Write a comment

I appreciate comments, suggestions, compliments etc. Unfortunately I have no time to reply to them. Useful input will be used for sure!