63 lines
2.2 KiB
C#
63 lines
2.2 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using Unity.VisualScripting;
|
|
using UnityEngine;
|
|
|
|
public class MapBuilding : MonoBehaviour
|
|
{
|
|
[Tooltip("地图SO数据")] public HomeMapSO SO_HomeMap;
|
|
[Tooltip("坐标起始点")] public GameObject startPositionObject;
|
|
[Tooltip("测试房间预制体")] public GameObject testRoomPrefab;
|
|
public int cellSize = 2;
|
|
|
|
// private function
|
|
private void create_direction_grid()
|
|
{
|
|
// 需要创建格子的坐标
|
|
List<Vector2Int> neighbor_position_list = new List<Vector2Int>();
|
|
// 方向列表:上下左右
|
|
List<Vector2Int> direction_list = new List<Vector2Int>
|
|
{
|
|
new Vector2Int(1, 0), // 右
|
|
new Vector2Int(0, 1), // 上
|
|
new Vector2Int(-1, 0), // 左
|
|
new Vector2Int(0, -1) // 下
|
|
};
|
|
// 收集已有房间的格子坐标
|
|
List<Vector2Int> has_room_position_list = SO_HomeMap.get_position_by_has_room();
|
|
|
|
// 从已有房间的坐标推导出方向坐标列表
|
|
foreach (var hr_position in has_room_position_list)
|
|
{
|
|
foreach (var dir_position in direction_list)
|
|
{
|
|
var neighbor_position = hr_position + dir_position;
|
|
if (neighbor_position.x >= 1) continue; // 地面上的空间不生成
|
|
if (!has_room_position_list.Contains(neighbor_position))
|
|
{
|
|
neighbor_position_list.Add(neighbor_position);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 生成四周的空间预制件
|
|
foreach (var _position in neighbor_position_list)
|
|
{
|
|
GameObject room = Instantiate<GameObject>(
|
|
testRoomPrefab,
|
|
position: (startPositionObject.transform.position +
|
|
new Vector3(_position.y, _position.x, 0) * cellSize),
|
|
rotation: Quaternion.identity);
|
|
Transform neighbor_container = startPositionObject.transform.Find("neighborContainer");
|
|
room.name = $"Cell_{_position.x}.{_position.y}";
|
|
room.transform.SetParent(neighbor_container);
|
|
}
|
|
}
|
|
|
|
|
|
// UI function
|
|
public void m_button_start_build()
|
|
{
|
|
create_direction_grid();
|
|
}
|
|
} |