我有一条在两个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);
}有没有人知道是否有任何数学库已经这样做了,或举例说明如何做到这一点,我可以跟随?
发布于 2017-11-14 04:05:07
您有起始(2.0f)和结束(6.0f) Z坐标。两点之间的Z距离为4.0f。你想知道Z是3.0f点的X和Y坐标。
请记住,Z沿段线性变化。这段是4个单位长,你感兴趣的点是一个单位从一开始,或1/4的长度段。
整个段的X距离为7.0-2.0,或5个单位.5的1/4是1.25,所以在交点处的X坐标是3.25。
整个路段的Y距离为8的8.1/4为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 = 10和start.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。我们知道zDist和zDiff都有相同的符号,所以ratio总是肯定的。
https://stackoverflow.com/questions/47277316
复制相似问题