Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if two rays intersect

I have two rays on a 2D plane that extend to infinity, but both have a starting point. They are both described by a starting point and a vector in the direction of the ray extending to infinity. I want to find out if the two rays intersect, but I don't need to know where they intersect (it's part of a collision detection algorithm).

Everything I have looked at so far describes finding the intersection point of two lines or line segments. Is there a fast algorithm to solve this?

like image 570
Faken Avatar asked May 28 '10 18:05

Faken


People also ask

At what point did the two rays intersect?

The common point of intersection of two rays to form an angle is called as vertex.

Can the intersection of two lines be a ray?

For lines, rays, and line segments, intersect means to meet or cross. When two lines, rays, or line segments intersect, they have one common point.


1 Answers

I am sorry to disagree with the answer of Peter Walser. Solving the equations gives on my desk:

u = ((bs.y - as.y) * bd.x - (bs.x - as.x) * bd.y) / (bd.x * ad.y - bd.y * ad.x) v = ((bs.y - as.y) * ad.x - (bs.x - as.x) * ad.y) / (bd.x * ad.y - bd.y * ad.x) 

Factoring out the common terms, this comes to:

dx = bs.x - as.x dy = bs.y - as.y det = bd.x * ad.y - bd.y * ad.x u = (dy * bd.x - dx * bd.y) / det v = (dy * ad.x - dx * ad.y) / det 

Five subtractions, six multiplications and two divisions.

If you only need to know if the rays intersect, the signs of u and v are enough, and these two divisons can be replaced by num*denom<0 or (sign(num) != sign(denom)), depending on what is more efficient on your target machine.

Please note that the rare case of det==0 means that the rays do not intersect (one additional comparison).

like image 107
Gunter Blache Avatar answered Sep 24 '22 00:09

Gunter Blache