PuzzleGame/PuzzleGameProject/Assets/Scripts/DungeonGenerator/DungeonMapLoader.cs

84 lines
3.4 KiB
C#

using System;
using System.Collections.Generic;
using UnityEngine;
using DungeonMapGenerator;
using Unity.VisualScripting;
using Object = UnityEngine.Object;
namespace DungeonGenerator
{
public class DungeonMapLoader
{
private const string ROOMS_PARENT = "RoomsParent";
private const string MONSTER_ROOM = "Rooms\\MonsterRoom";
private const string BOSS_ROOM = "Rooms\\BossRoom";
private const string NORMAL_ROOM = "Rooms\\Room";
private Dictionary<int, GameObject> _roomIdToGameObject = new Dictionary<int, GameObject>();
public void AddDungeonRoomsToGameObject(GameObject gameObject, string pathToDungeonFile)
{
DungeonMap map = DungeonMapSerializer.DeserializeFromFile(pathToDungeonFile);
GameObject bossRoomPrefab = Resources.Load<GameObject>(BOSS_ROOM);
GameObject monsterRoomPrefab = Resources.Load<GameObject>(MONSTER_ROOM);
GameObject normalRoomPrefab = Resources.Load<GameObject>(NORMAL_ROOM);
GameObject bossRoomGO = Object.Instantiate(bossRoomPrefab,
ConvertToUnityPosition(map.GetBossRoom().GetCenterOfRoom(), map.Width, map.Height),
Quaternion.identity,
gameObject.transform);
_roomIdToGameObject[map.GetBossRoom().Id] = bossRoomGO;
foreach (var monsterRoom in map.GetMonsterRooms())
{
GameObject monsterRoomGO = Object.Instantiate(
monsterRoomPrefab,
ConvertToUnityPosition(monsterRoom.GetCenterOfRoom(), map.Width, map.Height),
Quaternion.identity,
gameObject.transform);
_roomIdToGameObject[monsterRoom.Id] = monsterRoomGO;
}
foreach (var normalRoom in map.GetNormalRooms())
{
GameObject normalRoomGO = Object.Instantiate(
normalRoomPrefab,
ConvertToUnityPosition(normalRoom.GetCenterOfRoom(), map.Width, map.Height),
Quaternion.identity,
gameObject.transform);
_roomIdToGameObject[normalRoom.Id] = normalRoomGO;
}
foreach (var entranceRoom in map.GetEntranceRooms())
{
GameObject entranceRoomGO = Object.Instantiate(
normalRoomPrefab,
ConvertToUnityPosition(entranceRoom.GetCenterOfRoom(), map.Width, map.Height),
Quaternion.identity,
gameObject.transform);
entranceRoomGO.GetComponent<Room>().IsEntrance = true;
_roomIdToGameObject[entranceRoom.Id] = entranceRoomGO;
}
foreach (var mapRoom in map.GetAllRooms())
{
HashSet<int> adjacentRoomsIds = mapRoom.GetAdjacentRoomIds();
Room roomComponent = _roomIdToGameObject[mapRoom.Id].GetComponent<Room>();
foreach (var id in adjacentRoomsIds)
{
roomComponent.AdjacentRooms.Add(_roomIdToGameObject[id]);
}
}
}
private Vector3 ConvertToUnityPosition(Point dungeonPosition, int mapWidth, int mapHeight)
{
float newX = (dungeonPosition.X - (mapWidth / 2f)) / 2;
float newY = -(dungeonPosition.Y - (mapHeight / 2f)) / 2;
return new Vector3(newX, newY, 0f);
}
}
}