さまざまなアプローチでそれを行うことができます。
。しかし、セグメントとセグメントの交差テストを要求すると、非常に興味深い本「リアルタイム衝突検出」から抽出された疑似C ++の例がここにあります。
float Signed2DTriArea(Point a, Point b, Point c)
{
return (a.x - c.x) * (b.y - c.y) - (a.y - c.y) * (b.x - c.x);
}
int Test2DSegmentSegment(Point a, Point b, Point c, Point d, float &t, Point &p)
{
// signs of areas correspond to which side of ab points c and d are
float a1 = Signed2DTriArea(a,b,d); // Compute winding of abd (+ or -)
float a2 = Signed2DTriArea(a,b,c); // To intersect, must have sign opposite of a1
// If c and d are on different sides of ab, areas have different signs
if( a1 * a2 < 0.0f ) // require unsigned x & y values.
{
float a3 = Signed2DTriArea(c,d,a); // Compute winding of cda (+ or -)
float a4 = a3 + a2 - a1; // Since area is constant a1 - a2 = a3 - a4, or a4 = a3 + a2 - a1
// Points a and b on different sides of cd if areas have different signs
if( a3 * a4 < 0.0f )
{
// Segments intersect. Find intersection point along L(t) = a + t * (b - a).
t = a3 / (a3 - a4);
p = a + t * (b - a); // the point of intersection
return 1;
}
}
// Segments not intersecting or collinear
return 0;
}
本のソフトウェア使用許諾契約は、コード例を使用するために以下のクレジットを含めることを求めています:
コード例「モーガンカウフマーンパブリッシャーズ発行のChrister EricsonによるReal-Time Collision Detectionから©2005 Elvesier Inc」