I'm a flash actionscript game developer who is a bit backward with mathematics, though I find physics both interesting and cool.
For reference this is a similar game to the one I'm making: Untangled flash game
I have made this untangled game almost to full completion of logic. But, when two lines intersect, I need those intersected or 'tangled' lines to show a different color; red.
It would be really kind of you people if you could suggest an algorithm for detecting line segment collisions. I'm basically a person who likes to think 'visually' than 'arithmetically' :)
Edit: I'd like to add a few diagrams to make convey the idea more clearly
P.S I'm trying to make a function as
private function isIntersecting(A:Point, B:Point, C:Point, D:Point):Boolean
Thanks in advance.
Answer
I use the following method which is pretty much just an implementation of this algorithm. It's in C# but translating it to ActionScript should be trivial.
bool IsIntersecting(Point a, Point b, Point c, Point d)
{
float denominator = ((b.X - a.X) * (d.Y - c.Y)) - ((b.Y - a.Y) * (d.X - c.X));
float numerator1 = ((a.Y - c.Y) * (d.X - c.X)) - ((a.X - c.X) * (d.Y - c.Y));
float numerator2 = ((a.Y - c.Y) * (b.X - a.X)) - ((a.X - c.X) * (b.Y - a.Y));
// Detect coincident lines (has a problem, read below)
if (denominator == 0) return numerator1 == 0 && numerator2 == 0;
float r = numerator1 / denominator;
float s = numerator2 / denominator;
return (r >= 0 && r <= 1) && (s >= 0 && s <= 1);
}
There's a subtle problem with the algorithm though, which is the case in which two lines are coincident but don't overlap. The algorithm still returns an intersectioin in that case. If you care about that case, I believe this answer on stackoverflow has a more complex version that addresses it.
Edit
I did not get a result from this algorithm, sorry !
That's strange, I've tested it and it's working for me except for that single case I described above. Using the exact same version I posted above I got these results when I took it for a test drive:
No comments:
Post a Comment