在给定情况下:
-在单机游戏中将使用C#绘制32x32瓦片地图。
-每个纹理均为64x64像素。
-只有一种纹理(即一个.png文件)不断重复以填充地图。
-类Tile.cs中的每个图块都是对象。
示例1:
创建一个静态/抽象类,其中包含要绘制的一个纹理,以便每个图块对象在绘制时都可以使用该纹理。
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)
}
从性能角度来看,哪些示例是最佳实践?任何其他想法都欢迎!
该代码是为此帖子制作的。
从渲染性能的角度来看,重要的是您在一次绘制地图时不会使用许多不同的纹理。
以我的经验,经常切换纹理确实会损害性能。因此,您真正感兴趣的是将地图的所有图块都保留在一个纹理上(通常称为纹理图集)。
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);
当然,要使这一切顺利进行还需要其他一些步骤。
最后,如果您已经在使用Tiled Map Editor创建地图,您可能会想知道MonoGame.Extended已经支持加载和渲染它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句