首页 > 解决方案 > 如何从 Unity 中的 Animated Tile/Tilemap.animationFrameRate 获取当前帧

问题描述

我正在统一使用 2dExtras 中的瓷砖地图和动画瓷砖。

我的图块有 6 帧,速度 = 2f,我的图块帧率为 2。

放置的新图块始终从第 1 帧开始,然后立即跳转到已放置的其他图块的当前帧,图块地图使每个图块保持相同的速度,这可以按我的意愿工作。

但是,我希望新放置的图块从其他图块当前所在的帧开始,(而不是放置从第 1 帧跳到第 4 帧的图块)我希望新图块从第 4 帧开始

我已经找到了如何选择我想要开始的帧,但是我无法检索动画当前所在的帧,所以我想知道如何准确访问给定瓷砖地图的当前动画帧(或给定图块,我可以创建一个虚拟图块并从中读取信息,如何获取动画图块的当前帧?)

动画 tilemaps 功能似乎缺少检索此信息的功能,当我尝试 tilemap.getsprite 它总是返回序列的第一帧(不返回当前显示的精灵),并且似乎没有任何方法从 tilemap.animationFrameRate 轮询信息。

我认为另一种方法是设置一个时钟并将其与动画的速率同步,但由于我无法获得确切的帧速率持续时间,时钟最终会不同步。

任何帮助,将不胜感激!

标签: unity3d

解决方案


我找到了解决这个问题的方法。但这不是 100% 的保险。首先,我使用了 SuperTile2Unity。这似乎不是重点。

private void LateUpdate()
{
    // I use this variable to monitor the run time of the game
    this.totalTime += Time.deltaTime;
}

private void func()
{
    // ...
    TileBase[] currentTiles = tilemap.GetTilesBlock(new BoundsInt(new Vector3Int(0, 0, 0), new Vector3Int(x, y, 1)));

    Dictionary<string, Sprite> tempTiles = new Dictionary<string, Sprite>();
    //I use SuperTiled2Unity. But it doesn't matter, the point is to find animated tile
    foreach (SuperTiled2Unity.SuperTile tile in currentTiles)
    {
        if (tile == null)
        {
            continue;
        }

        if (tile.m_AnimationSprites.Length > 1 && !tempTiles.ContainsKey(tile.name))
        {
            // find animated tile current frame
            // You can easily find that the way SuperTile2Unity is used to process animation is to generate a sprite array based on the time of each frame set by Tiled animation and the value of AnimationFrameRate parameter.
            // The length of array is always n times of AnimationFrameRate. You can debug to find this.
            tempTiles.Add(tile.name, tile.m_AnimationSprites[GetProbablyFrameIndex(tile.m_AnimationSprites.Length)]);
        }
    }
    //...
}

private int GetProbablyFrameIndex(int totalFrame)
{
    //According to the total running time and the total length of  tile animation and AnimationFrameRate, the approximate frame index can be deduced.
    int overFrameTime = (int)(totalTime * animationFrameRate);

    return overFrameTime % totalFrame;
}

我做了一些测试。至少在 30 分钟内,动画不会出现偏差,但可能存在临界值。如果超过临界时间,可能会出现错误。这取决于 AnimationFrameRate 的大小和 totalTime 的累积方式。毕竟,我们不知道 unity 何时以及如何处理animatedTile。


推荐阅读