Есть классы, есть двери, есть механика вселения, свага есть
This commit is contained in:
1 parent
2ae795c30a
commit
0f9a539460
69 files changed
+3960
-299
No files matched your search
@@ -0,0 +1,163 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace _Project.Scripts.LevelGenerating
|
||||
{
|
||||
// =====================================================================
|
||||
// Контроллер ДВОЙНОЙ двери (левая + правая створка).
|
||||
// Сейчас сам создаёт Trigger-коллайдер и открывает створки при подходе игрока.
|
||||
// Позже оркестратор сможет управлять дверью через Open(), Close() и SetLocked().
|
||||
// =====================================================================
|
||||
public class DoorController : MonoBehaviour
|
||||
{
|
||||
public enum OpenType
|
||||
{
|
||||
Sliding, // раздвижная: левая створка едет влево (-X), правая вправо (+X)
|
||||
Rotating // распашная: створки поворачиваются на петлях в разные стороны
|
||||
}
|
||||
|
||||
[Header("Створки двойной двери")]
|
||||
[Tooltip("Левая створка двери")]
|
||||
[SerializeField] private Transform leftWing;
|
||||
[Tooltip("Правая створка двери")]
|
||||
[SerializeField] private Transform rightWing;
|
||||
|
||||
[Header("Режим и скорость открытия")]
|
||||
[SerializeField] private OpenType openType = OpenType.Sliding;
|
||||
[SerializeField] private float openSpeed = 3.5f;
|
||||
|
||||
[Tooltip("Для Sliding: на сколько метров каждая створка отъезжает в свою сторону по локальной оси X")]
|
||||
[SerializeField] private float slideDistance = 1f;
|
||||
|
||||
[Tooltip("Для Rotating: на какой угол (в градусах) распахивается каждая створка")]
|
||||
[SerializeField] private float openAngle = 90f;
|
||||
|
||||
[Header("Авто-открытие (временно, до оркестратора)")]
|
||||
[Tooltip("Выключи, когда дверями начнёт управлять оркестратор")]
|
||||
[SerializeField] private bool autoOpenNearPlayer = true;
|
||||
[SerializeField] private string playerTag = "Player";
|
||||
[SerializeField] private Vector3 triggerSize = new Vector3(3.5f, 2.5f, 4.5f);
|
||||
|
||||
public bool IsOpen { get; private set; }
|
||||
public bool IsLocked { get; private set; }
|
||||
|
||||
private Vector3 _leftClosedPos, _rightClosedPos;
|
||||
private Quaternion _leftClosedRot, _rightClosedRot;
|
||||
private int _playersInsideTrigger;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
// Если створки не назначены в инспекторе, пробуем найти первые два дочерних объекта автоматически
|
||||
if (leftWing == null && transform.childCount > 0) leftWing = transform.GetChild(0);
|
||||
if (rightWing == null && transform.childCount > 1) rightWing = transform.GetChild(1);
|
||||
|
||||
if (leftWing != null)
|
||||
{
|
||||
_leftClosedPos = leftWing.localPosition;
|
||||
_leftClosedRot = leftWing.localRotation;
|
||||
}
|
||||
|
||||
if (rightWing != null)
|
||||
{
|
||||
_rightClosedPos = rightWing.localPosition;
|
||||
_rightClosedRot = rightWing.localRotation;
|
||||
}
|
||||
|
||||
if (autoOpenNearPlayer)
|
||||
{
|
||||
SetupProximityTrigger();
|
||||
}
|
||||
}
|
||||
|
||||
private void SetupProximityTrigger()
|
||||
{
|
||||
var col = GetComponent<BoxCollider>();
|
||||
if (col == null || !col.isTrigger)
|
||||
{
|
||||
var trigger = gameObject.AddComponent<BoxCollider>();
|
||||
trigger.isTrigger = true;
|
||||
trigger.size = triggerSize;
|
||||
trigger.center = new Vector3(0f, triggerSize.y / 2f, 0f);
|
||||
}
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (openType == OpenType.Sliding)
|
||||
{
|
||||
// Левая створка едет в -X, правая в +X
|
||||
if (leftWing != null)
|
||||
{
|
||||
Vector3 targetL = IsOpen ? _leftClosedPos + Vector3.left * slideDistance : _leftClosedPos;
|
||||
leftWing.localPosition = Vector3.MoveTowards(
|
||||
leftWing.localPosition, targetL, openSpeed * Time.deltaTime);
|
||||
}
|
||||
|
||||
if (rightWing != null)
|
||||
{
|
||||
Vector3 targetR = IsOpen ? _rightClosedPos + Vector3.right * slideDistance : _rightClosedPos;
|
||||
rightWing.localPosition = Vector3.MoveTowards(
|
||||
rightWing.localPosition, targetR, openSpeed * Time.deltaTime);
|
||||
}
|
||||
}
|
||||
else // Rotating
|
||||
{
|
||||
float rotSpeed = openSpeed * 60f * Time.deltaTime;
|
||||
|
||||
if (leftWing != null)
|
||||
{
|
||||
Quaternion targetL = IsOpen
|
||||
? _leftClosedRot * Quaternion.Euler(0f, -openAngle, 0f)
|
||||
: _leftClosedRot;
|
||||
leftWing.localRotation = Quaternion.RotateTowards(leftWing.localRotation, targetL, rotSpeed);
|
||||
}
|
||||
|
||||
if (rightWing != null)
|
||||
{
|
||||
Quaternion targetR = IsOpen
|
||||
? _rightClosedRot * Quaternion.Euler(0f, openAngle, 0f)
|
||||
: _rightClosedRot;
|
||||
rightWing.localRotation = Quaternion.RotateTowards(rightWing.localRotation, targetR, rotSpeed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- API для будущего Оркестратора ----------
|
||||
|
||||
public void Open()
|
||||
{
|
||||
if (IsLocked) return;
|
||||
IsOpen = true;
|
||||
}
|
||||
|
||||
public void Close() => IsOpen = false;
|
||||
|
||||
public void SetLocked(bool locked)
|
||||
{
|
||||
IsLocked = locked;
|
||||
if (locked) Close();
|
||||
}
|
||||
|
||||
// ---------- Триггер приближения игрока ----------
|
||||
|
||||
private void OnTriggerEnter(Collider other)
|
||||
{
|
||||
if (!autoOpenNearPlayer || !IsPlayer(other)) return;
|
||||
_playersInsideTrigger++;
|
||||
Open();
|
||||
}
|
||||
|
||||
private void OnTriggerExit(Collider other)
|
||||
{
|
||||
if (!autoOpenNearPlayer || !IsPlayer(other)) return;
|
||||
_playersInsideTrigger = Mathf.Max(0, _playersInsideTrigger - 1);
|
||||
if (_playersInsideTrigger == 0) Close();
|
||||
}
|
||||
|
||||
private bool IsPlayer(Collider col)
|
||||
{
|
||||
if (col.CompareTag(playerTag)) return true;
|
||||
if (col.transform.root.CompareTag(playerTag)) return true;
|
||||
return col.name.Contains("Player") || col.transform.root.name.Contains("Player");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5850387c1f4a4054bb33e19563ddb215
|
||||
timeCreated: 1792595120
|
||||
@@ -5,54 +5,38 @@ namespace _Project.Scripts.LevelGenerating
|
||||
{
|
||||
public enum FloorKind
|
||||
{
|
||||
Generated, // обычный этаж: раскладка -> роли -> стены -> наполнение
|
||||
Special // готовая локация (крыша с боссом), собрана вручную, генератор не нужен
|
||||
Generated,
|
||||
Special
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Данные ОДНОГО этажа. Заменяет статический LevelManager.Rooms.
|
||||
// Все координаты и размеры комнат - в МОДУЛЯХ (1 модуль = 0.5 м), см. LevelGrid.
|
||||
//
|
||||
// НЕ ЗАБЫТЬ:
|
||||
// - Для сохранения в файл этот класс НЕ годится напрямую: Room использует свойства,
|
||||
// которые JsonUtility не сериализует. Для диска нужны отдельные структуры (FloorSave)
|
||||
// с публичными полями, а FloorData остаётся рабочим объектом генерации.
|
||||
// - Parent / CorridorOf живут в WallsGenerator (нужны только при генерации раскладки).
|
||||
// =====================================================================
|
||||
public class FloorData
|
||||
{
|
||||
public int Index; // номер этажа (0-based)
|
||||
public int Index;
|
||||
public FloorKind Kind;
|
||||
public int Seed; // пока не используется (сид "пох"), поле на будущее
|
||||
public string SpecialId; // для Special: id префаба локации, например "BossRoof"
|
||||
public int SizeModules; // сторона карты этажа в модулях (для Generated)
|
||||
public int Seed;
|
||||
public string SpecialId;
|
||||
public int SizeModules;
|
||||
|
||||
public readonly List<Room> Rooms = new List<Room>();
|
||||
public readonly Dictionary<Room, int> Depth = new Dictionary<Room, int>();
|
||||
|
||||
// Отрезки стен (заполняет ShellBuilder.Build)
|
||||
// Отрезки стен и дверные проёмы (заполняет ShellBuilder.Build)
|
||||
public readonly List<WallRun> Walls = new List<WallRun>();
|
||||
public readonly List<Doorway> Doorways = new List<Doorway>();
|
||||
|
||||
public Room Start; // стартовая комната (вход с предыдущего этажа)
|
||||
public Room Lift; // комната с лифтом (выход на следующий этаж)
|
||||
public Room Start;
|
||||
public Room Lift;
|
||||
|
||||
// ---------- Выборки ----------
|
||||
|
||||
public IEnumerable<Room> Corridors => Rooms.Where(r => r.rt == RoomType.Corridor);
|
||||
|
||||
// Всё, кроме коридоров (старт, лифт и обычные комнаты)
|
||||
public IEnumerable<Room> PlayableRooms => Rooms.Where(r => r.rt != RoomType.Corridor);
|
||||
|
||||
// Комнаты, которым ещё не назначена роль
|
||||
public IEnumerable<Room> UnassignedRooms => Rooms.Where(r => r.rt == RoomType.Undefined);
|
||||
|
||||
public IEnumerable<Room> OfType(RoomType type) => Rooms.Where(r => r.rt == type);
|
||||
|
||||
public int GetDepth(Room room) => Depth.TryGetValue(room, out int d) ? d : -1;
|
||||
|
||||
// ---------- Изменение ----------
|
||||
|
||||
// Добавить комнату (не коридор) вместе с глубиной
|
||||
public void AddRoom(Room room, int depth)
|
||||
{
|
||||
Rooms.Add(room);
|
||||
@@ -62,7 +46,6 @@ namespace _Project.Scripts.LevelGenerating
|
||||
else if (room.rt == RoomType.Lift) Lift = room;
|
||||
}
|
||||
|
||||
// Коридоры глубины не имеют
|
||||
public void AddCorridor(Room corridor) => Rooms.Add(corridor);
|
||||
|
||||
public void Remove(Room room)
|
||||
@@ -78,6 +61,7 @@ namespace _Project.Scripts.LevelGenerating
|
||||
Rooms.Clear();
|
||||
Depth.Clear();
|
||||
Walls.Clear();
|
||||
Doorways.Clear();
|
||||
Start = null;
|
||||
Lift = null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using _Project.Scripts.PlayerUtils;
|
||||
using UnityEngine;
|
||||
|
||||
namespace _Project.Scripts.LevelGenerating
|
||||
{
|
||||
[Serializable]
|
||||
public class EnemySpawnEntry
|
||||
{
|
||||
public BodyClass enemyClass = BodyClass.Trooper;
|
||||
[Tooltip("Кастомный префаб этого класса. Если пусто — возьмётся общий префаб или создастся капсула.")]
|
||||
public GameObject customPrefab;
|
||||
[Tooltip("Вес (шанс) выбора этого класса относительно других в списке")]
|
||||
[Min(1f)] public float weight = 10f;
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Конфиг спавна врагов для темы комнаты (RoomTheme).
|
||||
// Создаётся: ПКМ -> Create -> Level -> Room Enemy Spawn Config.
|
||||
// =====================================================================
|
||||
[CreateAssetMenu(menuName = "Level/Room Enemy Spawn Config", fileName = "RoomEnemySpawnConfig")]
|
||||
public class RoomEnemySpawnConfig : ScriptableObject
|
||||
{
|
||||
[Header("Количество врагов в комнате")]
|
||||
[Min(0)] public int minEnemies = 2;
|
||||
[Min(0)] public int maxEnemies = 4;
|
||||
[Tooltip("Добавлять +1 врага за каждые N кв. метров площади (0 = не зависит от размера комнаты)")]
|
||||
[Min(0f)] public float extraEnemyPerArea = 35f;
|
||||
[Tooltip("Отступ от стен при спавне врагов (в метрах)")]
|
||||
[Min(1f)] public float wallMargin = 2f;
|
||||
|
||||
[Header("Префаб по умолчанию")]
|
||||
[Tooltip("Если не назначен — генератор сам соберёт работающую капсулу с EnemyAI!")]
|
||||
public GameObject defaultEnemyPrefab;
|
||||
|
||||
[Header("Пул классов для этой комнаты")]
|
||||
public List<EnemySpawnEntry> enemyPool = new List<EnemySpawnEntry>
|
||||
{
|
||||
new EnemySpawnEntry { enemyClass = BodyClass.Scout, weight = 25f },
|
||||
new EnemySpawnEntry { enemyClass = BodyClass.Trooper, weight = 45f },
|
||||
new EnemySpawnEntry { enemyClass = BodyClass.Juggernaut, weight = 15f },
|
||||
new EnemySpawnEntry { enemyClass = BodyClass.Sniper, weight = 15f }
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 543780e1d0e842ca96364a1f94696107
|
||||
timeCreated: 1792605497
|
||||
@@ -1,21 +1,15 @@
|
||||
using System.Collections.Generic;
|
||||
using _Project.Scripts.PlayerUtils;
|
||||
using UnityEngine;
|
||||
|
||||
namespace _Project.Scripts.LevelGenerating
|
||||
{
|
||||
// =====================================================================
|
||||
// Генератор, который оформляет одну комнату после того, как построены её меши.
|
||||
// Специальные комнаты (лифт, старт) получают свои реализации,
|
||||
// обычные - универсальный ThemedRoomGenerator.
|
||||
// =====================================================================
|
||||
public interface IRoomGenerator
|
||||
{
|
||||
bool Supports(Room room);
|
||||
void Generate(RoomView view, FloorData floor, RoomTheme theme);
|
||||
}
|
||||
|
||||
// Универсальный генератор: материалы из темы и сетка светильников под потолком.
|
||||
// Позже сюда добавится расстановка предметов по правилам темы.
|
||||
public class ThemedRoomGenerator : IRoomGenerator
|
||||
{
|
||||
public bool Supports(Room room) => true;
|
||||
@@ -35,17 +29,21 @@ namespace _Project.Scripts.LevelGenerating
|
||||
if (theme.lightConfig != null)
|
||||
{
|
||||
CreateLights(view, theme.lightConfig);
|
||||
RuntimeRoomLightmapBaker.BakeRoom(view, theme.lightConfig); // <-- ЗАПЕКАЕМ СВЕТ НА ЛЕТУ!
|
||||
RuntimeRoomLightmapBaker.BakeRoom(view, theme.lightConfig);
|
||||
}
|
||||
|
||||
if (theme.spawnEnemies)
|
||||
{
|
||||
SpawnEnemies(view, floor, theme.enemyConfig);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ApplyMaterial(List<Renderer> renderers, Material mat)
|
||||
{
|
||||
if (mat == null) return; // остаётся материал префаба
|
||||
if (mat == null) return;
|
||||
foreach (var r in renderers) r.sharedMaterial = mat;
|
||||
}
|
||||
|
||||
// Сетка светильников: спавнит префаб из RoomLightConfig и применяет параметры
|
||||
private static void CreateLights(RoomView view, RoomLightConfig config)
|
||||
{
|
||||
Vector3 size = view.SizeMeters;
|
||||
@@ -66,8 +64,8 @@ namespace _Project.Scripts.LevelGenerating
|
||||
for (int iz = 0; iz < nz; iz++)
|
||||
{
|
||||
Vector3 pos = origin + new Vector3(
|
||||
(ix + 0.5f) / nx * size.x,
|
||||
y,
|
||||
(ix + 0.5f) / nx * size.x,
|
||||
y,
|
||||
(iz + 0.5f) / nz * size.z);
|
||||
|
||||
GameObject lightGo;
|
||||
@@ -79,7 +77,6 @@ namespace _Project.Scripts.LevelGenerating
|
||||
}
|
||||
else
|
||||
{
|
||||
// Запасной вариант, если префаб забыли назначить в SO
|
||||
lightGo = new GameObject($"FallbackLight_{ix}_{iz}");
|
||||
lightGo.transform.SetParent(lightsRoot, false);
|
||||
lightGo.transform.SetPositionAndRotation(pos, rot);
|
||||
@@ -87,7 +84,6 @@ namespace _Project.Scripts.LevelGenerating
|
||||
fallbackLight.type = LightType.Point;
|
||||
}
|
||||
|
||||
// Если включена перезапись параметров (или сработал запасной вариант без префаба)
|
||||
if (config.overrideLightParameters || config.lightPrefab == null)
|
||||
{
|
||||
var lights = lightGo.GetComponentsInChildren<Light>(true);
|
||||
@@ -102,5 +98,223 @@ namespace _Project.Scripts.LevelGenerating
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- ГЕНЕРАЦИЯ ВРАГОВ В КОМНАТЕ ----------
|
||||
|
||||
private static void SpawnEnemies(RoomView view, FloorData floor, RoomEnemySpawnConfig config)
|
||||
{
|
||||
RoomType rt = view.Data.rt;
|
||||
|
||||
// В коридорах и в лифте врагов не спавним
|
||||
if (rt == RoomType.Corridor || rt == RoomType.Lift || rt == RoomType.Undefined)
|
||||
return;
|
||||
|
||||
Vector3 size = view.SizeMeters;
|
||||
Vector3 origin = view.OriginMeters;
|
||||
float area = size.x * size.z;
|
||||
|
||||
int count;
|
||||
if (rt == RoomType.Start)
|
||||
{
|
||||
// В стартовой комнате ставим 1 врага (первый носитель, в которого игрок может сразу вселиться Духом)
|
||||
count = 1;
|
||||
}
|
||||
else if (config != null)
|
||||
{
|
||||
int baseCount = Random.Range(config.minEnemies, config.maxEnemies + 1);
|
||||
int areaBonus = config.extraEnemyPerArea > 0f ? Mathf.FloorToInt(area / config.extraEnemyPerArea) : 0;
|
||||
count = baseCount + areaBonus;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Авто-расчёт по площади комнаты и глубине (чем дальше от старта, тем больше охрана)
|
||||
int depth = Mathf.Max(1, floor.GetDepth(view.Data));
|
||||
int min = Mathf.Clamp(1 + depth / 2, 1, 3);
|
||||
int max = Mathf.Clamp(2 + Mathf.FloorToInt(area / 30f), min, 6);
|
||||
count = Random.Range(min, max + 1);
|
||||
}
|
||||
|
||||
if (count <= 0) return;
|
||||
|
||||
var enemiesRoot = new GameObject("Enemies").transform;
|
||||
enemiesRoot.SetParent(view.transform, false);
|
||||
|
||||
float margin = config != null ? config.wallMargin : 2f;
|
||||
float minX = origin.x + Mathf.Min(margin, size.x * 0.35f);
|
||||
float maxX = origin.x + size.x - Mathf.Min(margin, size.x * 0.35f);
|
||||
float minZ = origin.z + Mathf.Min(margin, size.z * 0.35f);
|
||||
float maxZ = origin.z + size.z - Mathf.Min(margin, size.z * 0.35f);
|
||||
|
||||
var spawnedPositions = new List<Vector3>();
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
BodyClass chosenClass = rt == RoomType.Start
|
||||
? BodyClass.Trooper // На старте всегда даём сбалансированного Штурмовика (или Скаута)
|
||||
: PickClass(rt, config);
|
||||
|
||||
Vector3 spawnPos = FindSpawnPosition(minX, maxX, minZ, maxZ, view.CenterMeters, rt == RoomType.Start, spawnedPositions);
|
||||
spawnedPositions.Add(spawnPos);
|
||||
|
||||
GameObject prefab = ResolveEnemyPrefab(chosenClass, config);
|
||||
EnemyAI enemy = CreateEnemyInstance(prefab, chosenClass, spawnPos, enemiesRoot, i);
|
||||
|
||||
view.Enemies.Add(enemy);
|
||||
}
|
||||
}
|
||||
|
||||
// Подбирает точку спавна в комнате так, чтобы враги не слипались друг с другом
|
||||
// и не спавнились прямо на голове игрока в Start-комнате
|
||||
private static Vector3 FindSpawnPosition(float minX, float maxX, float minZ, float maxZ,
|
||||
Vector3 roomCenter, bool isStartRoom, List<Vector3> occupied)
|
||||
{
|
||||
for (int attempt = 0; attempt < 15; attempt++)
|
||||
{
|
||||
Vector3 candidate = new Vector3(
|
||||
Random.Range(minX, maxX),
|
||||
0.1f,
|
||||
Random.Range(minZ, maxZ));
|
||||
|
||||
// В стартовой комнате игрок падает в центр, поэтому врага ставим чуть поодаль от центра
|
||||
if (isStartRoom && Vector2.Distance(new Vector2(candidate.x, candidate.z), new Vector2(roomCenter.x, roomCenter.z)) < 2.5f)
|
||||
continue;
|
||||
|
||||
bool tooClose = false;
|
||||
foreach (var pos in occupied)
|
||||
{
|
||||
if ((candidate - pos).sqrMagnitude < 3.0f) // минимум ~1.7м между врагами
|
||||
{
|
||||
tooClose = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!tooClose) return candidate;
|
||||
}
|
||||
|
||||
return new Vector3(Random.Range(minX, maxX), 0.1f, Random.Range(minZ, maxZ));
|
||||
}
|
||||
|
||||
// Выбирает класс врага из конфига ИЛИ автоматически по смыслу комнаты (RoomType)
|
||||
private static BodyClass PickClass(RoomType roomType, RoomEnemySpawnConfig config)
|
||||
{
|
||||
if (config != null && config.enemyPool != null && config.enemyPool.Count > 0)
|
||||
{
|
||||
float totalWeight = 0f;
|
||||
foreach (var e in config.enemyPool) totalWeight += e.weight;
|
||||
|
||||
float roll = Random.Range(0f, totalWeight);
|
||||
float cursor = 0f;
|
||||
foreach (var e in config.enemyPool)
|
||||
{
|
||||
cursor += e.weight;
|
||||
if (roll <= cursor) return e.enemyClass;
|
||||
}
|
||||
return config.enemyPool[0].enemyClass;
|
||||
}
|
||||
|
||||
// Умное распределение классов по ролям комнат по умолчанию:
|
||||
float r = Random.value;
|
||||
switch (roomType)
|
||||
{
|
||||
case RoomType.Storage:
|
||||
case RoomType.BoilerRoom:
|
||||
case RoomType.SwitchboardRoom:
|
||||
// Узкие технические комнаты: много Джаггернаутов (35%) и быстрых Скаутов (40%)
|
||||
if (r < 0.35f) return BodyClass.Juggernaut;
|
||||
if (r < 0.75f) return BodyClass.Scout;
|
||||
return BodyClass.Trooper;
|
||||
|
||||
case RoomType.Penthouse:
|
||||
case RoomType.Laboratory:
|
||||
// Просторные/чистые залы: Снайперы (35%), Штурмовики (45%), Скауты (20%)
|
||||
if (r < 0.35f) return BodyClass.Sniper;
|
||||
if (r < 0.80f) return BodyClass.Trooper;
|
||||
return BodyClass.Scout;
|
||||
|
||||
default: // Office и остальные
|
||||
// Офисы: в основном Штурмовики (45%) и Скауты (30%), реже Снайпер (15%) и Джаггернаут (10%)
|
||||
if (r < 0.45f) return BodyClass.Trooper;
|
||||
if (r < 0.75f) return BodyClass.Scout;
|
||||
if (r < 0.90f) return BodyClass.Sniper;
|
||||
return BodyClass.Juggernaut;
|
||||
}
|
||||
}
|
||||
|
||||
private static GameObject ResolveEnemyPrefab(BodyClass cls, RoomEnemySpawnConfig config)
|
||||
{
|
||||
if (config == null) return null;
|
||||
if (config.enemyPool != null)
|
||||
{
|
||||
foreach (var entry in config.enemyPool)
|
||||
{
|
||||
if (entry.enemyClass == cls && entry.customPrefab != null)
|
||||
return entry.customPrefab;
|
||||
}
|
||||
}
|
||||
return config.defaultEnemyPrefab;
|
||||
}
|
||||
|
||||
// Спавнит префаб врага ИЛИ автоматически собирает боевую капсулу нужного размера и цвета, если префаб ещё не сделан!
|
||||
private static EnemyAI CreateEnemyInstance(GameObject prefab, BodyClass cls, Vector3 pos, Transform parent, int index)
|
||||
{
|
||||
Quaternion rot = Quaternion.Euler(0f, Random.Range(0f, 360f), 0f);
|
||||
GameObject go;
|
||||
|
||||
if (prefab != null)
|
||||
{
|
||||
go = Object.Instantiate(prefab, pos, rot, parent);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Авто-сборка капсулы врага (чтобы можно было играть сразу без готовых 3D-моделей!)
|
||||
go = GameObject.CreatePrimitive(PrimitiveType.Capsule);
|
||||
go.transform.SetParent(parent, false);
|
||||
|
||||
// Подгоняем размер и цвет капсулы под класс врага, чтобы игрок сразу различал их визуально!
|
||||
Vector3 scale = Vector3.one;
|
||||
Color classColor = Color.blue;
|
||||
|
||||
switch (cls)
|
||||
{
|
||||
case BodyClass.Scout:
|
||||
scale = new Vector3(0.85f, 0.9f, 0.85f);
|
||||
classColor = new Color(1f, 0.85f, 0.1f); // Жёлтый (быстрый)
|
||||
break;
|
||||
case BodyClass.Trooper:
|
||||
scale = new Vector3(1f, 1f, 1f);
|
||||
classColor = new Color(0.2f, 0.5f, 1f); // Синий (штурмовик)
|
||||
break;
|
||||
case BodyClass.Juggernaut:
|
||||
scale = new Vector3(1.35f, 1.25f, 1.35f); // Крупный высокий танк
|
||||
classColor = new Color(0.9f, 0.15f, 0.15f); // Красный
|
||||
break;
|
||||
case BodyClass.Sniper:
|
||||
scale = new Vector3(0.9f, 1.05f, 0.9f);
|
||||
classColor = new Color(0.75f, 0.2f, 1f); // Фиолетовый (снайпер)
|
||||
break;
|
||||
}
|
||||
|
||||
go.transform.localScale = scale;
|
||||
// Поднимаем капсулу так, чтобы её низ стоял ровно на полу (Y = 0)
|
||||
go.transform.SetPositionAndRotation(pos + Vector3.up * scale.y, rot);
|
||||
|
||||
var renderer = go.GetComponent<Renderer>();
|
||||
if (renderer != null)
|
||||
{
|
||||
renderer.material.color = classColor;
|
||||
}
|
||||
}
|
||||
|
||||
go.name = $"Enemy_{index}_{cls}";
|
||||
|
||||
var ai = go.GetComponent<EnemyAI>();
|
||||
if (ai == null) ai = go.AddComponent<EnemyAI>();
|
||||
|
||||
ai.enemyClass = cls;
|
||||
ai.profile = BodyProfile.CreateDefault(cls);
|
||||
|
||||
return ai;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,6 @@
|
||||
|
||||
namespace _Project.Scripts.LevelGenerating
|
||||
{
|
||||
// =====================================================================
|
||||
// Набор оформления комнаты: материалы, конфиг освещения и пропсы.
|
||||
// Создаётся в проекте: ПКМ -> Create -> Level -> Room Theme.
|
||||
// Новая тема - это новые данные, код не меняется.
|
||||
// =====================================================================
|
||||
[CreateAssetMenu(menuName = "Level/Room Theme", fileName = "RoomTheme")]
|
||||
public class RoomTheme : ScriptableObject
|
||||
{
|
||||
@@ -19,6 +14,12 @@ namespace _Project.Scripts.LevelGenerating
|
||||
[Tooltip("Конфиг света с префабом и настройками. Если пусто — света в комнате не будет.")]
|
||||
public RoomLightConfig lightConfig;
|
||||
|
||||
[Header("Враги")]
|
||||
[Tooltip("Спавнить ли врагов в этой комнате (для Коридоров и Лифта выключается автоматически)")]
|
||||
public bool spawnEnemies = true;
|
||||
[Tooltip("Опциональный конфиг спавна. Если пусто — классы врагов подберутся автоматически под тип комнаты!")]
|
||||
public RoomEnemySpawnConfig enemyConfig;
|
||||
|
||||
[Header("Предметы (опционально)")]
|
||||
public RoomPropSet propSet;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Collections.Generic;
|
||||
using _Project.Scripts.PlayerUtils;
|
||||
using UnityEngine;
|
||||
|
||||
namespace _Project.Scripts.LevelGenerating
|
||||
@@ -12,8 +13,9 @@ namespace _Project.Scripts.LevelGenerating
|
||||
public readonly List<Renderer> FloorRenderers = new List<Renderer>();
|
||||
public readonly List<Renderer> CeilingRenderers = new List<Renderer>();
|
||||
public readonly List<Renderer> WallRenderers = new List<Renderer>();
|
||||
//public readonly List<DoorController> Doors = new List<DoorController>();
|
||||
public readonly List<RenderTexture> BakedLightmaps = new List<RenderTexture>();
|
||||
public readonly List<DoorController> Doors = new List<DoorController>();
|
||||
public readonly List<EnemyAI> Enemies = new List<EnemyAI>();
|
||||
public List<RenderTexture> BakedLightmaps = new List<RenderTexture>();
|
||||
|
||||
public Vector3 OriginMeters =>
|
||||
new Vector3(Data.Position.x * LevelGrid.Module, 0f, Data.Position.y * LevelGrid.Module);
|
||||
@@ -28,7 +30,11 @@ namespace _Project.Scripts.LevelGenerating
|
||||
{
|
||||
foreach (var rt in BakedLightmaps)
|
||||
{
|
||||
if (rt != null) rt.Release();
|
||||
if (rt != null)
|
||||
{
|
||||
rt.Release();
|
||||
Destroy(rt);
|
||||
}
|
||||
}
|
||||
BakedLightmaps.Clear();
|
||||
}
|
||||
|
||||
@@ -19,8 +19,26 @@ namespace _Project.Scripts.LevelGenerating
|
||||
|
||||
public static void BakeRoom(RoomView view, RoomLightConfig config)
|
||||
{
|
||||
if (config == null || !config.bakeToRuntimeLightmap) return;
|
||||
var targets = new List<Renderer>();
|
||||
targets.AddRange(view.FloorRenderers);
|
||||
targets.AddRange(view.CeilingRenderers);
|
||||
targets.AddRange(view.WallRenderers);
|
||||
|
||||
// Если запекание ВЫКЛЮЧЕНО в конфиге — сбрасываем лайтмапу в чёрный цвет (выключаем фейковый Emission),
|
||||
// чтобы ты сразу видел разницу!
|
||||
if (config == null || !config.bakeToRuntimeLightmap)
|
||||
{
|
||||
var resetBlock = new MaterialPropertyBlock();
|
||||
foreach (var r in targets)
|
||||
{
|
||||
if (r == null) continue;
|
||||
r.GetPropertyBlock(resetBlock);
|
||||
resetBlock.SetTexture(LightmapTexProp, Texture2D.blackTexture);
|
||||
r.SetPropertyBlock(resetBlock);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (_bakeMaterial == null)
|
||||
{
|
||||
var shader = Shader.Find("Hidden/LevelGenerating/UVRoomBaker");
|
||||
@@ -80,10 +98,7 @@ namespace _Project.Scripts.LevelGenerating
|
||||
rMin.y));
|
||||
|
||||
// 3. Собираем все рендереры комнаты (пол, потолок, стены)
|
||||
var targets = new List<Renderer>();
|
||||
targets.AddRange(view.FloorRenderers);
|
||||
targets.AddRange(view.CeilingRenderers);
|
||||
targets.AddRange(view.WallRenderers);
|
||||
|
||||
|
||||
var cmd = new CommandBuffer { name = $"BakeRoom_{view.Index}" };
|
||||
var mpb = new MaterialPropertyBlock();
|
||||
@@ -108,6 +123,10 @@ namespace _Project.Scripts.LevelGenerating
|
||||
|
||||
// Назначаем напрямую в инстанс материала (100% работает с любым Shader Graph и SRP Batcher!)
|
||||
r.material.SetTexture(LightmapTexProp, rt);
|
||||
|
||||
r.GetPropertyBlock(mpb);
|
||||
mpb.SetTexture(LightmapTexProp, rt);
|
||||
r.SetPropertyBlock(mpb);
|
||||
}
|
||||
|
||||
// Выполняем запекание на GPU мгновенно
|
||||
@@ -115,12 +134,19 @@ namespace _Project.Scripts.LevelGenerating
|
||||
cmd.Release();
|
||||
|
||||
// 4. САМОЕ ГЛАВНОЕ ДЛЯ FPS: Выключаем реальные источники света после запекания!
|
||||
if (config.disableRealtimeLightsAfterBake)
|
||||
int bakedShellMask = LayerMask.GetMask("Ground", "Ceiling", "Wall");
|
||||
|
||||
foreach (var l in lights)
|
||||
{
|
||||
foreach (var l in lights)
|
||||
// Убираем запечённые стены, пол и потолок из Culling Mask лампы
|
||||
l.cullingMask &= ~bakedShellMask;
|
||||
|
||||
// Если включена галочка оптимизации в конфиге — убираем дорогие тени
|
||||
if (config.disableRealtimeLightsAfterBake)
|
||||
{
|
||||
l.enabled = false;
|
||||
l.shadows = LightShadows.None;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,14 +3,8 @@ using UnityEngine;
|
||||
|
||||
namespace _Project.Scripts.LevelGenerating
|
||||
{
|
||||
// Куда смотрит видимая сторона стены (внутрь комнаты или коридора)
|
||||
public enum WallFacing { XP, XN, ZP, ZN }
|
||||
|
||||
// Прямой отрезок стены по линии сетки (координаты в модулях).
|
||||
// Start - точка на линии сетки, с которой отрезок начинается.
|
||||
// Для ZP/ZN отрезок идёт вдоль +X, для XP/XN - вдоль +Z.
|
||||
// RoomIndex - индекс комнаты в FloorData.Rooms, которой принадлежит стена.
|
||||
// Поля публичные, чтобы потом сохранять в файл.
|
||||
[System.Serializable]
|
||||
public struct WallRun
|
||||
{
|
||||
@@ -28,26 +22,38 @@ namespace _Project.Scripts.LevelGenerating
|
||||
}
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Строит отрезки стен из FloorData. Спавна здесь нет, только данные.
|
||||
//
|
||||
// Правила:
|
||||
// - Стена стоит на границе прямоугольника комнаты (плоскость без толщины).
|
||||
// - У коридора стены только по двум длинным сторонам, торцы открыты.
|
||||
// - В стенах комнат вырезаются проёмы шириной ровно с коридор.
|
||||
// - Каждый отрезок помнит комнату-владельца (RoomIndex).
|
||||
// =====================================================================
|
||||
// Дверной проём в стене (для перемычки над дверью и спавна самой двойной двери)
|
||||
[System.Serializable]
|
||||
public struct Doorway
|
||||
{
|
||||
public Vector2Int Start;
|
||||
public int Length;
|
||||
public WallFacing Facing;
|
||||
public int RoomIndex;
|
||||
public bool SpawnDoor;
|
||||
|
||||
public Doorway(Vector2Int start, int length, WallFacing facing, int roomIndex, bool spawnDoor)
|
||||
{
|
||||
Start = start;
|
||||
Length = length;
|
||||
Facing = facing;
|
||||
RoomIndex = roomIndex;
|
||||
SpawnDoor = spawnDoor;
|
||||
}
|
||||
}
|
||||
|
||||
public static class ShellBuilder
|
||||
{
|
||||
private struct Gap
|
||||
{
|
||||
public bool Vertical; // линия x = Line (вертикальная), иначе z = Line
|
||||
public bool Vertical;
|
||||
public int Line, From, To;
|
||||
}
|
||||
|
||||
public static void Build(FloorData floor)
|
||||
{
|
||||
floor.Walls.Clear();
|
||||
floor.Doorways.Clear();
|
||||
var gaps = CollectGaps(floor);
|
||||
|
||||
for (int i = 0; i < floor.Rooms.Count; i++)
|
||||
@@ -58,16 +64,22 @@ namespace _Project.Scripts.LevelGenerating
|
||||
|
||||
if (r.rt == RoomType.Corridor)
|
||||
{
|
||||
// у коридора проёмов нет, его торцы просто открыты
|
||||
// Длинные стороны коридора — стены, а на торцах — перемычки над дверью (обращённые внутрь коридора)
|
||||
if (IsAlongX(r))
|
||||
{
|
||||
AddSide(floor, i, false, z0, x0, x1, WallFacing.ZP, null);
|
||||
AddSide(floor, i, false, z1, x0, x1, WallFacing.ZN, null);
|
||||
|
||||
AddDoorway(floor, i, true, x0, z0, z1, WallFacing.XP, false);
|
||||
AddDoorway(floor, i, true, x1, z0, z1, WallFacing.XN, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
AddSide(floor, i, true, x0, z0, z1, WallFacing.XP, null);
|
||||
AddSide(floor, i, true, x1, z0, z1, WallFacing.XN, null);
|
||||
|
||||
AddDoorway(floor, i, false, z0, x0, x1, WallFacing.ZP, false);
|
||||
AddDoorway(floor, i, false, z1, x0, x1, WallFacing.ZN, false);
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -80,7 +92,6 @@ namespace _Project.Scripts.LevelGenerating
|
||||
}
|
||||
}
|
||||
|
||||
// Коридор идёт вдоль X, если его выход по оси X (запасной вариант: длинная сторона)
|
||||
private static bool IsAlongX(Room c)
|
||||
{
|
||||
if (c.exits != null && c.exits.Count > 0)
|
||||
@@ -88,7 +99,6 @@ namespace _Project.Scripts.LevelGenerating
|
||||
return c.Length >= c.Width;
|
||||
}
|
||||
|
||||
// Места, где коридор упирается в стены комнат
|
||||
private static List<Gap> CollectGaps(FloorData floor)
|
||||
{
|
||||
var gaps = new List<Gap>();
|
||||
@@ -112,7 +122,6 @@ namespace _Project.Scripts.LevelGenerating
|
||||
return gaps;
|
||||
}
|
||||
|
||||
// Добавляет сторону [from, to] на линии line, вырезая проёмы
|
||||
private static void AddSide(FloorData floor, int owner, bool vertical, int line, int from, int to,
|
||||
WallFacing facing, List<Gap> gaps)
|
||||
{
|
||||
@@ -129,6 +138,13 @@ namespace _Project.Scripts.LevelGenerating
|
||||
foreach (var g in own)
|
||||
{
|
||||
if (g.From > cursor) AddRun(floor, owner, vertical, line, cursor, g.From, facing);
|
||||
|
||||
// Записываем проём для перемычки и двери
|
||||
int gapStart = Mathf.Max(cursor, g.From);
|
||||
int gapEnd = Mathf.Min(to, g.To);
|
||||
if (gapEnd > gapStart)
|
||||
AddDoorway(floor, owner, vertical, line, gapStart, gapEnd, facing, true);
|
||||
|
||||
cursor = Mathf.Max(cursor, g.To);
|
||||
}
|
||||
}
|
||||
@@ -142,5 +158,12 @@ namespace _Project.Scripts.LevelGenerating
|
||||
Vector2Int start = vertical ? new Vector2Int(line, a) : new Vector2Int(a, line);
|
||||
floor.Walls.Add(new WallRun(start, b - a, facing, owner));
|
||||
}
|
||||
|
||||
private static void AddDoorway(FloorData floor, int owner, bool vertical, int line, int a, int b,
|
||||
WallFacing facing, bool spawnDoor)
|
||||
{
|
||||
Vector2Int start = vertical ? new Vector2Int(line, a) : new Vector2Int(a, line);
|
||||
floor.Doorways.Add(new Doorway(start, b - a, facing, owner, spawnDoor));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,24 +6,10 @@ namespace _Project.Scripts.LevelGenerating
|
||||
public class ShellResult
|
||||
{
|
||||
public Transform Root;
|
||||
public List<RoomView> Views = new List<RoomView>(); // индекс совпадает с FloorData.Rooms
|
||||
public List<RoomView> Views = new List<RoomView>();
|
||||
public List<DoorController> AllDoors = new List<DoorController>();
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Спавнит пол, потолок и стены из одного префаба-плоскости.
|
||||
// Для каждой комнаты создаётся объект Room_N_Тип с компонентом RoomView.
|
||||
// Материалы здесь НЕ назначаются: этим занимаются генераторы комнат (RoomTheme).
|
||||
//
|
||||
// Требования к префабу:
|
||||
// - Unity Plane (3D Object -> Plane): лежит в XZ, нормаль +Y, размер 10x10 при scale 1.
|
||||
// Если размер другой (например 1x1), поменяй planeBaseSize. Quad не подойдёт: у него нормаль -Z.
|
||||
// - Меш и Renderer на корне префаба. Коллайдеры на префабе игнорируются и заменяются на Box.
|
||||
//
|
||||
// Все плоскости видны только с одной стороны (внутрь комнаты):
|
||||
// стены смотрят внутрь, пол вверх, потолок вниз.
|
||||
//
|
||||
// НЕ ЗАБЫТЬ: сейчас сюда попадает и комната лифта. Позже у неё будет свой фиксированный префаб.
|
||||
// =====================================================================
|
||||
public class ShellSpawner : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private GameObject planePrefab;
|
||||
@@ -31,6 +17,18 @@ namespace _Project.Scripts.LevelGenerating
|
||||
[SerializeField] private float wallHeight = 3f;
|
||||
[SerializeField] private float colliderThickness = 0.2f;
|
||||
|
||||
[Header("Двери и проёмы")]
|
||||
[Tooltip("Префаб двойной двери (с компонентом DoorController)")]
|
||||
[SerializeField] private GameObject doorPrefab;
|
||||
[Tooltip("Высота дверного проёма в метрах. От doorHeight до wallHeight будет построена перемычка с текстурой комнаты.")]
|
||||
[SerializeField] private float doorHeight = 2.2f;
|
||||
[Tooltip("Толщина перемычки над дверью в метрах (0 = плоская, >0 = объёмная с нижней гранью над головой)")]
|
||||
[Min(0f)] [SerializeField] private float lintelThickness = 0.3f;
|
||||
[Tooltip("Дополнительный поворот префаба двери (по умолчанию 180 по Y)")]
|
||||
[SerializeField] private Vector3 doorRotationOffset = new Vector3(0f, 180f, 0f);
|
||||
[Tooltip("Локальное смещение двери относительно проёма (X - вдоль стены, Y - высота, Z - вперёд/назад)")]
|
||||
[SerializeField] private Vector3 doorPositionOffset = Vector3.zero;
|
||||
|
||||
public ShellResult Spawn(FloorData floor)
|
||||
{
|
||||
if (planePrefab == null)
|
||||
@@ -44,6 +42,9 @@ namespace _Project.Scripts.LevelGenerating
|
||||
Root = new GameObject($"Floor_{floor.Index}_Shell").transform
|
||||
};
|
||||
|
||||
int groundLayer = LayerMask.NameToLayer("Ground");
|
||||
int ceilingLayer = LayerMask.NameToLayer("Ceiling");
|
||||
|
||||
// 1. Объект на каждую комнату + пол и потолок
|
||||
for (int i = 0; i < floor.Rooms.Count; i++)
|
||||
{
|
||||
@@ -64,18 +65,17 @@ namespace _Project.Scripts.LevelGenerating
|
||||
// пол: нормаль вверх
|
||||
var floorGo = Make(roomGo.transform, "Floor", new Vector3(c.x, 0f, c.z),
|
||||
Quaternion.identity, scale, true);
|
||||
floorGo.layer = LayerMask.NameToLayer("Ground");
|
||||
if (groundLayer != -1) floorGo.layer = groundLayer;
|
||||
view.FloorRenderers.AddRange(floorGo.GetComponentsInChildren<Renderer>());
|
||||
|
||||
|
||||
// потолок: перевёрнут, нормаль вниз
|
||||
var ceilingGo = Make(roomGo.transform, "Ceiling", new Vector3(c.x, wallHeight, c.z),
|
||||
Quaternion.Euler(180f, 0f, 0f), scale, false);
|
||||
ceilingGo.layer = LayerMask.NameToLayer("Ceiling");
|
||||
if (ceilingLayer != -1) ceilingGo.layer = ceilingLayer;
|
||||
view.CeilingRenderers.AddRange(ceilingGo.GetComponentsInChildren<Renderer>());
|
||||
}
|
||||
|
||||
// 2. Стены раскладываются по комнатам-владельцам
|
||||
// 2. Сплошные стены раскладываются по комнатам-владельцам
|
||||
foreach (var run in floor.Walls)
|
||||
{
|
||||
if (run.RoomIndex < 0 || run.RoomIndex >= result.Views.Count)
|
||||
@@ -83,48 +83,159 @@ namespace _Project.Scripts.LevelGenerating
|
||||
Debug.LogWarning($"Стена ссылается на несуществующую комнату {run.RoomIndex}");
|
||||
continue;
|
||||
}
|
||||
SpawnWall(result.Views[run.RoomIndex], run);
|
||||
SpawnWallPiece(result.Views[run.RoomIndex], run.Start, run.Length, run.Facing, 0f, wallHeight, 0f, "Wall");
|
||||
}
|
||||
|
||||
// 3. Дверные проёмы: объёмная перемычка над дверью + сама двойная дверь
|
||||
foreach (var dw in floor.Doorways)
|
||||
{
|
||||
if (dw.RoomIndex < 0 || dw.RoomIndex >= result.Views.Count) continue;
|
||||
SpawnDoorway(result.Views[dw.RoomIndex], dw, result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private void SpawnWall(RoomView view, WallRun run)
|
||||
private void SpawnDoorway(RoomView view, Doorway dw, ShellResult result)
|
||||
{
|
||||
float len = run.Length * LevelGrid.Module;
|
||||
float y = wallHeight / 2f;
|
||||
float sx = run.Start.x * LevelGrid.Module;
|
||||
float sz = run.Start.y * LevelGrid.Module;
|
||||
// 1. Объёмная перемычка над дверью (от doorHeight до wallHeight)
|
||||
float topWallHeight = wallHeight - doorHeight;
|
||||
if (topWallHeight > 0.01f)
|
||||
{
|
||||
SpawnLintel(view, dw, doorHeight, topWallHeight);
|
||||
}
|
||||
|
||||
// 2. Спавн префаба двойной двери на каждом проёме комнаты
|
||||
if (!dw.SpawnDoor || doorPrefab == null) return;
|
||||
|
||||
float len = dw.Length * LevelGrid.Module;
|
||||
float sx = dw.Start.x * LevelGrid.Module;
|
||||
float sz = dw.Start.y * LevelGrid.Module;
|
||||
|
||||
Vector3 basePos;
|
||||
Quaternion baseRot;
|
||||
|
||||
switch (dw.Facing)
|
||||
{
|
||||
case WallFacing.ZP: // южная стена, нормаль в +Z
|
||||
basePos = new Vector3(sx + len / 2f, 0f, sz);
|
||||
baseRot = Quaternion.Euler(0f, 0f, 0f);
|
||||
break;
|
||||
case WallFacing.ZN: // северная стена, нормаль в -Z
|
||||
basePos = new Vector3(sx + len / 2f, 0f, sz);
|
||||
baseRot = Quaternion.Euler(0f, 180f, 0f);
|
||||
break;
|
||||
case WallFacing.XP: // западная стена, нормаль в +X
|
||||
basePos = new Vector3(sx, 0f, sz + len / 2f);
|
||||
baseRot = Quaternion.Euler(0f, 90f, 0f);
|
||||
break;
|
||||
default: // XN: восточная стена, нормаль в -X
|
||||
basePos = new Vector3(sx, 0f, sz + len / 2f);
|
||||
baseRot = Quaternion.Euler(0f, -90f, 0f);
|
||||
break;
|
||||
}
|
||||
|
||||
Quaternion finalRot = baseRot * Quaternion.Euler(doorRotationOffset);
|
||||
Vector3 finalPos = basePos + finalRot * doorPositionOffset;
|
||||
|
||||
var doorGo = Instantiate(doorPrefab, finalPos, finalRot, view.transform);
|
||||
doorGo.name = $"DoubleDoor_{dw.Facing}";
|
||||
|
||||
var controller = doorGo.GetComponent<DoorController>();
|
||||
if (controller == null) controller = doorGo.AddComponent<DoorController>();
|
||||
|
||||
view.Doors.Add(controller);
|
||||
result.AllDoors.Add(controller);
|
||||
}
|
||||
|
||||
// Строит перемычку над дверью с учётом толщины lintelThickness:
|
||||
// лицевую вертикальную стенку (сдвинутую на halfThick внутрь комнаты) и нижнюю горизонтальную грань
|
||||
private void SpawnLintel(RoomView view, Doorway dw, float bottomY, float pieceHeight)
|
||||
{
|
||||
float halfThick = lintelThickness * 0.5f;
|
||||
|
||||
// Лицевая вертикальная сторона перемычки
|
||||
SpawnWallPiece(view, dw.Start, dw.Length, dw.Facing, bottomY, pieceHeight, halfThick, "Wall_AboveDoor");
|
||||
|
||||
// Если толщина > 0, закрываем нижний торец перемычки (на высоте doorHeight, нормалью вниз)
|
||||
if (halfThick > 0.001f)
|
||||
{
|
||||
float len = dw.Length * LevelGrid.Module;
|
||||
float sx = dw.Start.x * LevelGrid.Module;
|
||||
float sz = dw.Start.y * LevelGrid.Module;
|
||||
|
||||
Vector3 capPos;
|
||||
Vector3 capScale;
|
||||
|
||||
switch (dw.Facing)
|
||||
{
|
||||
case WallFacing.ZP: // от линии стены в +Z на halfThick
|
||||
capPos = new Vector3(sx + len / 2f, bottomY, sz + halfThick / 2f);
|
||||
capScale = new Vector3(len / planeBaseSize, 1f, halfThick / planeBaseSize);
|
||||
break;
|
||||
case WallFacing.ZN: // от линии стены в -Z на halfThick
|
||||
capPos = new Vector3(sx + len / 2f, bottomY, sz - halfThick / 2f);
|
||||
capScale = new Vector3(len / planeBaseSize, 1f, halfThick / planeBaseSize);
|
||||
break;
|
||||
case WallFacing.XP: // от линии стены в +X на halfThick
|
||||
capPos = new Vector3(sx + halfThick / 2f, bottomY, sz + len / 2f);
|
||||
capScale = new Vector3(halfThick / planeBaseSize, 1f, len / planeBaseSize);
|
||||
break;
|
||||
default: // XN: от линии стены в -X на halfThick
|
||||
capPos = new Vector3(sx - halfThick / 2f, bottomY, sz + len / 2f);
|
||||
capScale = new Vector3(halfThick / planeBaseSize, 1f, len / planeBaseSize);
|
||||
break;
|
||||
}
|
||||
|
||||
// Поворот 180 по X — нормаль смотрит вниз (в проём над дверью)
|
||||
var capGo = Make(view.transform, "Wall_AboveDoor_Bottom", capPos,
|
||||
Quaternion.Euler(180f, 0f, 0f), capScale, false);
|
||||
|
||||
int wallLayer = LayerMask.NameToLayer("Wall");
|
||||
if (wallLayer != -1) capGo.layer = wallLayer;
|
||||
view.WallRenderers.AddRange(capGo.GetComponentsInChildren<Renderer>());
|
||||
}
|
||||
}
|
||||
|
||||
private void SpawnWallPiece(RoomView view, Vector2Int startCell, int lengthModules, WallFacing facing,
|
||||
float bottomY, float pieceHeight, float forwardOffset, string pieceName)
|
||||
{
|
||||
float len = lengthModules * LevelGrid.Module;
|
||||
float y = bottomY + pieceHeight / 2f;
|
||||
float sx = startCell.x * LevelGrid.Module;
|
||||
float sz = startCell.y * LevelGrid.Module;
|
||||
|
||||
Vector3 pos;
|
||||
Quaternion rot;
|
||||
Vector3 scale;
|
||||
|
||||
switch (run.Facing)
|
||||
switch (facing)
|
||||
{
|
||||
case WallFacing.ZP: // идёт вдоль X, нормаль +Z
|
||||
pos = new Vector3(sx + len / 2f, y, sz);
|
||||
case WallFacing.ZP:
|
||||
pos = new Vector3(sx + len / 2f, y, sz + forwardOffset);
|
||||
rot = Quaternion.Euler(90f, 0f, 0f);
|
||||
scale = new Vector3(len / planeBaseSize, 1f, wallHeight / planeBaseSize);
|
||||
scale = new Vector3(len / planeBaseSize, 1f, pieceHeight / planeBaseSize);
|
||||
break;
|
||||
case WallFacing.ZN: // идёт вдоль X, нормаль -Z
|
||||
pos = new Vector3(sx + len / 2f, y, sz);
|
||||
case WallFacing.ZN:
|
||||
pos = new Vector3(sx + len / 2f, y, sz - forwardOffset);
|
||||
rot = Quaternion.Euler(-90f, 0f, 0f);
|
||||
scale = new Vector3(len / planeBaseSize, 1f, wallHeight / planeBaseSize);
|
||||
scale = new Vector3(len / planeBaseSize, 1f, pieceHeight / planeBaseSize);
|
||||
break;
|
||||
case WallFacing.XP: // идёт вдоль Z, нормаль +X
|
||||
pos = new Vector3(sx, y, sz + len / 2f);
|
||||
case WallFacing.XP:
|
||||
pos = new Vector3(sx + forwardOffset, y, sz + len / 2f);
|
||||
rot = Quaternion.Euler(0f, 0f, -90f);
|
||||
scale = new Vector3(wallHeight / planeBaseSize, 1f, len / planeBaseSize);
|
||||
scale = new Vector3(pieceHeight / planeBaseSize, 1f, len / planeBaseSize);
|
||||
break;
|
||||
default: // XN: идёт вдоль Z, нормаль -X
|
||||
pos = new Vector3(sx, y, sz + len / 2f);
|
||||
default: // XN
|
||||
pos = new Vector3(sx - forwardOffset, y, sz + len / 2f);
|
||||
rot = Quaternion.Euler(0f, 0f, 90f);
|
||||
scale = new Vector3(wallHeight / planeBaseSize, 1f, len / planeBaseSize);
|
||||
scale = new Vector3(pieceHeight / planeBaseSize, 1f, len / planeBaseSize);
|
||||
break;
|
||||
}
|
||||
|
||||
var go = Make(view.transform, "Wall", pos, rot, scale, true);
|
||||
var go = Make(view.transform, pieceName, pos, rot, scale, true);
|
||||
int wallLayer = LayerMask.NameToLayer("Wall");
|
||||
if (wallLayer != -1) go.layer = wallLayer;
|
||||
view.WallRenderers.AddRange(go.GetComponentsInChildren<Renderer>());
|
||||
}
|
||||
|
||||
@@ -135,12 +246,10 @@ namespace _Project.Scripts.LevelGenerating
|
||||
go.name = name;
|
||||
go.transform.localScale = scale;
|
||||
|
||||
// коллайдеры префаба не используем: у плоскости нет толщины
|
||||
foreach (var c in go.GetComponents<Collider>()) Destroy(c);
|
||||
|
||||
if (withCollider)
|
||||
{
|
||||
// Box прячем за видимой стороной (локальный -Y), чтобы он не съедал место внутри комнаты
|
||||
var box = go.AddComponent<BoxCollider>();
|
||||
box.size = new Vector3(planeBaseSize, colliderThickness, planeBaseSize);
|
||||
box.center = new Vector3(0f, -colliderThickness / 2f, 0f);
|
||||
|
||||
Reference in new issue
Block a user