【问题标题】:MonoGame / XNA Draw Polygon in SpritebatchMonoGame / XNA 在 Spritebatch 中绘制多边形
【发布时间】:2016-01-13 04:39:47
【问题描述】:

我目前正在使用 MonoGame 编写游戏,我需要绘制带纹理的形状。我想绘制具有 4 个角的多边形。 我所有的渲染都是用 spritebatch 完成的。 我尝试使用 TriangleStripes,但它对我来说效果不佳,因为我对着色器没有任何经验,并且将它与 spritebatch-rendercode 的其余部分混合似乎很复杂。 我想到的一个解决方案是绘制一个四边形并使用纹理坐标拉伸纹理。这有可能吗?我找不到与 spritebatch 相关的内容。 有人有教程或知道如何归档我的目标吗?

提前致谢。

【问题讨论】:

  • 如果您设置的目标矩形大于源矩形,则使用 spritebatch 将拉伸纹理。如果您只想渲染部分纹理,还可以设置不覆盖整个纹理的源矩形。您是否也需要扭曲纹理或您想要实现什么?
  • 是的,纹理也应该是倾斜的,这是我的问题。

标签: c# xna monogame


【解决方案1】:

如果您想以非矩形方式绘制纹理,则不能使用SpriteBatch。但是绘制多边形也不难,你可以使用BasicEffect,所以你不必担心着色器。 首先设置您的顶点和索引数组:

BasicEffect basicEffect = new BasicEffect(device);
basicEffect.Texture = myTexture;
basicEffect.TextureEnabled = true;

VertexPositionTexture[] vert = new VertexPositionTexture[4];
vert[0].Position = new Vector3(0, 0, 0);
vert[1].Position = new Vector3(100, 0, 0);
vert[2].Position = new Vector3(0, 100, 0);
vert[3].Position = new Vector3(100, 100, 0);

vert[0].TextureCoordinate = new Vector2(0, 0);
vert[1].TextureCoordinate = new Vector2(1, 0);
vert[2].TextureCoordinate = new Vector2(0, 1);
vert[3].TextureCoordinate = new Vector2(1, 1);

short[] ind = new short[6];
ind[0] = 0;
ind[1] = 2;
ind[2] = 1;
ind[3] = 1;
ind[4] = 2;
ind[5] = 3;

BasicEffect 是一个很棒的标准着色器,您可以使用它来绘制纹理、颜色,甚至对其应用光照。

VertexPositionTexture 是您的顶点缓冲区的设置方式。

如果你只想要颜色,你可以使用VertexPositionColor,如果你想要两者都使用VertexPositionColorTexture(用颜色着色纹理)。

ind 数组说明了组成四边形的两个三角形的绘制顺序。

然后在你的渲染循环中你这样做:

foreach (EffectPass effectPass in basicEffect.CurrentTechnique.Passes) 
{
    effectPass.Apply();
    device.DrawUserIndexedPrimitives<VertexPositionTexture>(
        PrimitiveType.TriangleList, vert, 0, vert.Length, ind, 0, ind.Length / 3);
}

就是这样! 这是一个非常简短的介绍,我建议您尝试一下,如果您遇到困难,这里有大量的教程和信息,谷歌是您的朋友。

【讨论】:

  • 感谢您的评论。我不知道基本效果。我见过的所有教程都使用了自定义着色器,monogame 无法编译它们
猜你喜欢
  • 2011-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多