draw the two lines with intersect each other and need to find the intersect point in c# using directx?
views:
318answers:
1
+3
A:
I can't remember much about direct3d at the moment; this website should get you started: http://www.drunkenhyena.com/cgi-bin/view_net_article.pl?chapter=2;article=21
As far as intersecting lines go, the following function should calculate a) whether or not two lines intersect at all, and if so where abouts.
static Point lineIntersect(Point a1, Point a2, Point b1, Point b2)
{
float dx, dy, da, db, t, s;
dx = a2.X - a1.X;
dy = a2.Y - a1.Y;
da = b2.X - b1.X;
db = b2.Y - b1.Y;
if (da * dy - db * dx == 0) {
// The segments are parallel.
return Point.Empty;
}
s = (dx * (b1.Y - a1.Y) + dy * (a1.X - b1.X)) / (da * dy - db * dx);
t = (da * (a1.Y - b1.Y) + db * (b1.X - a1.X)) / (db * dx - da * dy);
if ((s >= 0) & (s <= 1) & (t >= 0) & (t <= 1))
return new Point((int)(a1.X + t * dx), (int)(a1.Y + t * dy));
else
return Point.Empty;
}
You didn't specify whether your lines are expressed as coordinates (2 coordinates per line) or whether its an equation so I've assumed you have 2 points.
In addition, I have assumed the lines are not infinitely long, and hence may not intersect because either they are parallel, or simply not long enough to intersect.
Finally, these are for 2d lines only, if you want the equivalent in 3d, you need to ask about intersecting planes
Martin Booth
2010-01-18 06:21:01
There is a subtle bug here: if (da * dy - db * dx == 0) then the lines may be coincident, specifically, they may (1) touch at one point, (2) overlap in which case the intersection is actually a line segment, not a point or (3) they may not overlap at all (returning Point.Empty).
Jared Updike
2010-02-12 23:40:18
Specifically: http://stackoverflow.com/questions/2255842/detecting-coincident-part-of-two-line-segments-in-c
Jared Updike
2010-02-12 23:51:04
That is a good point, and it would probably be best to prefix this code with a comment explaining how it works when lines are coincident. I can think of a lot of cases where I would prefer to treat overlapping line segments as not intersecting but certainly it needs to be specified the output of the function in this event. Hopefully its clear enough from the method's signature that it cannot return a line segment and hence does not consider overlapping lines as intersected
Martin Booth
2010-02-14 23:47:41