编程判断两个线段是否相交

\

原文链接: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)));
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值