C# 使用单游戏绘制平铺地图
我一直在尝试实现一个函数,该函数允许我在平铺文件(.tmx)中绘制平铺。我环顾四周,发现了一种工作代码,但它不存在。C# 使用单游戏绘制平铺地图,c#,monogame,C#,Monogame,我一直在尝试实现一个函数,该函数允许我在平铺文件(.tmx)中绘制平铺。我环顾四周,发现了一种工作代码,但它不存在。 这是我找到并编辑的代码: private void DrawLayer(int index, SpriteBatch batch) { for (var i = 0; i < Map.Layers[index].Tiles.Count; i++) { //Get the identification of the tile
这是我找到并编辑的代码:
private void DrawLayer(int index, SpriteBatch batch) {
for (var i = 0; i < Map.Layers[index].Tiles.Count; i++) {
//Get the identification of the tile
int gid = Map.Layers[index].Tiles[i].Gid;
// Empty tile, do nothing
if (gid == 0) { }
else {
int tileFrame = gid - 1 ;
int column = tileFrame % (tileset.Width / tileWidth);
int row = tileFrame / (tileset.Height / tileHeight);
float x = (i % Map.Width) * Map.TileWidth;
float y = (float)Math.Floor(i / (double)Map.Width) * Map.TileHeight;
//Put all the data together in a new rectangle
Rectangle tilesetRec = new Rectangle(tileWidth * column, tileHeight * row, tileWidth, tileHeight);
//Draw the tile that is within the tilesetRec
batch.Draw(tileset, new Rectangle((int)x, (int)y, tileWidth, tileHeight), tilesetRec, Color.White);
}
}
}
private void DrawLayer(整数索引,SpriteBatch批处理){
对于(var i=0;i
该库支持加载和渲染平铺(.tmx)贴图。它是开源的,所以如果您愿意,可以查看它是如何工作的
支持不同的贴图类型(正交、等轴测)、不同的渲染顺序(右下、右上、左下、左上)和多个平铺集,因此它不会像您的方法那样归结为单个方法
如果要从何处提取相关的代码位,您可能会得到如下结果:
for (var y = 0; y < layerHeight; y++)
{
for (var x = 0; x < layerWidth; x++)
{
var region = tile.Id == 0 ? null : _regions[tile.Id];
if (region != null)
{
var tx = tile.X * _map.TileWidth;
var ty = tile.Y * _map.TileHeight;
var sourceRectangle = region.Bounds;
var destinationRectangle = new Rectangle(tx, ty, region.Width, region.Height);
_spriteBatch.Draw(region.Texture, destinationRectangle, sourceRectangle, Color.White);
}
}
}
请记住,我主要是从中复制和粘贴代码。它不会完全按照这里写的那样工作,但我认为我已经提供了足够的细节,可以弄清楚如果您想编写自己的平铺渲染代码,所有其他变量都会做什么。显然,您的平铺宽度和平铺高度不正确。不,它们实际上是正确的
_regions = new Dictionary<int, TextureRegion2D>();
for (var y = Margin; y < texture.Height - Margin; y += TileHeight + Spacing)
{
for (var x = Margin; x < texture.Width - Margin; x += TileWidth + Spacing)
{
_regions.Add(id, new TextureRegion2D(Texture, x, y, TileWidth, TileHeight));
id++;
}
}
public class TextureRegion2D
{
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); } }
}