Unity 2D Tilemap自定义六边形规则图块

时间:2020-03-24 03:23:06

标签: c# unity3d

我正在寻找一种创建新型六边形规则图块的方法,以执行非常简单和特定的操作。我想创建一个六角规则图块,该图块可以根据相邻的其他类型的六角形图块自动选择一个精灵。默认的六边形规则图块使您可以在给定图块的每一侧都由同一图块类型作为边界时指定精灵,但这对我来说是不够的。

我最终想要创建一个海岸瓦片,该海岸瓦片将检测哪些边被海洋瓦片作为边界,并基于此选择正确的十六进制精灵。像这样的东西,但是具有指定海洋瓷砖的功能,而不仅仅是绿色箭头指示的瓷砖类型:

Coast tile example

我可以在他们的github仓库中看到Unity的六角形规则图块的默认代码,但不知道如何精确地覆盖此代码: https://github.com/Unity-Technologies/2d-extras/blob/master/Runtime/Tiles/HexagonalRuleTile/HexagonalRuleTile.cs

这是Unity中相对较新的主题,但是任何帮助或指导将不胜感激。

1 个答案:

答案 0 :(得分:1)

好吧,经过一些深入的谷歌搜索和反复试验后,发现了这一点。我需要的只是这个继承类,它覆盖了RuleMatch方法。希望这对其他人有用。

using System;
using UnityEngine;
using UnityEngine.Tilemaps;

[Serializable]
[CreateAssetMenu(fileName = "CoastHexagonTile", menuName = "Tiles/CoastHexagonTile")]
public class CoastHexagonTile : HexagonalRuleTile<CoastHexagonTile.Neighbor>
{
    public bool isOcean;
    public bool isCoast;

    public class Neighbor : TilingRule.Neighbor
    {
        public const int IsOcean = 3;
        public const int IsNotOcean = 4;
        public const int IsCoast = 5;
        public const int IsNotCoast = 6;
    }

    /// <summary>
    /// Checks if there is a match given the neighbor matching rule and a Tile.
    /// </summary>
    /// <param name="neighbor">Neighbor matching rule.</param>
    /// <param name="other">Tile to match.</param>
    /// <returns>True if there is a match, False if not.</returns>
    public override bool RuleMatch(int neighbor, TileBase tile)
    {
        var other = tile as CoastHexagonTile;
        switch (neighbor)
        {
            case Neighbor.IsOcean:
                return other && other.isOcean;
            case Neighbor.IsNotOcean:
                return other && !other.isOcean;
            case Neighbor.IsCoast:
                return other && other.isCoast;
            case Neighbor.IsNotCoast:
                return other && !other.isCoast;
        }
        return base.RuleMatch(neighbor, tile);
    }
}

编辑:不幸的是,似乎并非所有规则图块都出于某些原因而遵守规则。我正在以编程方式在一张大地图上设置每个图块,我想知道这是否基本上是原因。

其他编辑:好的,我发现为了正确渲染图块,需要调用Tilemap.RefreshAllTiles()方法。我认为只有在像我一样在运行时移动瓷砖并以编程方式进行设置时,这才是正确的。

相关问题