3D Line-Plane Intersection

后端 未结 8 1912
-上瘾入骨i
-上瘾入骨i 2020-11-29 21:51

If given a line (represented by either a vector or two points on the line) how do I find the point at which the line intersects a plane? I\'ve found loads of resources on th

8条回答
  •  Happy的楠姐
    2020-11-29 22:27

    Just to expand on ZGorlock's answer, I have done the dot product, plus and scalse of 3D Vectors. The references for these calculations are Dot Product, Add two 3D vectors and Scaling. Note: Vec3D is just a custom class which has points: x, y and z.

    /**
     * Determines the point of intersection between a plane defined by a point and a normal vector and a line defined by a point and a direction vector.
     *
     * @param planePoint    A point on the plane.
     * @param planeNormal   The normal vector of the plane.
     * @param linePoint     A point on the line.
     * @param lineDirection The direction vector of the line.
     * @return The point of intersection between the line and the plane, null if the line is parallel to the plane.
     */
    public static Vec3D lineIntersection(Vec3D planePoint, Vec3D planeNormal, Vec3D linePoint, Vec3D lineDirection) {
        //ax × bx + ay × by
        int dot = (int) (planeNormal.x * lineDirection.x + planeNormal.y * lineDirection.y);
        if (dot == 0) {
            return null;
        }
    
        // Ref for dot product calculation: https://www.mathsisfun.com/algebra/vectors-dot-product.html
        int dot2 = (int) (planeNormal.x * planePoint.x + planeNormal.y * planePoint.y);
        int dot3 = (int) (planeNormal.x * linePoint.x + planeNormal.y * linePoint.y);
        int dot4 = (int) (planeNormal.x * lineDirection.x + planeNormal.y * lineDirection.y);
    
        double t = (dot2 - dot3) / dot4;
    
        float xs = (float) (lineDirection.x * t);
        float ys = (float) (lineDirection.y * t);
        float zs = (float) (lineDirection.z * t);
        Vec3D lineDirectionScale = new Vec3D( xs, ys, zs);
    
        float xa = (linePoint.x + lineDirectionScale.x);
        float ya = (linePoint.y + lineDirectionScale.y);
        float za = (linePoint.z + lineDirectionScale.z);
    
        return new Vec3D(xa, ya, za);
    }
    

提交回复
热议问题