所以,我已經成功地取得了光線的代表未投影到世界的鼠標,現在我需要檢查,如果該線可以用四物相交,這裏是我使用來獲取射線代碼:Ray在XNA中與3D四邊形相交?
public Ray GetMouseRay()
{
Vector2 mousePosition = new Vector2(cursor.getX(), cursor.getY());
Vector3 nearPoint = new Vector3(mousePosition, 0);
Vector3 farPoint = new Vector3(mousePosition, 1);
nearPoint = viewport.Unproject(nearPoint, projectionMatrix, viewMatrix, Matrix.Identity);
farPoint = viewport.Unproject(farPoint, projectionMatrix, viewMatrix, Matrix.Identity);
Vector3 direction = farPoint - nearPoint;
direction.Normalize();
return new Ray(nearPoint, direction);
}
同樣,這是我的四元結構,我用它在三維空間中繪製「立方體世界」。 public struct Quad { public Vector3 Origin; public Vector3 UpperLeft; public Vector3 LowerLeft; public Vector3 UpperRight; public Vector3 LowerRight; public Vector3正常; public Vector3 Up; public Vector3 Left;
public VertexPositionNormalTexture[] Vertices;
public int[] Indexes;
public short[] Indexes;
public Quad(Vector3 origin, Vector3 normal, Vector3 up,
float width, float height)
{
Vertices = new VertexPositionNormalTexture[4];
Indexes = new short[6];
Origin = origin;
Normal = normal;
Up = up;
// Calculate the quad corners
Left = Vector3.Cross(normal, Up);
Vector3 uppercenter = (Up * height/2) + origin;
UpperLeft = uppercenter + (Left * width/2);
UpperRight = uppercenter - (Left * width/2);
LowerLeft = UpperLeft - (Up * height);
LowerRight = UpperRight - (Up * height);
FillVertices();
}
private void FillVertices()
{
// Fill in texture coordinates to display full texture
// on quad
Vector2 textureUpperLeft = new Vector2(0.0f, 0.0f);
Vector2 textureUpperRight = new Vector2(1.0f, 0.0f);
Vector2 textureLowerLeft = new Vector2(0.0f, 1.0f);
Vector2 textureLowerRight = new Vector2(1.0f, 1.0f);
// Provide a normal for each vertex
for (int i = 0; i < Vertices.Length; i++)
{
Vertices[i].Normal = Normal;
}
// Set the position and texture coordinate for each
// vertex
Vertices[0].Position = LowerLeft;
Vertices[0].TextureCoordinate = textureLowerLeft;
Vertices[1].Position = UpperLeft;
Vertices[1].TextureCoordinate = textureUpperLeft;
Vertices[2].Position = LowerRight;
Vertices[2].TextureCoordinate = textureLowerRight;
Vertices[3].Position = UpperRight;
Vertices[3].TextureCoordinate = textureUpperRight;
// Set the index buffer for each vertex, using
// clockwise winding
Indexes[0] = 0;
Indexes[1] = 1;
Indexes[2] = 2;
Indexes[3] = 2;
Indexes[4] = 1;
Indexes[5] = 3;
}
}
我發現射線類有一個方法相交(),這需要平面結構作爲參數,飛機結構需要一個正常的距離起源於構造,但我的飛機有位置和法線,而不是距離原點的距離,所以我不能轉換它們。我如何檢測我的射線是否與四元結構相交?
編輯: 我意識到我不能使用平面結構,因爲它不是有限的大小,也不包括角落,就像我的四邊形一樣。我需要找到一種方法來檢測這條射線是否與我創建的四邊形相交...
感謝閱讀,我意識到這個問題有點冗長,並且在此先感謝。
沿着平面的法向矢量的距離意味着,如果平面處於相同的方向,但被翻譯爲它也包含點(0,0,0),它需要移動多遠以達到其實際位置。或者它可能是這個價值的負面影響,我總是混合最後一點:) –
好吧,但不是距離原點到飛機最近的距離?對我來說,這似乎措辭不佳。 –
是的,但它依賴於一個平面可以完全由該正常單位矢量和距離定義的想法。 –