c# - Unity 2D Tilemap 自定义六角规则瓦片

标签 c# unity3d

我正在寻找一种方法来创建一种新型的六边形规则图 block 来完成一些相当简单和具体的事情。我想创建一个六边形规则图 block ,该图 block 能够根据与它相邻的其他类型的六角形图 block 自动选择 Sprite 。默认的六边形规则图 block 允许您在给定图 block 的每一侧以相同类型的图 block 作为边界时指定 Sprite ,但这对于我的目的来说是不够的。

我最终想要的是创建一个海岸图 block ,它将检测哪些边与海洋图 block 接壤,并根据它选择正确的六边形 Sprite 。类似这样的东西,但能够指定海洋瓦片,而不仅仅是绿色箭头指示的相同瓦片类型:

Coast tile example

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

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

最佳答案

好的,经过深入的谷歌搜索和反复试验后,我明白了这一点。我所需要的只是这个覆盖 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);
    }
}

编辑:不幸的是,由于某种原因,似乎并非所有规则板 block 都遵守规则。我在大 map 上以编程方式设置每个图 block ,我想知道这是否是根本原因。

其他编辑:好的,我发现为了正确呈现图 block ,需要调用 Tilemap.RefreshAllTiles() 方法。我认为只有在运行时四处移动并以编程方式设置磁贴时才会出现这种情况。

关于c# - Unity 2D Tilemap 自定义六角规则瓦片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60824529/

相关文章:

c# - 泛型 <T> Unity C#

c# - 命名空间外的私有(private)类

c# - "The remote certificate is invalid according to the validation procedure"使用 HttpClient

c# - Xml 序列化在简单类上因 NullReferenceException 而失败

android-activity - 在 Unity Android 插件中包含自定义 Activity (不覆盖 UnityPlayerActivity)?

c# - 我怎样才能阻止角色二段跳?

c# - 处理程序映射的嵌套 WebAPI 问题(继承问题?)

c# - C# 新手 - 尝试编写代码来执行简单的功能

c# - 检查 T 是否实现接口(interface)并在填充接口(interface)属性后返回 T

c# - 如何在Unity 3D中使音频静音?