supervisor-simulator/scripts/TileMapping.cs
2026-01-18 20:05:23 +08:00

66 lines
2.1 KiB
C#

using System.Collections.Generic;
using System.Linq;
using Godot;
/// <summary>
/// 图块映射辅助类
/// </summary>
public partial class TileMapping : Node {
/// <summary>
/// 从图块坐标到像素坐标的映射。如果不为空,则使用此映射。
/// </summary>
private readonly Dictionary<Vector2I, Vector2I> _pixelMap;
/// <summary>
/// 如果 pixelMap 为空,使用此偏移量将图块坐标转换为像素坐标。
/// </summary>
private Vector2I _pixelOffset;
/// <summary>
/// 图块区域
/// </summary>
private Rect2I _tileRect;
/// <summary>
/// 构造函数,使用坐标映射字典
/// </summary>
/// <param name="map">坐标映射字典</param>
public TileMapping(Dictionary<Vector2I, Vector2I> map) {
_pixelMap = map;
_pixelOffset = new Vector2I(-int.MaxValue, -int.MaxValue);
}
/// <summary>
/// 构造函数,使用偏移量和区域
/// </summary>
/// <param name="offset">偏移量</param>
/// <param name="rect">区域</param>
public TileMapping(Vector2I offset, Rect2I rect) {
_pixelMap = null;
_pixelOffset = offset;
_tileRect = rect;
}
public TileMapping() { }
/// <summary>
/// 应用映射到TileMapLayer
/// </summary>
/// <param name="layer">TileMapLayer</param>
public void Apply(TileMapLayer layer) {
// if pixelMap is not null, use all the pairs in pixelMap to set the tiles.
if (_pixelMap != null) {
var sourceId = layer.GetCellSourceId(_pixelMap.Keys.First());
foreach (var pair in _pixelMap) layer.SetCell(pair.Key, sourceId, pair.Value);
}
else {
var sourceId = layer.GetCellSourceId(_tileRect.Position);
GD.Print(_tileRect);
for (var x = _tileRect.Position.X; x < _tileRect.End.X; x++)
for (var y = _tileRect.Position.Y; y < _tileRect.End.Y; y++) {
var pos = new Vector2I(x, y);
layer.SetCell(pos, sourceId, pos + _pixelOffset);
}
}
}
}