如果相交返回true,不相交返回false
bool check(Node a, Node b, Node c, Node d){
if(!(min(a.x,b.x) <= max(c.x,d.x)
&& min(c.y,d.y) <= max(a.y,b.y)
&& min(c.x,d.x) <= max(a.x,b.x)
&& min(a.y,b.y) <= max(c.y,d.y)))
return 0;//所在矩形都不重叠 肯定不相交
double u, v, w, z;
u = (c.x - a.x) * (b.y - a.y) - (b.x - a.x) * (c.y - a.y);
v = (d.x - a.x) * (b.y - a.y) - (b.x - a.x) * (d.y - a.y);
w = (a.x - c.x) * (d.y - c.y) - (d.x - c.x) * (a.y - c.y);
z = (b.x - c.x) * (d.y - c.y) - (d.x - c.x) * (b.y - c.y);
return u * v < -eps && w * z < -eps;//跨立实验 解释如下
}
关于跨立实验的解释(转自勿忘初心0924)
如果两条线段相交,那么必须跨立,就是以一条线段为标准,另一条线段的两端点一定在这条线段的两段
也就是说a b两点在线段cd的两端,c d两点在线段ab的两端
这里就用到了向量X乘的知识点,有向量X乘的物理意义知:AB x CD=-CD x AB
看下图:
(ca x cd)·(cb x cd)<=0 则说明ca cb先对于cd的方向不同,则a b在线段cd的两侧,由此可以判断其他点