Efficient maths algorithm to calculate intersections

后端 未结 9 784
既然无缘
既然无缘 2020-11-28 21:40

For a game I am developing I need an algorithm that can calculate intersections. I have solved the problem, but the way I have done it is really nasty and I am hoping someon

9条回答
  •  被撕碎了的回忆
    2020-11-28 22:28

    public struct PointD
    {
        public double X { get; set; }
        public double Y { get; set; }
    }
    
    /// 
    /// Find the intersection point between two lines.
    /// 
    /// The intersection point. A PointD structure.
    /// The starting point of first line. A PointD structure.
    /// The end point of first line. A PointD structure.
    /// The starting point of second line. A PointD structure.
    /// The end point of second line. A PointD structure.
    /// The intersection position at first line.
    /// The intersection position at second line.
    /// Returns a boolean. True if there is intersection, false otherwise.
    /// The formula is taken from comp.graphics.algorithms Frequently Asked Questions.
    public static bool LineIntersect(out PointD IntersectPoint, PointD L1StartPoint, PointD L1EndPoint, PointD L2StartPoint, PointD L2EndPoint, out double L1IntersectPos, out double L2IntersectPos) 
    {
        IntersectPoint = new PointD();
        double ay_cy, ax_cx, px, py;
        double dx_cx = L2EndPoint.X - L2StartPoint.X,
            dy_cy = L2EndPoint.Y - L2StartPoint.Y,
            bx_ax = L1EndPoint.X - L1StartPoint.X,
            by_ay = L1EndPoint.Y - L1StartPoint.Y;
    
        double de = (bx_ax) * (dy_cy) - (by_ay) * (dx_cx);
        //double tor = 1.0E-10;     //tolerance
    
    
        L1IntersectPos = 0;      L2IntersectPos = 0;
        if (Math.Abs(de)<0.01)
            return false;
        //if (de > -tor && de < tor) return false; //line is in parallel
    
        ax_cx = L1StartPoint.X - L2StartPoint.X;
        ay_cy = L1StartPoint.Y - L2StartPoint.Y;
        double r = ((ay_cy) * (dx_cx) - (ax_cx) * (dy_cy)) / de;
        double s = ((ay_cy) * (bx_ax) - (ax_cx) * (by_ay)) / de;
        px = L1StartPoint.X + r * (bx_ax);
        py = L1StartPoint.Y + r * (by_ay);
    
        IntersectPoint.X = px;  //return the intersection point
        IntersectPoint.Y = py;  //return the intersection position
        L1IntersectPos = r;      L2IntersectPos = s;
    
        return true; //indicate there is intersection
    }
    

    To check whether the intersection point is not beyond the original length of the line, just make sure that 0 and 0

提交回复
热议问题