Efficient maths algorithm to calculate intersections

后端 未结 9 786
既然无缘
既然无缘 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:21

    float x12 = x1 - x2;
    float x34 = x3 - x4;
    float y12 = y1 - y2;
    float y34 = y3 - y4;
    
    float c = x12 * y34 - y12 * x34;
    
    if (fabs(c) < 0.01)
    {
      // No intersection
      return false;
    }
    else
    {
      // Intersection
      float a = x1 * y2 - y1 * x2;
      float b = x3 * y4 - y3 * x4;
    
      float x = (a * x34 - b * x12) / c;
      float y = (a * y34 - b * y12) / c;
    
      return true;
    }
    

    Formulas taken from:
    Line-line intersection - Wikipedia

提交回复
热议问题