我想計算一個垂直于平面法向量的向量,如果你從上往下看平面,你會看到結果向量指向一個點。
示例影像:

我試過的
這是我為嘗試計算向量而撰寫的代碼。它不起作用,不確定要添加什么來修復它。
int sgn(float val) {
return (0.0f < val) - (val < 0.0f);
}
void DetermineVector(Vector3 normalVector, Vector3 hitPosition, Vector3 goalPoint) {
float deltaX = goalPoint.X - hitPosition.X; // TO - FROM
float deltaY = goalPoint.Y - hitPosition.Y; // TO - FROM
float deltaZ = goalPoint.Z - hitPosition.Z; // TO - FROM
// Determine the x, z components of the vector.
// Basic Pythagorean Theorem
float length = sqrt(deltaX * deltaX deltaZ * deltaZ);
float x = deltaX / length;
float z = deltaZ / length;
// Determine the y component of the vector;
// Gets the sign of angle rotation
float crossProductSum = -normalVector.X * deltaY normalVector.Y * deltaX;
int sign = sgn(crossProductSum); // Gets the sign -1, 0, and 1
// Use trigonometry to figure out the angle of the normal vector in relation to the UP vector (0, 1, 0)
// take that angle and subtract rotate 90 and take that resulting y vector and multiply the sign
float angle = acos(normalVector.Y);
float y = cos(angle - 90) * sign;
// We have to combine the components so that the Y component is the same because its already normalized
// But we have to normalize the x, z components based on the Y component
return Vector3(x / (1 - y), y, z / (1 - y));
}
uj5u.com熱心網友回復:
換句話說,您正在尋找從 hitPosition 到 goalPoint 沿 Y 軸的投影的向量。你不需要三角函式。
一個向量 (X,Y,Z) 垂直于平面的法線,如果它滿足:
X*normalVector.X Y*normalVector.Y Z*normalVector.Z == 0
(見點積。)
該向量指向goalPoint沿Y軸的投影,如果
X = deltaX
Z = deltaZ
代入并求解 Y:
Y = -(deltaX*normalVector.X deltaZ*normalVector.Z)/normalVector.Y
如果需要,您可以在最后標準化結果。
把它們放在一起:
Vector3 DetermineVector(Vector3 normalVector, Vector3 hitPosition, Vector3 goalPoint) {
float deltaX = goalPoint.X - hitPosition.X; // TO - FROM
float deltaY = goalPoint.Y - hitPosition.Y; // TO - FROM
float deltaZ = goalPoint.Z - hitPosition.Z; // TO - FROM
float X = deltaX;
float Y = -(deltaX*normalVector.X deltaZ*normalVector.Z)/normalVector.Y;
float Z = deltaZ;
// optionally normalize:
float length = sqrt(X*X Y*Y Z*Z);
X /= length, Y /= length, Z /= length;
return Vector3(X, Y, Z);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/516804.html
標籤:C 数学向量
下一篇:添加尾隨零以動態匹配精度
