うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】2次元タイルマップ空間で中心から特定の距離の座標一覧を取得する

以下の図のように中心から指定した距離のマス座標一覧を取得するスクリプト

例えば、2の場合は (0, 2), (0, -2), (1, 1), (-1, 1), (1, -1), (-1, -1), (2, 0), (-2, 0)になる

f:id:hacchi_man:20210129005422p:plain

public static class TileMapUtil
{
    public static List<Vector2Int> GetPositions(int distance)
    {
        var ret = new List<Vector2Int>();
        for (var x = 0; x <= distance; x++)
        {
            var y = distance - x;
            ret.Add(new Vector2Int(x, y));
            if (x > 0)
                ret.Add(new Vector2Int(-x, y));

            if (y > 0)
                ret.Add(new Vector2Int(x, -y));

            if (x > 0 && y > 0)
                ret.Add(new Vector2Int(-x, -y));
        }
 
        return ret;
    }
}
// 3の距離の座標一覧を取得する
MapUtil.GetPositions(3); // (0, 3), (0, -3), (1, 2), (-1, 2), (1, -2), (-1, -2), (2, 1), (-2, 1), (2, -1), (-2, -1), (3, 0), (-3, 0)