Vector Question

Not exactly a graphics question but a graphics person should be able to answer me.

I've got a Vector with origin Ro and Direction Rd, I also have a line between two points, P0 and P1, how do I find out if the line intersects between the two points, and where they intersect?

Who is Participating?
JaccoConnect With a Mentor Commented:
I presume your question concerns 2D problems.

Here is a sample algoritm:

P0(X,Y) P1(X,Y)

Ro(X,Y) Rd(X,Y)

First you make Po and Pd (which are the origin and direction of the lines through the points P0 and P1)

For the origin you take P1: Po = P1
For the direction you take P2 - P1: Pd = P2 - P1

PoX = P1X
PoY = P1Y

PdX = P2X - P1X
PdY = P2Y - P1Y

Normalizing the directions:

PdX = 1
PdY = (P2Y - P1Y)/(P2X - P1X)

RdY = RdY/RdX
RdX = 1

(Note: P2X-P1X can be zero making the divide impossible but you know then that the line
is vertical so if there is an intersection it is at RoX. An that is only possible if RoX is between P1X and P2X)

If RdY and PdY are equal then the line do not intersect. Otherwise continue.

The following equations describe both lines

RY = RoY + (RX - RoX)*RdY
PY = PoY + (PX - PoX)*PdY

a intersection occurs when:


Replace RX and PX by IX
Replace RY and PY by IY

That gives:

IY = RoY + (IX - RoX)*RdY
IY = PoY + (IX - PoX)*PdY

Subtract to two equations:

0 = RoY - PoY  + (IX - RoX)*RdY - (IX - PoX)*PdY

IX is the only unknow in this equation (notice that RdY and PdY need to be different):

0 = RoY - PoY + IX*RdY - RoX*RdY - IX*PdY + PoX*PdY

0 = RoY - PoY + IX*(RdY - PdY) - RoX*RdY + PoX*PdY

IX*(PdY - RdY) = RoY - PoY - RoX*RdY + PoX*PdY

IX = (RoY - PoY - RoX*RdY + PoX*PdY)/(PdY - RdY)

remembering that:

PoX = P1X
PoY = P1Y
PdY = (P2Y - P1Y)/(P2X - P1X)

You can rewrite the formula to:

IX = (RoY - P1Y - RoX*RdY + P1X*((P2Y - P1Y)/(P2X - P1X)))/((P2Y - P1Y)/(P2X - P1X) - RdY)

which were all known from the start.

Now we have the IX which is the X position of the intersection.

Check if IX is between P1X and P2X.

If not then there is no intersection.

If so then calculate the Y position. The line between the points P1 and P2 was described by:

IY = PoY + (IX - PoX)*PdY

Fill in formula for PdY:

IY = PoY + (IX - PoX)*PdY

IY = PoY + (IX - PoX)*(P2Y - P1Y)/(P2X - P1X)

There is you intersection.

I hope I didn't make any mistakes. You can use the ultimate formulas. But pay attention to vertical lines or directions!!

Regards Jacco

P.S. Phew these mathematics are handy but rusty

Good luck!
JoncAuthor Commented:
Edited text of question
All Courses

From novice to tech pro — start learning today.