Detect if line segment intersects square

前端 未结 3 718
面向向阳花
面向向阳花 2020-12-21 04:25

Anyone have a simple algorithm for this? No need for rotation or anything. Just finding if a line segment made from two points intersects a square

3条回答
  •  时光说笑
    2020-12-21 05:15

    This code should do the trick. It checks where the line intersects the sides, then checks if that is within the width of the square. The number of intesections is returned.

    float CalcY(float xval, float x0, float y0, float x1, float y1)
    {
        if(x1 == x0) return NaN;
        return y0 + (xval - x0)*(y1 - y0)/(x1 - x0);
    }
    
    float CalcX(float yval, float x0, float y0, float x1, float y1)
    {
        if(x1 == x0) return NaN;
        return x0 + (yval - y0)*(y1 - y0)/(x1 - x0);
    }
    
    int LineIntersectsSquare(int x0, int y0, int x1, int y1, int left, int top, int right, int bottom)
    {
        int intersections = 0;
        if(CalcX(bottom, x0, y0, x1, y1) < right && CalcX(bottom, x0, y0, x1, y1) > left  ) intersections++;
        if(CalcX(top   , x0, y0, x1, y1) < right && CalcX(top   , x0, y0, x1, y1) > left  ) intersections++;
        if(CalcY(left  , x0, y0, x1, y1) < top   && CalcY(left  , x0, y0, x1, y1) > bottom) intersections++;
        if(CalcY(right , x0, y0, x1, y1) < top   && CalcY(right , x0, y0, x1, y1) > bottom) intersections++;
        return intersections;
    }
    

    NB: this code is theoretical and may not be correct, as it has not been tested

提交回复
热议问题