绘制瓷砖地图monogame performance

时间:2016-01-31 10:21:39

标签: c# monogame texture2d

在特定情况下:
- 一个32x32的平铺地图即将用C#在monogame中绘制。
- 每个纹理都是64x64像素。
- 只有一种纹理(即一个.png文件)反复重复以填充地图 - 每个瓷砖都是来自Tile.cs类的对象 例1:
创建一个静态/抽象类,其中包含要绘制的一个纹理,以便每个tile对象在绘制时都可以使用它。

    public void Draw(){
        //Texture.GrassTexture is from the static class
        tile.Draw(Textures.GrassTexture);
    }

例2:
另一种方法是在从中创建新对象时为每个图块设置纹理变量。

    Texture2D tileTexture;
    public Tile(Texture texture){
        tileTexture = texture;
    }

绘制图块时,可以使用tileTexture变量。

例3:
在绘制图块时将纹理作为每个图块的参数发送。

    public void Draw(Texture2D texture){
        tile.draw(texture)
    }


从绩效的角度来看,哪些例子是最好的做法?欢迎任何其他想法!


该代码是为这篇文章制作的。

1 个答案:

答案 0 :(得分:2)

渲染性能角度来看,重要的是你在一次绘制地图时不会使用许多不同的纹理。

根据我的经验,经常切换纹理会损害性能。因此,您真正感兴趣的是将地图上的所有图块保存在单个纹理上(这通常称为纹理图集)。

MonoGame没有开箱即用的纹理图集支持。但是,您可以查看我们如何在MonoGame.Extended中实现它。

核心思想是实现一个类来表示纹理区域,它代表多块纹理中的单个图块。

public class TextureRegion2D
{
    public TextureRegion2D(string name, Texture2D texture, int x, int y, int width, int height)
    {
        if (texture == null) throw new ArgumentNullException("texture");

        Name = name;
        Texture = texture;
        X = x;
        Y = y;
        Width = width;
        Height = height;
    }

    public string Name { get; private set; }
    public Texture2D Texture { get; protected set; }
    public int X { get; private set; }
    public int Y { get; private set; }
    public int Width { get; private set; }
    public int Height { get; private set; }

    public Rectangle Bounds
    {
        get { return new Rectangle(X, Y, Width, Height); }
    }
}

然后在渲染瓷砖时,使用sprite批量的重载,该过量采用源矩形

var sourceRectangle = textureRegion.Bounds;
spriteBatch.Draw(textureRegion.Texture, position, sourceRectangle, color);

当然,要让这一切顺利完成仍然需要一些其他步骤。

  1. 您需要将瓷砖打包到单个纹理上。您可以手动执行此操作,也可以使用TexturePacker等工具。
  2. 您需要一种方法将瓷砖加载到纹理区域。如果瓷砖以简单的网格图案打包,则此代码手动编写相当简单。如果您使用过纹理包装器,则需要编写一个导入器。
  3. 最后,如果您已经使用Tiled Map Editor创建地图,您可能有兴趣知道MonoGame.Extended已经支持加载和渲染它们。

相关问题