几何模板判断线段与直线相交模板

来源:互联网 发布:redis php 编辑:程序博客网 时间:2024/06/06 02:09

判断线段与直线是否相交

  对于线段相交的问题网上模板一大堆,但线段与直线相交的却很少,做几何计算的时候偶尔需要用到,如果没有相关的模板往往难以下手。这里就关于线段与直线相交的问题整理出一份模板,希望有所帮助。若有不足之处,请路过的大牛门不惜赐教。

  对于线段相交问题有两种版本:

       ①  包括端点相交和部分重合

       ②  不包括端点相交和部分重合

  那么对于直线与线段问题同样可以分为两种版本:

       ①  包括端点(线段端点)相交和重合

        ②  不包括端点和重合


    原理:判断线段两个端点是否在直线异侧


  预备函数:

struct point//定义点{    double x,y;    point() {}    point(double _x,double _y)    {        x=_x,y=_y;    }    point operator -(const point &b)const    {        return point(x-b.x,y-b.y);    }    double operator ^(const point &b)const    {        return x*b.y-y*b.x;    }    double operator *(const point &b)const    {        return x*b.x+y*b.y;    }} ;struct line//线{    point a,b;};int sgn(double x){    if(fabs(x)<eps) return 0;    if(x<0) return -1;    return 1;}

  叉积

double mult(point p0,point p1,point p2)//叉积{    return (p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y);}

  版本一:  判断两点(p1,p2)是否在直线异侧,不包括端点和重合

bool opposite_side(point p1,point p2,point l1,point l2){    return mult(l1,p1,l2)*mult(l1,p2,l2)<-eps;}

  版本二:  判断线段l1与直线l2是否相交,包括端点相交

bool seg_inter_line(line l1,line l2){    return sgn((l1.a-l2.b)^(l2.a-l2.b))*sgn((l1.b-l2.b)^(l2.a-l2.b))<=0;}

  test:
#include<bits/stdc++.h>using namespace std;const double eps=1e-8;struct point//定义点{    double x,y;    point() {}    point(double _x,double _y)    {        x=_x,y=_y;    }    point operator -(const point &b)const    {        return point(x-b.x,y-b.y);    }    double operator ^(const point &b)const    {        return x*b.y-y*b.x;    }    double operator *(const point &b)const    {        return x*b.x+y*b.y;    }} ;struct line//线{    point a,b;};int sgn(double x){    if(fabs(x)<eps) return 0;    if(x<0) return -1;    return 1;}double mult(point p0,point p1,point p2)//叉积{    return (p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y);}bool opposite_side(point p1,point p2,point l1,point l2){    return mult(l1,p1,l2)*mult(l1,p2,l2)<-eps;}bool seg_inter_line(line l1,line l2){    return sgn((l1.a-l2.b)^(l2.a-l2.b))*sgn((l1.b-l2.b)^(l2.a-l2.b))<=0;}bool inter(point s1,point e1,point s2,point e2)//判断线段相交{//    return opposite_side(s1,e1,s2,e2) && opposite_side(s2,e2,s1,e1);    return (max(s1.x,e1.x)>=min(s2.x,e2.x)) &&           (max(s2.x,e2.x)>=min(s1.x,e1.x)) &&           (max(s1.y,e1.y)>=min(s2.y,e2.y)) &&           (max(s2.y,e2.y)>=min(s1.y,e1.y)) &&           (mult(s1,s2,e1)*mult(s1,e1,e2)>0)&&           (mult(s2,s1,e2)*mult(s2,e2,e1)>0);}int main(){    line Seg,Line;    Seg.a.x=0,Seg.a.y=0;    Seg.b.x=1,Seg.b.y=1;    Line.a.x=0,Line.a.y=2;    Line.b.x=2,Line.b.y=0;    printf("test1: ");    if(opposite_side(Seg.a,Seg.b,Line.a,Line.b)) puts("opposite_side");    else puts("in_side!");    printf("test2: ");    if(seg_inter_line(Seg,Line)) puts("opposite_side");    else puts("in_side!");}


原创粉丝点击