C#与平面上2 Vector3点之间的线相交

时间:2017-11-14 03:47:39

标签: c# vector intersection

我在两个Vector3点之间有一条线,我想找到这条线在沿Z轴的高度相交的时候。

我正在尝试编写一个函数来计算交点。

void Main()
{
    Vector3 A = new Vector3(2.0f,  2.0f, 2.0f);
    Vector3 B = new Vector3(7.0f, 10.0f, 6.0f);
    float Z = 3.0f;

    Vector3 C = getIntersectingPoint(A, B, Z);
    //C should be X=3.25, Y=4.0, Z=3.0
} 

但是试图弄清楚如何正确地处理可能的负数正在开始让我迷惑。

这就是我现在所拥有的,但这不是正确的。

public static Vector3 getIntersectingPoint(Vector3 A, Vector3 B, float Z)
{
    // Assume z is bettween A and B and we don't need to validate
    // Get ratio of triangle hight, height Z divided by (Za to Zb)  
    ("absolute value: " + Math.Abs(A.Z-B.Z)).Dump();
    ("z offset: " + (Math.Abs(Z-B.Z)<Math.Abs(A.Z-Z)?Math.Abs(Z-B.Z):Math.Abs(A.Z-Z))).Dump();
    float ratio = (Math.Abs(Z-B.Z)<Math.Abs(A.Z-Z)?Math.Abs(Z-B.Z):Math.Abs(A.Z-Z))/Math.Abs(A.Z-B.Z);
    ("ratio: " + ratio.ToString()).Dump();
    float difX = ratio*Math.Abs(A.X-B.X);//this still needs to be added to or taken from the zero point offset
    ("difX: " + difX.ToString()).Dump();
    float difY = ratio*Math.Abs(A.Y-B.Y);//this still needs to be added to or taken from the zero point offset
    ("difY: " + difY.ToString()).Dump();

    float X = difX + (A.X<B.X?A.X:B.X);
    ("X: " + X).Dump();
    float Y = difY + (A.Y<B.Y?A.Y:B.Y);
    ("Y: " + Y).Dump();
    return new Vector3(X,Y,Z);
}

有没有人知道是否有任何已经执行此操作的数学库或示例如何执行此操作我可以遵循?

1 个答案:

答案 0 :(得分:1)

您有起始(2.0f)和结束(6.0f)Z坐标。两点之间的Z距离为4.0f。您想知道Z为3.0f的点处的X和Y坐标。

请记住,Z会沿段细分线性。该段长度为4个单位,您感兴趣的点从一开始就是1个单位,或者该段长度的1/4。

整个段的X距离为7.0 - 2.0或5个单位。 1/4的5是1.25,因此交点处的X坐标是3.25。

整个段的Y距离是8. 1/4的8是2.所以交点的Y坐标是6.0。

交点是(3.25f,6.0f,3.0f)。

如何计算:

// start is the starting point
// end is the ending point
// target is the point you're looking for.
// It's pre-filled with the Z coordinate.
zDist = Math.Abs(end.z - start.z);
zDiff = Math.Abs(target.z - start.z);
ratio = zDiff / zDist;

xDist = Math.Abs(end.x - start.x);
xDiff = xDist * ratio;
xSign = (start.x < end.x) ? 1 : -1;
target.x = start.x + (xDiff * xSign);

yDist = Math.Abs(end.y - start.y);
yDiff = yDist * ratio;
ySign = (start.y < end.y) ? 1 : -1;
target.y = start.y + (yDiff * ySign);

想一想,整个标志不应该是必要的。在end.x = 10start.x = 18

时请考虑这一点
xDist = end.x - start.x;      // xDist = -8
xDiff = xDist * ratio;        // xDiff = -2
target.x = start.x + xDiff;   // target.x = 18 + (-2) = 16

是的,不需要签名愚蠢。

计算比率时也不需要调用Math.Abs。我们知道zDistzDiff都会有相同的符号,因此ratio将始终为正。