Today, I suddenly discovered that there was a problem with the intersection of planes and non-parallel lines before. It was too related to the previous blog, so I had to write a special article for error correction.
It can only be said that I have never encountered such a situation before. It is amazing. The code is as follows:
/// <summary>
/// 计算两射线交点
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <param name="p4"></param>
/// <param name="p3"></param>
/// <returns></returns>
private Vector2 CalculateLineCross(Vector2 p1, Vector2 p2, Vector2 p4, Vector2 p3)
{
//构建直线参数k和a
float k1 = (p2.y - p1.y) / (p2.x - p1.x);
float a1 = p2.y - k1 * p2.x;
float k2 = (p3.y - p4.y) / (p3.x - p4.x);
float a2 = p3.y - k2 * p3.x;
//根据求解计算交点
float y = (k2 * a1 - k1 * a2) / (k2 - k1);
float x = 0;
if (k1 != 0)
{
x = (y - a1) / k1;
}
else if (k2 != 0)
{
x = (y - a2) / k2;
}
return new Vector2(x, y);
}
See the problem, if (p2.x - p1.x), or (p3.x - p4.x) is equal to 0, then the slope k does not exist, and the result calculated based on this non-existent slope k is wrong.
However, the c# mathematical operation denominator = 0 does not report an error and the actual development scenario does not encounter the calculation result that the slope k does not exist, so it is ignored.
So now we have to complete the adaptability of this calculation, and use the linear equation system to solve it, as follows:
Then we only need to construct the parameters of the linear equation through four coordinates, as follows:
Next build the algorithm:
/// <summary>
/// 计算平面直线相交
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <param name="p4"></param>
/// <param name="p3"></param>
/// <returns></returns>
private Vector2 CalculateLineCross(Vector2 p1, Vector2 p2, Vector2 p4, Vector2 p3)
{
float[] abc1 = GetLineEquationParams(p1, p2);
float[] abc2 = GetLineEquationParams(p4, p3);
float a1 = abc1[0], b1 = abc1[1], c1 = abc1[2];
float a2 = abc2[0], b2 = abc2[1], c2 = abc2[2];
float x = (c2 * b1 - c1 * b2) / (a1 * b2 - a2 * b1);
float y = (c2 * a1 - c1 * a2) / (b1 * a2 - b2 * a1);
return new Vector2(x, y);
}
/// <summary>
/// 构建平面直线方程参数A、B、C
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <returns></returns>
private float[] GetLineEquationParams(Vector2 p1, Vector2 p2)
{
float a, b, c;
//L1
if (p1.y == p2.y)
{
a = 0;
b = 1;
c = -p1.y;
}
//L2
else if (p1.x == p2.x)
{
a = 1;
b = 0;
c = -p1.x;
}
//L3
else
{
float k = (p2.y - p1.y) / (p2.x - p1.x);
//y-y1=k(x-x1)
a = k;
b = -1;
c = p1.y - k * p1.x;
}
return new float[] {
a, b, c };
}
Just tested with the actual project, the effect is as follows:
This is the correction method for the intersection of plane non-parallel lines.