找到共线之间的重叠

时间:2013-03-31 05:59:11

标签: algorithm geometry coordinates computational-geometry line-segment

给定两条共线线段AB和CD,如何找到它们是否重叠?如何找到重叠的起点和终点?

以下是我正在使用的方法。我首先确保A< B和C< d。

if(pa < pc){
  if(pc < pb){
    if(pd < pb){
      //  overlap exists; CD falls entirely within AB
    }
    else {
      //  overlap exists; CB is the overlapping segment
    }
  }
  else {
    //  no overlap exists; AB lies before CD
  }
}
else {
  if(pa < pd){
    if(pb < pd){
      //  overlap exists; AB lies entirely within CD
    }
    else {
      //  overlap exists; AD is the overlapping segment
    }
  }
  else {
    //  no overlap exists; CD lies before AB
  }
}

现在,有没有更简单的解决方案呢?

更新:还有另一种方法...比较两个段的长度之和与最外点之间的距离。如果后者较小,则存在重叠。

2 个答案:

答案 0 :(得分:17)

确保A&lt; B,C&lt; D:

if (pb - pc >= 0 and pd - pa >=0 ) { // overlap
    OverlapInterval = [ max(pa, pc), min(pb, pd) ] // it could be a point [x, x]
} // else: not overlap

答案 1 :(得分:3)

确保A<BC<DA<=C(您可以通过简单的交换来完成)。然后:

  • 如果B<C,则细分不相交
  • 如果B=C,则交叉点是单点B=C
  • 如果B>C,则交叉点为细分[C, min(B, D)]