原文链接:http://www.2cto.com/kf/201308/237246.html
java自创代码,供大家参考:
public static boolean intersect(MyPoint a1, MyPoint a2, MyPoint a3, MyPoint a4)
{
//判断a3&a4在a1a2两边
vector a1a4 = new vector(a4.getX()-a1.getX(), a4.getY()-a1.getY());
vector a1a2 = new vector(a2.getX()-a1.getX(), a2.getY()-a1.getY());
vector a1a3 = new vector(a3.getX()-a1.getX(), a3.getY()-a1.getY());
double cpa1a3_a1a2 = a1a3.crossProduct(a1a2);// a1a3Xa1a2
double cpa1a2_a1a4 = a1a2.crossProduct(a1a4);// a1a2Xa1a4
if(cpa1a3_a1a2*cpa1a2_a1a4<0)
{
return false;
}else if(cpa1a3_a1a2*cpa1a2_a1a4==0)
{
return true;
}else
{ //判断a1&a2在a3a4两边
vector a3a1 = new vector(a1.getX()-a3.getX(), a1.getY()-a3.getY());
vector a3a2 = new vector(a2.getX()-a3.getX(), a2.getY()-a3.getY());
vector a3a4 = new vector(a4.getX()-a3.getX(), a4.getY()-a3.getY());
double cpa3a1_a3a4 = a3a1.crossProduct(a3a4);// a3a1Xa3a4
double cpa3a4_a3a2 = a3a4.crossProduct(a3a2);// a3a4Xa3a2
if(cpa3a1_a3a4*cpa3a4_a3a2>=0)
{
return true;
}else
return false;
}
}
}
class vector{
private double x;
private double y;
vector()
{
x = 0;
y = 0;
}
vector(double xi, double yi)
{
x = xi;
y = yi;
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public double crossProduct(vector v1)
{
return (this.x*v1.getY() - this.y*v1.getX());
}
}
class MyPoint{
private double x;
private double y;
MyPoint()
{
this.x = 0;
this.y = 0;
}
MyPoint(double x, double y)
{
this.x = x;
this.y = y;
}
public double getX()
{
return this.x;
}
public double getY()
{
return this.y;
}
public void set(double x, double y)
{
this.x = x;
this.y = y;
}
public double distance(MyPoint p1)
{
return (Math.sqrt(Math.pow(this.x-p1.getX(), 2) + Math.pow(this.y-p1.getY(), 2)));
}
public double distance(double x, double y)
{
return (Math.sqrt(Math.pow(this.x-x, 2) + Math.pow(this.y-y, 2)));
}
}