メインコンテンツへスキップ
見出し画像

【Unity ローグライク制作#5】ゲームビューにタイルを表示しよう

    初めての方はこちら:#1 プロジェクト作成と素材のインポート
    ◀前の記事:#4 部屋をつなぐ通路を作ろう
    ▶次の記事:#6 プレイヤーをランダムで部屋に配置しよう

    前回までは、二次元配列を使って、「0 = 壁」「1 = 床」という基準で配置を決めていきました。
    今回は、そのデータをもとに、ゲームビュー上に表示をさせてみましょう。

    手順①:タイルマップを準備する

    まずは、タイルマップを準備しましょう。
    タイルマップは、以下の2種類を準備します。
    ①壁用:歩けない
    ②床用:歩ける

    それでは作成していきましょう。
    2D Object > Tilemap > Rectangularを選択してください。

    画像

    タイルマップ名は、「WallTilemap」と「FloorTilemap」としましょう。

    画像

    WallTilemapに「Tilemap Collider 2D」をアタッチしましょう。

    画像

    次に、レイヤーを作ります。
    WallTilemapのLayerのプルダウンから「Add Layer」を選択します。

    画像

    LayersにWallを追加(記載)します。

    画像

    WallTilemapのLayerにWallを設定します。

    画像
    画像

    手順②:タイルの設定プログラムを作る

    次に、タイルを配置するプログラムを書いていきましょう。
    以下のように記載してください。

    
    using System.Collections.Generic;
    using UnityEngine;
    //------- 追加 Start --------//
    using UnityEngine.Tilemaps;
    //------- 追加 End --------//
    
    
    public class DungeonGenerator : MonoBehaviour
    {
        //------- 追加 Start --------//
        [SerializeField] private TileBase wallTile;  // 壁のスプライト
        [SerializeField] private TileBase floorTile; // 床のスプライト
        //------- 追加 End --------//
    
        // マップの大きさを設定
        [SerializeField] private int mapWidth = 40;
        [SerializeField] private int mapHeight = 25;
    
        // 部屋の数
        [SerializeField] private int roomCount = 5;
    
        // 部屋サイズの範囲を設定
        [SerializeField] private int minRoomSize = 4;
        [SerializeField] private int maxRoomSize = 8;
    
        [SerializeField] private int maxRoomCreateCount = 10; // 部屋作成の最大試行回数
        
        // マップデータ(二次元配列)
        private int[,] map;
    
        // 部屋の中心点を保存
        private readonly List<Vector2Int> roomCenters = new List<Vector2Int>();
        
        //------- 追加 Start --------//
        // タイルマップ用の変数
        [SerializeField] private Tilemap wallTilemap;
        [SerializeField] private Tilemap floorTilemap;
        //------- 追加 End --------//
    
    
        void Start()
        {
            MapGenerate();
            PrintMapToConsole();
        }
    
        private void MapGenerate()
        {
            // マップ初期化
            map = new int[mapWidth, mapHeight];
            
            // 中心点のリストを初期化
            roomCenters.Clear();
            
            for (int i = 0; i < roomCount; i++)
            {
                CreateRoom();
            }
    
            // 通路作成
            ConnectRoomsInOrder();
    
            // タイルの表示
            //------- 追加 Start --------//
            InstantiateTile();
            //------- 追加 End --------//
        }
    
        private void CreateRoom()
        {
            for(int i = 0; i < maxRoomCreateCount; i++)
            {
            
                // 部屋の大きさを決める
                int roomWidth = Random.Range(minRoomSize, maxRoomSize + 1);
                int roomHeight = Random.Range(minRoomSize, maxRoomSize + 1);
    
                // 部屋の位置を決める
                int roomX = Random.Range(1, mapWidth - roomWidth - 1);
                int roomY = Random.Range(1, mapHeight - roomHeight - 1);
    
                // 部屋が重なっていないかチェック
                if (IsOverlapping(roomX, roomY, roomWidth, roomHeight)) continue;
                
                for (int x = roomX; x < roomX + roomWidth; x++)
                {
                    for (int y = roomY; y < roomY + roomHeight; y++)
                    {
                        map[x, y] = 1; // 床を1で表現
                    }
                }
    
                // 中心点を保存
                int currentX = roomX + roomWidth / 2;
                int currentY = roomY + roomHeight / 2;
                roomCenters.Add(new Vector2Int(currentX, currentY));
    
                return; // 部屋作成成功で終了
            }
        }
    
        private bool IsOverlapping(int roomX, int roomY, int roomWidth, int roomHeight)
        {
            for(int x = roomX -1; x < roomX + roomWidth + 1; x++)
            {
                for(int y = roomY - 1; y < roomY + roomHeight + 1; y++)
                {
                    // マップの範囲外をチェック
                    if (x < 0 || x >= mapWidth || y < 0 || y >= mapHeight) continue;
    
                    // 部屋の範囲内に既に床があるかチェック
                    if (map[x, y] == 1)
                    {
                        return true; // 重なっている
                    }
                }
            }
            return false; // 重なっていない
        }
    
        // 部屋を生成順でつなぐ
        private void ConnectRoomsInOrder()
        {
            // 部屋が1つだけだったら、処理しない
            if (roomCenters.Count < 2) return;
    
            for (int i = 0; i < roomCenters.Count - 1; i++)
            {
                Vector2Int fromRoom = roomCenters[i];
                Vector2Int toRoom = roomCenters[i + 1];
                CarveCorridorL(fromRoom, toRoom);
            }
        }
    
        private void CarveCorridorL(Vector2Int from, Vector2Int to)
        {
            // x軸に通路を作成
            // from = 基準点からto = 目的地は左右どちら側に存在するかを確認して「1 = 床」を接地
            int xStep = from.x <= to.x ? 1 : -1;
            for (int x = from.x; x != to.x; x += xStep)
            {
                map[x, from.y] = 1;
            }
    
            // L字の曲がり角も床を置く
            map[to.x, from.y] = 1;
    
            int yStep = from.y <= to.y ? 1 : -1;
            for (int y = from.y; y != to.y; y += yStep)
            {
                map[to.x, y] = 1;
            }
    
            // 目的地にも床を置く
            map[to.x, to.y] = 1;
        }
    
        //------- 追加 Start --------//
        // 二次元配列(map)の内容に基づいてタイルを配置するメソッド
        private void InstantiateTile()
        {
            // タイルマップをクリア (再生成するので必要)
            wallTilemap.ClearAllTiles();
            floorTilemap.ClearAllTiles();
    
            for (int x = 0; x < mapWidth; x++)
            {
                for(int y = 0; y < mapHeight; y++)
                {
                    Vector3Int pos = new Vector3Int(x, y, 0);
    
                    if (map[x, y] == 1)
                    {
                        // 床タイルを配置
                        floorTilemap.SetTile(pos, floorTile);
                    }
                    else
                    {
                        // 壁タイルを配置
                        wallTilemap.SetTile(pos, wallTile);
                    }
                }
            }
        }
        //------- 追加 End --------//
    
        public void PrintMapToConsole()
        {
            for(int y = mapHeight - 1; y >= 0; y--)
            {
                string line = "";
                for (int x = 0; x < mapWidth; x++)
                {
                    line += map[x, y] == 1 ? "■" : "□";
                }
                Debug.Log(line);
            }
        }
    
    }

    手順③:タイルを作成する

    次は、壁と床のタイルを作成します。
    Create > 2D > Tiles > Rule Tileを選択してください。

    画像

    作成したオブジェクトはWallと名称変更しました。
    Default Spriteの中に壁の画像を設定します。

    画像

    床(floor)も同様の手順で画像を設定します。

    手順④:DungeonGeneratorのinspectorの設定を行う

    以下の画像を参考に、Wall Tile、Floor Tile、Wall Tilemap、Floor Tilemapを設定してください。

    画像

    手順⑤:動作確認

    それでは動作確認をしてみましょう。
    以下の画像のようにタイルが設定されていれば成功です。

    画像

    今回はここまでです。
    次回は、自動生成したマップに、プレイヤーをランダムで配置する処理を作成します。

    前の記事:【Unity ローグライク制作#4】部屋をつなぐ通路を作ろう

    次の記事:【Unity ローグライク制作#6】プレイヤーをランダムで部屋に配置しよう

    あなたへのおすすめ