问题
Possible Duplicate:
How do you detect where two line segments intersect?
Given two points a
and b
plus two vectors v
and u
I want to find a third point c
, which is the point of intersection in the following manner:
vector2 intersection(vector2 a, vector2 v, vector2 b, vector2 u)
{
float r, s;
a + r * v = b + s * u;
r * v - s * u = b - a
r * v.x - s * u.x = b.x - a.x
r * v.y - s * u.y = b.y - a.y
}
Is there any other way than using gaussian elimination to solve this system? Or is this the best (or at least an acceptable) way to handle this?
EDIT:
Definition of vector2
typedef union vector2
{
float v[2];
struct { float x, y; };
} vector2;
a
and b
are also of type vector2
, because the only difference between a point and a vector is in the the way it is transformed by an affine transformation.
回答1:
It's simple math.
But, first, check that you have intersection. If both vector are parallel you will fail to solve that:
// Edit this line to protect from division by 0
if (Vy == 0 && Uy == 0) || ((Vy != 0 && Uy != 0 && (Vx/Vy == Ux/Uy)) // => Fail.
Then (I want show the calculation cause they long but):
R = (AxUy - AyUx + ByUx - BxUy) / (VyUx - VxUy)
S = (Ax - Bx + RVx) / Ux
Hope that helped you.
回答2:
Looks like an assignment problem to me. Here is the logic that will help you write the code.
Let us call the first Ray as R0
.
Locus of a point on R0
is defined as P
:
P = P0 + alpha x V0
For the second ray R1
:
P = P1 + beta x V1
Since they should intersect:
P0 + alpha x V0 = P1 + beta x V1
alpha
and beta
are unknowns and we have two equations in x
any y
.
Solve for the unknowns and get back the point of intersection.
i.e.,
P0.x + alpha * V0.x = P1.x + beta * V1.x
P0.y + alpha * V0.y = P1.y + beta * V1.y
solve for alpha
and beta
.
If there is a real positive solution for both alpha
and beta
, rays intersect.
If there is a real but at least one negative solution for both alpha
and beta
, extended rays intersect.
来源:https://stackoverflow.com/questions/14256525/given-two-points-and-two-vectors-find-point-of-intersection