java判断三维直线是否相交

    xiaoxiao2024-12-06  59

    因为工作需要,在网上找了很多的资料,没有直接的方法来解释或者是判断三维直线如何相交的问题。

    对于初学者(伸手党)来说很是苦扰。转载需要说明

    这里我自己尝试写了一下demo,感觉还是不错,但是只能判断三维无限长度的直线是否相交。

    如果是有限长度的三维直线,那么这个方式就不适用了,需要自己判断交点。

    原理:我这里是使用向量的方式来求的

    如:空间直线段1,2

    1、获取线段1的方向向量

    2、获取线段2的方向向量

    3、获取方向向量的阶乘

    4、从线段1任取一点,线段2任取一点组成一向量,相乘判断n的值就能判断是否相交

    好了原理大致这样略过,no code say bb?

    public class Distance3dTest { public String test3d(String point1, String point2,String point3,String point4) { //注意这里是包含有xyz坐标系的 Point3d p1 = new Point3d(point1); Point3d p2 = new Point3d(point2); Point3d p3 = new Point3d(point3); Point3d p4 = new Point3d(point4); //求出方向1的方向向量 Point3d f1 = new Point3d(); f1.setX(p2.x - p1.x); f1.setY(p2.y - p1.y); f1.setZ(p2.z - p1.z); //求出方向2的方向向量 Point3d f2 = new Point3d(); f2.setX(p4.x - p3.x); f2.setY(p4.y - p3.y); f2.setZ(p4.z - p3.z); if (f1.x * f2.y * f2.z == f2.x * f1.y * f1.z) { return "空间线段平行"; } //法向量的阶乘 Point3d faJie = faFa(f1, f2); //各取一点组成向量 Point3d point3d = new Point3d(); point3d.setX(p3.x-p1.x); point3d.setY(p3.y-p1.y); point3d.setZ(p3.z-p1.z); double n = point3d.x * faJie.x + point3d.y * faJie.y + point3d.z * faJie.z; if (n == 0) { return "相交!"; } return "不相交"; } /** * 2个法向量的叉乘 */ private Point3d faFa(Point3d p1,Point3d p2) { Point3d p = new Point3d(); p.setX(p1.y * p2.z - p2.y * p1.z); p.setY(-(p1.x * p2.z - p2.x * p1.z)); p.setZ(p1.x * p2.y - p2.x * p1.y); return p; } @Test public void test() { String s = test3d("0,0,0", "1,1,1", "1,1,2", "1,2,3"); System.out.println(s+"============"); } } public class Point3d { public double x; public double y; public double z; public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getZ() { return z; } public void setZ(double z) { this.z=z; } public Point3d() {} public Point3d(String location) { super(); //这里是我本地测试为了方便,传入的数据的类型是 1,2,3(经度,维度,高度,当然也可以自己赋值) String[] p1 = location.split(","); this.x = Double.valueOf(p1[0]); this.y = Double.valueOf(p1[1]); this.z = Double.valueOf(p1[2]); } }

    好了,基本上就这样判断。求交点比较的麻烦,这里因为我工作暂时不需要,所以也就没有深入的去了解,上面的代码如果高数学的好的话,基本上没多大问题,其实我就是利用高数推导出来的

    最新回复(0)