[英]Unity 2D Tile Map — Group Tiles By Type C#
我正在寻找一种解决方案,可以根据游戏图块的类型对游戏图块进行分组。 磁贴存储在2d数组中,类型为空和水,成组的磁贴将存储在Group类中。
所以,如果我有二维数组:
0、0、0、0、0、0、0、0,
0、1、1、1、0、0、0、0,
0,1,1,0,0,0,1,1,
0、1、0、0、0、0、1、1
如果0为空,而1为水,则会有两个水组。
我花了整个下午努力弄清楚,这是我目前的状况。
public void GenerateGroups(){
//Debug.Log("Generate Groups");
m_Groups = new List<Group>();
List<Tile> groupingTiles = new List<Tile>();
int groupId = 1;
foreach(Tile t in m_Tiles){
t.IsGrouped = false;
}
for(int y = 0; y < Height; y++){
for (int x = 0; x < Width; x++) {
Tile tile = m_Tiles[x, y];
if(tile.Type == TileType.Water && !tile.IsGrouped){
// if(m_Tiles[x+1, y].IsGrouped || m_Tiles[x, y + 1].IsGrouped){
// if(m_Groups.Count > 0){
// foreach(Group g in m_Groups){
// if(g.m_Tiles.Contains(m_Tiles[x+1, y]) || g.m_Tiles.Contains(m_Tiles[x, y + 1])){
// g.m_Tiles.Add(tile);
// tile.IsGrouped = true;
// continue;
// }
// }
// }
// }else{
// groupingTiles.Add(tile);
// }
groupingTiles.Add(tile);
tile.IsGrouped = true;
Tile next = m_Tiles[x + 1, y];
int pos = x + 1;
while(next.Type == TileType.Water && !next.IsGrouped && pos < Width){
// Debug.Log("Going right!");
groupingTiles.Add(next);
pos++;
next.IsGrouped = true;
next = m_Tiles[pos, y];
}
next = m_Tiles[x, y + 1];
pos = y + 1;
while(next.Type == TileType.Water && !next.IsGrouped && pos < Height){
//Debug.Log("Going up!");
groupingTiles.Add(next);
pos++;
next.IsGrouped = true;
next = m_Tiles[x, pos];
}
}
if(groupingTiles.Count > 0){
//Debug.Log("Group Tiles: " + groupingTiles.Count);
m_Groups.Add(new Group("Group_" + groupId, groupingTiles));
groupId++;
groupingTiles = new List<Tile>();
}
}
}
Debug.Log(m_Groups.Count);
}
任何帮助,将不胜感激,谢谢!
我可以通过在磁贴内部保存组的引用来解决此问题。 遇到水砖时,请检查它的左邻居还是底部邻居也是水砖。 这可以在以下四种情况下结束:
我写了一段代码作为演示,但是请注意,它未经测试且经过简化。 我认为合并两个组有点麻烦,因为您需要更新每个组的引用。 另外,您以后必须仅用一个图块整理出组(如果需要)。 但这应该为您指明正确的方向:
for(int y = 0; y < Height; y++)
{
for(int x = 0; x < Width; x++)
{
Tile currentTile = GetTile(x, y);
if(!currentTile.IsWater)
continue;
Tile leftTile = GetLeftNeighbour(currentTile);
Tile bottomTile = GetBottomNeighbour(currentTile);
if(!leftTile.IsWater && !bottomTile.IsWater)
{
//first case
Group newGroup = new Group();
newGroup.Tiles.Add(currentTile);
currentTile.Group = newGroup;
}
else if(leftTile.IsWater && !bottomTile.IsWater)
{
//second case A
leftTile.Group.Tiles.Add(currentTile);
currentTile.Group = leftTile.Group;
}
else if(!leftTile.IsWater && bottomTile.IsWater)
{
//second case B
bottomTile.Group.Tiles.Add(currentTile);
currentTile.Group = bottomTile.Group;
}
else
{
if(leftTile.Group == bottomTile.Group)
{
//third case
leftTile.Group.Tiles.Add(currentTile);
currentTile.Group = leftTile.Group;
}
else
{
//fourth case
leftTile.Group.Merge(bottomTile.Group);
leftTile.Group.Tiles.Add(currentTile);
currentTile.Group = leftTile.Group;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.