How to test if a line segment intersects an axis-aligned rectange in 2D?

前端 未结 12 749
执念已碎
执念已碎 2020-11-30 07:33

How to test if a line segment intersects an axis-aligned rectange in 2D? The segment is defined with its two ends: p1, p2. The rectangle is defined with top-left and bottom-

12条回答
  •  萌比男神i
    2020-11-30 08:05

    Some sample code for my solution (in php):

    // returns 'true' on overlap checking against an array of similar objects in $this->packed
    public function checkForOverlaps(BinPack_Polygon $nItem) {
      $nX = $nItem->getLeft();
      $nY = $nItem->getTop();
      $nW = $nItem->getWidth();
      $nH = $nItem->getHeight();
      // loop through the stored polygons checking for overlaps
      foreach($this->packed as $_i => $pI) {
        if(((($pI->getLeft() - $nW) < $nX) && ($nX < $pI->getRight())) && ((($pI->getTop() - $nH) < $nY) && ($nY < $pI->getBottom()))) {
          return true;
        }
      }
      return false;
    }
    

提交回复
热议问题