所以我成功地制作了一条代表未投影到世界中的鼠标的射线,现在我需要检查该射线是否可以与四边形对象相交,这是我用来获取射线的代码:
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);
}
同样,这是我的四边形结构,我用它在 3d 空间中绘制“立方体世界”。public struct Quad { public Vector3 Origin; 公共 Vector3 左上角;公共 Vector3 左下;公共 Vector3 UpperRight; 公共 Vector3 右下角;公共 Vector3 正常;公共 Vector3 向上;公共 Vector3 左;
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;
}
}
我发现射线类有一个方法 intersects() 它将平面结构作为参数,平面结构在构造函数中采用法线和距原点的距离,但我的平面有位置和法线,而不仅仅是距原点的距离,所以我无法转换它们。如何检测我的光线是否与我的四边形结构相交?
编辑:我意识到我不能使用平面结构,因为它不是有限大小并且不包括角,就像我的四边形一样。我现在需要找到一种方法来检测这条射线是否与我创建的四边形相交...
感谢阅读,我意识到这个问题有点冗长,在此先感谢。