c# - XNA - 矩阵等效于 SpriteBatch.Draw 转换?

标签 c# matrix xna transformation

假设我有这个接口(interface):

interface Drawable {
    Vector2 DrawPosition { get; }
    Texture2D Texture { get; }
    float Rotation { get; }
    Vector2 Origin { get; }
    Vector2 Scale { get; }
    bool FlipHorizontally { get; }
}

在扩展 Microsoft.Xna.Framework.Game 的类中,我重写了 Draw(GameTime) 并且此代码位于某处:

Drawable d = ...;
spriteBatch.Begin();
spriteBatch.Draw(d.Texture, d.DrawPosition, new Rectangle(0, 0, d.Texture.Width, d.Texture.Height), Color.White, d.Rotation, d.Origin, d.Scale, d.FlipHorizontally ? SpriteEffects.FlipHorizontally : SpriteEffects.None, 0);
spriteBatch.End();

这使用了 SpriteBatch.Draw(Texture2D 纹理、Vector2 位置、Nullable sourceRectangle、Color 颜色、 float 旋转、Vector2 原点、Vector2 比例、SpriteEffects 效果、 float layerDepth) 重载。

假设我有一组顶点,这些顶点构成了 d.Texture 返回的图像的粗略轮廓(也就是说,如果我在 Microsoft Paint 中打开图像并用铅笔画出这组顶点中的每个点,它会非常贴合)。如果我想绘制这些点,以便它们使用 GraphicsDevice.DrawUserPrimitives() 遍历纹理,是否有一种方法可以仅使用矩阵来转换顶点?关键是它只能使用矩阵,而且我没有其他绘图方法,因为我实际上还需要将转换后的顶点用于其他用途。我已经尝试过类似的东西

Matrix.CreateTranslation(new Vector3(-d.Origin, 0))
    * Matrix.CreateScale(new Vector3(d.Scale, 0))
    * Matrix.CreateRotationZ(d.Rotation)
    * Matrix.CreateTranslation(new Vector3(d.DrawPosition, 0)));

但它很难失败。这个问题有解决办法吗?

最佳答案

您的矩阵代码看起来适合世界 矩阵(在世界空间中放置一个模型)。所以我的猜测是其中之一:

  • 您的原语在模型空间中的位置错误。 Sprite 批处理创建一个多边形,其中 (0,0) 是 Sprite 的左上角,({texture width}, {texture height}) 是右下角。您的图元需要具有相同的大小并位于相同的位置。

  • 您的投影矩阵是错误的。参见 this answer .请注意,SpriteBatch 使用翻转(客户空间)坐标系。

  • 您的背面剔除模式错误(未考虑翻转坐标系)。

  • 您遇到了深度缓冲问题(您需要在远平面和近平面内绘制,您是否被任何东西深度剔除了?)

如果您仍有问题,请从 DirectX SDK 获取 PIX 并使用它来确定您的游戏实际绘制的内容。

关于c# - XNA - 矩阵等效于 SpriteBatch.Draw 转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9510390/

相关文章:

c# - 比较两个声波

c# - 无法将.Net Core 2.0项目的项目引用添加到Azure函数项目(netStandard2.0)

python - IndexError : index 261861 is out of bounds for axis 0 with size 169567

C - 读取和解析方法未获得第二行输入

c# - 什么时候归一化一个向量?

c# - 已检测到关系 y 的角色 x 的冲突更改

c# - 从网页打开 .NET 应用程序

r - 如何在R中将多维下标存储为变量

c# - 为什么 Math.Cos 返回错误值?

vb.net - 将 XNA + VB.Net 游戏转换为 MonoGame