在可见时获取3D模型的特定顶点的屏幕空间坐标

Geo*_*ett 5 c# 3d xna coordinate-systems

我想渲染一个模型,然后,如果特定的顶点(我将如何标记它们?)是可见的,我想渲染它们所在的2D.

我该怎么做呢?

And*_*ell 7

首先,您需要将顶点位置作为 a Vector4(透视投影需要使用齐次坐标;设置W = 1)。我假设你知道你想要哪个顶点以及如何获得它的位置。它的位置将在模型空间中。

现在只需将该点转换为投影空间。也就是说 - 乘以你的世界观投影矩阵。那是:

Vector4 position = new Vector4(/* your position as a Vector3 */, 1);
IEffectMatrices e = /* a BasicEffect or whatever you are using to render with */
Matrix worldViewProjection = e.World * e.View * e.Projection;
Vector4 result = Vector4.Transform(position, worldViewProjection);
result /= result.W;
Run Code Online (Sandbox Code Playgroud)

现在您的结果将在投影空间中,即屏幕左下角的 (-1,-1) 和右上角的 (1,1)。如果您想在客户端空间中获得您的位置(这是SpriteBatch使用的),那么只需使用与SpriteBatch.

Viewport vp = GraphicsDevice.Viewport;
Matrix invClient = Matrix.Invert(Matrix.CreateOrthographicOffCenter(0, vp.Width, vp.Height, 0, -1, 1));
Vector2 clientResult = Vector2.Transform(new Vector2(result.X, result.Y), invClient);
Run Code Online (Sandbox Code Playgroud)

免责声明:我尚未测试任何此代码。

(显然,要检查特定顶点是否可见,只需检查它是否在投影空间中的 (-1,-1) 到 (1,1) 范围内。)