Делаю режим строительства
This commit is contained in:
1 parent
09be8e6737
commit
4ccd30d788
11 files changed
+1422
-163
No files matched your search
@@ -3,14 +3,12 @@ using UnityEngine;
|
||||
public class CameraController : MonoBehaviour
|
||||
{
|
||||
[Header("Настройки позиции камеры (Зум)")]
|
||||
[Tooltip("Стартовое расстояние от камеры до цели")]
|
||||
public float distance = 10f;
|
||||
public float minDistance = 3f;
|
||||
public float maxDistance = 30f;
|
||||
public float zoomSpeed = 0.05f;
|
||||
|
||||
[Header("Настройки цели (Ось Y)")]
|
||||
[Tooltip("Стартовая высота цели на оси Y")]
|
||||
public float targetY = 0f;
|
||||
public float minTargetY = 0f;
|
||||
public float maxTargetY = 15f;
|
||||
@@ -22,30 +20,41 @@ public class CameraController : MonoBehaviour
|
||||
[SerializeField]
|
||||
private float currentAngle = -45f;
|
||||
|
||||
[Header("Настройки смещения (Pan - НОВОЕ)")]
|
||||
[Tooltip("Скорость смещения камеры по горизонтали")]
|
||||
public float panSpeed = 0.03f;
|
||||
[Tooltip("При каком отдалении камеры разрешено смещение? (Если отдалить дальше - смещение сбросится)")]
|
||||
public float zoomThresholdForPan = 15f;
|
||||
[Tooltip("Максимальное смещение от центра комнаты")]
|
||||
public float maxPanDistance = 10f;
|
||||
|
||||
[Header("Настройки плавности (Сглаживание)")]
|
||||
[Tooltip("Время сглаживания. Чем больше значение, тем более плавно и с большей инерцией движется камера.")]
|
||||
[Range(0.01f, 0.5f)]
|
||||
public float smoothTime = 0.1f;
|
||||
|
||||
[Tooltip("Мертвая зона в пикселях. Отсекает микро-дрожание пальцев.")]
|
||||
public float touchDeadZone = 1.5f;
|
||||
|
||||
// ЦЕЛЕВЫЕ значения (куда камера должна стремиться прийти)
|
||||
// ЦЕЛЕВЫЕ значения
|
||||
private float _targetAngle;
|
||||
private float _targetY;
|
||||
private float _targetDistance;
|
||||
|
||||
// НОВОЕ: Целевое и текущее смещение по осям X и Z
|
||||
private Vector2 _targetPanOffset;
|
||||
private Vector2 _currentPanOffset;
|
||||
|
||||
// Внутренние переменные скорости (необходимы для работы функции Mathf.SmoothDamp)
|
||||
// Внутренние переменные скорости для SmoothDamp
|
||||
private float _angleVelocity;
|
||||
private float _yVelocity;
|
||||
private float _distanceVelocity;
|
||||
private Vector2 _panVelocity; // Скорость для смещения
|
||||
|
||||
void Start()
|
||||
{
|
||||
// Инициализируем целевые значения текущими при старте, чтобы камера не прыгала
|
||||
_targetAngle = currentAngle;
|
||||
_targetY = targetY;
|
||||
_targetDistance = distance;
|
||||
_targetPanOffset = Vector2.zero;
|
||||
_currentPanOffset = Vector2.zero;
|
||||
|
||||
UpdateCameraPosition();
|
||||
}
|
||||
@@ -53,6 +62,7 @@ public class CameraController : MonoBehaviour
|
||||
void LateUpdate()
|
||||
{
|
||||
HandleInput();
|
||||
CheckPanReset(); // Проверяем, не пора ли сбросить смещение
|
||||
SmoothMovement();
|
||||
UpdateCameraPosition();
|
||||
}
|
||||
@@ -64,22 +74,20 @@ public class CameraController : MonoBehaviour
|
||||
{
|
||||
Touch touch = Input.GetTouch(0);
|
||||
|
||||
// Проверяем, сдвинулся ли палец дальше "мертвой зоны", чтобы игнорировать дрожание
|
||||
if (touch.phase == TouchPhase.Moved && touch.deltaPosition.sqrMagnitude > touchDeadZone * touchDeadZone)
|
||||
{
|
||||
// Меняем ЦЕЛЕВЫЕ значения, а не саму камеру
|
||||
_targetAngle += touch.deltaPosition.x * rotationSpeed;
|
||||
|
||||
_targetY -= touch.deltaPosition.y * moveTargetSpeed;
|
||||
_targetY = Mathf.Clamp(_targetY, minTargetY, maxTargetY);
|
||||
}
|
||||
}
|
||||
// === 2. УПРАВЛЕНИЕ ДВУМЯ ПАЛЬЦАМИ (Зум) ===
|
||||
// === 2. УПРАВЛЕНИЕ ДВУМЯ ПАЛЬЦАМИ (Зум и Смещение) ===
|
||||
else if (Input.touchCount == 2)
|
||||
{
|
||||
Touch touch0 = Input.GetTouch(0);
|
||||
Touch touch1 = Input.GetTouch(1);
|
||||
|
||||
// -- Логика Зума --
|
||||
Vector2 touch0PrevPos = touch0.position - touch0.deltaPosition;
|
||||
Vector2 touch1PrevPos = touch1.position - touch1.deltaPosition;
|
||||
|
||||
@@ -88,47 +96,99 @@ public class CameraController : MonoBehaviour
|
||||
|
||||
float difference = currentMagnitude - prevMagnitude;
|
||||
|
||||
// Мертвая зона для зума
|
||||
if (Mathf.Abs(difference) > touchDeadZone)
|
||||
{
|
||||
_targetDistance -= difference * zoomSpeed;
|
||||
_targetDistance = Mathf.Clamp(_targetDistance, minDistance, maxDistance);
|
||||
}
|
||||
|
||||
// -- НОВОЕ: Логика смещения (Панорамирование) --
|
||||
// Разрешаем смещение только если камера достаточно близко
|
||||
if (_targetDistance <= zoomThresholdForPan)
|
||||
{
|
||||
// Берем среднее движение двух пальцев
|
||||
Vector2 avgDelta = (touch0.deltaPosition + touch1.deltaPosition) / 2f;
|
||||
ApplyPan(avgDelta.x, avgDelta.y);
|
||||
}
|
||||
}
|
||||
// === 3. МЫШЬ (Для редактора ПК) ===
|
||||
else if (Input.GetMouseButton(0))
|
||||
else
|
||||
{
|
||||
_targetAngle += Input.GetAxis("Mouse X") * rotationSpeed * 20f;
|
||||
_targetY -= Input.GetAxis("Mouse Y") * moveTargetSpeed * 20f;
|
||||
_targetY = Mathf.Clamp(_targetY, minTargetY, maxTargetY);
|
||||
}
|
||||
// Левая кнопка - Вращение и высота
|
||||
if (Input.GetMouseButton(0))
|
||||
{
|
||||
_targetAngle += Input.GetAxis("Mouse X") * rotationSpeed * 20f;
|
||||
_targetY -= Input.GetAxis("Mouse Y") * moveTargetSpeed * 20f;
|
||||
_targetY = Mathf.Clamp(_targetY, minTargetY, maxTargetY);
|
||||
}
|
||||
// НОВОЕ: Правая кнопка - Смещение (Pan)
|
||||
else if (Input.GetMouseButton(1) && _targetDistance <= zoomThresholdForPan)
|
||||
{
|
||||
ApplyPan(Input.GetAxis("Mouse X") * 20f, Input.GetAxis("Mouse Y") * 20f);
|
||||
}
|
||||
|
||||
// Зум колесиком мыши
|
||||
float scroll = Input.GetAxis("Mouse ScrollWheel");
|
||||
if (scroll != 0)
|
||||
// Зум колесиком мыши
|
||||
float scroll = Input.GetAxis("Mouse ScrollWheel");
|
||||
if (scroll != 0)
|
||||
{
|
||||
_targetDistance -= scroll * zoomSpeed * 100f;
|
||||
_targetDistance = Mathf.Clamp(_targetDistance, minDistance, maxDistance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// НОВЫЙ МЕТОД: Применение смещения относительно текущего поворота камеры
|
||||
private void ApplyPan(float deltaX, float deltaY)
|
||||
{
|
||||
// Высчитываем векторы "вправо" и "вперед" для камеры, игнорируя наклон (ось Y)
|
||||
Vector3 right = transform.right;
|
||||
right.y = 0;
|
||||
right.Normalize();
|
||||
|
||||
Vector3 forward = transform.forward;
|
||||
forward.y = 0;
|
||||
forward.Normalize();
|
||||
|
||||
// Умножаем движение пальца/мыши на направление камеры
|
||||
Vector3 move = (right * -deltaX) + (forward * -deltaY);
|
||||
|
||||
_targetPanOffset += new Vector2(move.x, move.z) * panSpeed;
|
||||
|
||||
// Ограничиваем максимальное смещение, чтобы не улететь за карту
|
||||
if (_targetPanOffset.magnitude > maxPanDistance)
|
||||
{
|
||||
_targetDistance -= scroll * zoomSpeed * 100f;
|
||||
_targetDistance = Mathf.Clamp(_targetDistance, minDistance, maxDistance);
|
||||
_targetPanOffset = _targetPanOffset.normalized * maxPanDistance;
|
||||
}
|
||||
}
|
||||
|
||||
// НОВЫЙ МЕТОД: Сброс смещения при отдалении
|
||||
private void CheckPanReset()
|
||||
{
|
||||
if (_targetDistance > zoomThresholdForPan)
|
||||
{
|
||||
// Если отдалились слишком сильно - обнуляем целевое смещение.
|
||||
// Благодаря SmoothDamp камера вернется в центр плавно!
|
||||
_targetPanOffset = Vector2.zero;
|
||||
}
|
||||
}
|
||||
|
||||
private void SmoothMovement()
|
||||
{
|
||||
// Функция SmoothDamp плавно "подтягивает" текущее значение к целевому.
|
||||
// Это создает эффект пружины и инерции.
|
||||
currentAngle = Mathf.SmoothDamp(currentAngle, _targetAngle, ref _angleVelocity, smoothTime);
|
||||
targetY = Mathf.SmoothDamp(targetY, _targetY, ref _yVelocity, smoothTime);
|
||||
distance = Mathf.SmoothDamp(distance, _targetDistance, ref _distanceVelocity, smoothTime);
|
||||
|
||||
// НОВОЕ: Плавно сглаживаем позицию смещения
|
||||
_currentPanOffset = Vector2.SmoothDamp(_currentPanOffset, _targetPanOffset, ref _panVelocity, smoothTime);
|
||||
}
|
||||
|
||||
private void UpdateCameraPosition()
|
||||
{
|
||||
// Цель на оси Y с ПЛАВНОЙ высотой (targetY)
|
||||
Vector3 targetPoint = new Vector3(0, targetY, 0);
|
||||
// НОВОЕ: Теперь цель вращения учитывает наше смещение по осям X и Z
|
||||
Vector3 targetPoint = new Vector3(_currentPanOffset.x, targetY, _currentPanOffset.y);
|
||||
|
||||
float radians = currentAngle * Mathf.Deg2Rad;
|
||||
|
||||
// Вычисляем ПЛАВНЫЕ координаты X и Z
|
||||
float x = targetPoint.x + distance * Mathf.Sin(radians);
|
||||
float z = targetPoint.z + distance * Mathf.Cos(radians);
|
||||
|
||||
|
||||
@@ -1,47 +1,118 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
|
||||
public class FurnitureBuilder : MonoBehaviour
|
||||
{
|
||||
public enum EditTool { Move, Rotate }
|
||||
|
||||
[Header("Настройки")]
|
||||
public GameObject currentPrefab;
|
||||
public LayerMask floorLayer;
|
||||
[SerializeField] private GameObject shopPanel;
|
||||
|
||||
[Header("Режим редактирования (UI)")]
|
||||
[SerializeField] private GameObject editPanel;
|
||||
public float rotationSpeed = 5f;
|
||||
|
||||
// Внутренние переменные состояния
|
||||
private GameObject _activeFurniture;
|
||||
private FurnitureObject _activeFurnitureScript; // <--- ИЗМЕНИЛИ ИМЯ ЗДЕСЬ
|
||||
private EditTool _currentTool = EditTool.Move;
|
||||
private Camera _cam;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
_cam = Camera.main;
|
||||
currentPrefab = null;
|
||||
editPanel.SetActive(false);
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (Input.GetMouseButtonDown(0)&&!shopPanel.activeSelf)
|
||||
if (_activeFurniture != null)
|
||||
{
|
||||
if (currentPrefab != null)
|
||||
HandleEditing();
|
||||
}
|
||||
else if (currentPrefab != null)
|
||||
{
|
||||
if (Input.GetMouseButtonDown(0) && !shopPanel.activeSelf && !IsPointerOverUI())
|
||||
{
|
||||
TryPlaceFurniture();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TryPlaceFurniture()
|
||||
private void HandleEditing()
|
||||
{
|
||||
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
|
||||
RaycastHit hit;
|
||||
|
||||
if (Physics.Raycast(ray, out hit, 100f, floorLayer))
|
||||
Vector3 screenPos = _cam.WorldToScreenPoint(_activeFurniture.transform.position);
|
||||
editPanel.transform.position = screenPos + new Vector3(0, 100, 0);
|
||||
|
||||
if (Input.GetMouseButton(0) && !IsPointerOverUI())
|
||||
{
|
||||
Instantiate(currentPrefab, hit.point, Quaternion.identity);
|
||||
currentPrefab = null;
|
||||
if (_currentTool == EditTool.Move)
|
||||
{
|
||||
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, floorLayer))
|
||||
{
|
||||
_activeFurniture.transform.position = hit.point;
|
||||
}
|
||||
}
|
||||
else if (_currentTool == EditTool.Rotate)
|
||||
{
|
||||
float rotX = Input.GetAxis("Mouse X");
|
||||
_activeFurniture.transform.Rotate(Vector3.up, -rotX * rotationSpeed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TryPlaceFurniture()
|
||||
{
|
||||
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, floorLayer))
|
||||
{
|
||||
_activeFurniture = Instantiate(currentPrefab, hit.point, Quaternion.identity);
|
||||
|
||||
// <--- ИЗМЕНИЛИ ИМЯ ЗДЕСЬ
|
||||
_activeFurnitureScript = _activeFurniture.GetComponent<FurnitureObject>();
|
||||
|
||||
_activeFurnitureScript.SetEditMode(true);
|
||||
editPanel.SetActive(true);
|
||||
_currentTool = EditTool.Move;
|
||||
currentPrefab = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void SelectMoveTool() { _currentTool = EditTool.Move; }
|
||||
public void SelectRotateTool() { _currentTool = EditTool.Rotate; }
|
||||
|
||||
public void ConfirmPlacement()
|
||||
{
|
||||
if (_activeFurnitureScript != null && _activeFurnitureScript.IsPlacementValid)
|
||||
{
|
||||
_activeFurnitureScript.SetEditMode(false);
|
||||
_activeFurniture = null;
|
||||
_activeFurnitureScript = null;
|
||||
editPanel.SetActive(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log("Нельзя поставить сюда! Мебель пересекается с препятствием.");
|
||||
}
|
||||
}
|
||||
|
||||
public void SelectFurnitureAndCloseShop(GameObject prefabToSelect)
|
||||
{
|
||||
currentPrefab = prefabToSelect;
|
||||
shopPanel.SetActive(false);
|
||||
}
|
||||
public void SelectFurniture(GameObject prefabToSelect)
|
||||
|
||||
private bool IsPointerOverUI()
|
||||
{
|
||||
currentPrefab = prefabToSelect;
|
||||
if (EventSystem.current != null)
|
||||
{
|
||||
if (EventSystem.current.IsPointerOverGameObject()) return true;
|
||||
if (Input.touchCount > 0 && EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class FurnitureObject : MonoBehaviour
|
||||
{
|
||||
[Header("Настройки")]
|
||||
public LayerMask obstacleLayers; // Слои объектов, с которыми нельзя пересекаться
|
||||
|
||||
private List<Material> _materials = new List<Material>();
|
||||
private List<Color> _originalColors = new List<Color>();
|
||||
private int _obstaclesCount = 0;
|
||||
|
||||
public bool IsPlacementValid => _obstaclesCount == 0;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
Renderer[] renderers = GetComponentsInChildren<Renderer>();
|
||||
foreach (var r in renderers)
|
||||
{
|
||||
foreach (var mat in r.materials)
|
||||
{
|
||||
_materials.Add(mat);
|
||||
_originalColors.Add(mat.color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void SetEditMode(bool active)
|
||||
{
|
||||
if (!active)
|
||||
{
|
||||
for (int i = 0; i < _materials.Count; i++)
|
||||
{
|
||||
_materials[i].color = _originalColors[i];
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
UpdateColor();
|
||||
}
|
||||
|
||||
private void OnTriggerEnter(Collider other)
|
||||
{
|
||||
if (((1 << other.gameObject.layer) & obstacleLayers) != 0)
|
||||
{
|
||||
_obstaclesCount++;
|
||||
UpdateColor();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnTriggerExit(Collider other)
|
||||
{
|
||||
if (((1 << other.gameObject.layer) & obstacleLayers) != 0)
|
||||
{
|
||||
_obstaclesCount--;
|
||||
UpdateColor();
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateColor()
|
||||
{
|
||||
Color targetColor = IsPlacementValid ? new Color(0, 1, 0, 0.6f) : new Color(1, 0, 0, 0.6f);
|
||||
|
||||
foreach (var mat in _materials)
|
||||
{
|
||||
mat.color = targetColor;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7196b5f65c7bcd143b0f035424936bef
|
||||
@@ -20,23 +20,54 @@ public class RoomVisibilityController : MonoBehaviour
|
||||
[Header("Столбики")]
|
||||
public PillarData[] pillars;
|
||||
|
||||
[Header("Настройки")]
|
||||
[Header("Настройки видимости")]
|
||||
[Range(-0.5f, 0.5f)]
|
||||
public float hideThreshold = 0.1f;
|
||||
|
||||
[Header("Настройки плавности (НОВОЕ)")]
|
||||
public float fadeSpeed = 3f; // Скорость исчезновения (чем больше, тем быстрее)
|
||||
|
||||
private Camera _mainCamera;
|
||||
private Dictionary<GameObject, bool> _wallHiddenStates = new Dictionary<GameObject, bool>();
|
||||
|
||||
// Новые словари для контроля плавного исчезновения
|
||||
private Dictionary<GameObject, float> _targetAlphas = new Dictionary<GameObject, float>();
|
||||
private Dictionary<GameObject, List<Material>> _objectMaterials = new Dictionary<GameObject, List<Material>>();
|
||||
private Dictionary<GameObject, Renderer[]> _objectRenderers = new Dictionary<GameObject, Renderer[]>();
|
||||
|
||||
void Start()
|
||||
{
|
||||
_mainCamera = Camera.main;
|
||||
|
||||
// При старте игры находим и запоминаем все материалы стен и столбиков
|
||||
foreach (var wall in walls) { InitializeFadingData(wall); }
|
||||
foreach (var pillar in pillars) { InitializeFadingData(pillar.pillarObject); }
|
||||
}
|
||||
|
||||
// Метод для кэширования материалов (чтобы не искать их каждый кадр)
|
||||
private void InitializeFadingData(GameObject obj)
|
||||
{
|
||||
if (obj == null || _objectMaterials.ContainsKey(obj)) return;
|
||||
|
||||
Renderer[] renderers = obj.GetComponentsInChildren<Renderer>();
|
||||
List<Material> mats = new List<Material>();
|
||||
|
||||
foreach (Renderer r in renderers)
|
||||
{
|
||||
// Обращение к .materials создает уникальную копию материала для объекта.
|
||||
// Это нужно, чтобы стены исчезали по отдельности, а не все разом.
|
||||
mats.AddRange(r.materials);
|
||||
}
|
||||
|
||||
_objectRenderers[obj] = renderers;
|
||||
_objectMaterials[obj] = mats;
|
||||
_targetAlphas[obj] = 1f; // 1f - это 100% непрозрачности (видимый)
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
if (_mainCamera == null || roomCenter == null) return;
|
||||
|
||||
// Вектор от центра к камере
|
||||
Vector3 dirToCamera = _mainCamera.transform.position - roomCenter.position;
|
||||
dirToCamera.y = 0; // Игнорируем высоту
|
||||
|
||||
@@ -45,24 +76,17 @@ public class RoomVisibilityController : MonoBehaviour
|
||||
{
|
||||
if (wall == null) continue;
|
||||
|
||||
// МАГИЯ ЗДЕСЬ: берем реальный геометрический центр 3D-модели!
|
||||
Vector3 targetPos = GetRealCenter(wall);
|
||||
|
||||
// Вектор от центра комнаты к реальному центру стены
|
||||
Vector3 dirToWall = targetPos - roomCenter.position;
|
||||
dirToWall.y = 0;
|
||||
|
||||
// Вычисляем, перекрывает ли стена камеру
|
||||
bool isHidden = Vector3.Dot(dirToCamera.normalized, dirToWall.normalized) > hideThreshold;
|
||||
|
||||
// Рисуем линии в сцене (зеленая - видима, красная - спрятана)
|
||||
Debug.DrawLine(roomCenter.position, targetPos, isHidden ? Color.red : Color.green);
|
||||
|
||||
// Включаем/выключаем графику
|
||||
SetVisibility(wall, !isHidden);
|
||||
|
||||
// Запоминаем для столбиков
|
||||
// Вместо мгновенного выключения, задаем ЦЕЛЕВУЮ прозрачность (0 - скрыть, 1 - показать)
|
||||
_targetAlphas[wall] = isHidden ? 0f : 1f;
|
||||
_wallHiddenStates[wall] = isHidden;
|
||||
|
||||
Debug.DrawLine(roomCenter.position, targetPos, isHidden ? Color.red : Color.green);
|
||||
}
|
||||
|
||||
// 2. СТОЛБИКИ
|
||||
@@ -74,34 +98,68 @@ public class RoomVisibilityController : MonoBehaviour
|
||||
bool isWall1Hidden = _wallHiddenStates.ContainsKey(pillar.connectedWall1) && _wallHiddenStates[pillar.connectedWall1];
|
||||
bool isWall2Hidden = _wallHiddenStates.ContainsKey(pillar.connectedWall2) && _wallHiddenStates[pillar.connectedWall2];
|
||||
|
||||
// Прячем столбик только если ОБЕ стены спрятаны
|
||||
bool shouldHidePillar = isWall1Hidden && isWall2Hidden;
|
||||
SetVisibility(pillar.pillarObject, !shouldHidePillar);
|
||||
|
||||
// Задаем целевую прозрачность для столбика
|
||||
_targetAlphas[pillar.pillarObject] = shouldHidePillar ? 0f : 1f;
|
||||
}
|
||||
|
||||
// 3. Вызываем функцию плавного изменения прозрачности
|
||||
UpdateFading();
|
||||
}
|
||||
|
||||
// Метод, который плавно меняет Альфа-канал каждый кадр
|
||||
private void UpdateFading()
|
||||
{
|
||||
foreach (var kvp in _objectMaterials)
|
||||
{
|
||||
GameObject obj = kvp.Key;
|
||||
float targetAlpha = _targetAlphas[obj];
|
||||
List<Material> mats = kvp.Value;
|
||||
|
||||
if (mats.Count == 0) continue;
|
||||
|
||||
// Берем текущую прозрачность из первого материала
|
||||
float currentAlpha = mats[0].color.a;
|
||||
|
||||
// Если текущая прозрачность не равна целевой (надо менять)
|
||||
if (!Mathf.Approximately(currentAlpha, targetAlpha))
|
||||
{
|
||||
// Плавно меняем значение от текущего к целевому
|
||||
float newAlpha = Mathf.MoveTowards(currentAlpha, targetAlpha, fadeSpeed * Time.deltaTime);
|
||||
|
||||
// Применяем новую прозрачность ко всем материалам объекта
|
||||
foreach (Material mat in mats)
|
||||
{
|
||||
Color c = mat.color;
|
||||
c.a = newAlpha;
|
||||
mat.color = c;
|
||||
}
|
||||
|
||||
// ОПТИМИЗАЦИЯ:
|
||||
// Включаем Renderer, если прозрачность больше 0.
|
||||
// Выключаем Renderer полностью, только когда он на 100% прозрачен.
|
||||
Renderer[] renderers = _objectRenderers[obj];
|
||||
bool shouldRender = newAlpha > 0f;
|
||||
|
||||
foreach (Renderer r in renderers)
|
||||
{
|
||||
if (r.enabled != shouldRender)
|
||||
{
|
||||
r.enabled = shouldRender;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Метод, который находит геометрический центр (игнорируя кривые координаты)
|
||||
private Vector3 GetRealCenter(GameObject obj)
|
||||
{
|
||||
Renderer r = obj.GetComponentInChildren<Renderer>();
|
||||
if (r != null)
|
||||
{
|
||||
// bounds.center - это центр самой "коробки" 3D модели
|
||||
return r.bounds.center;
|
||||
}
|
||||
return obj.transform.position; // Запасной вариант
|
||||
}
|
||||
|
||||
// Метод, который выключает саму картинку (сработает даже если стена вложена в пустышку)
|
||||
private void SetVisibility(GameObject obj, bool isVisible)
|
||||
{
|
||||
Renderer[] renderers = obj.GetComponentsInChildren<Renderer>();
|
||||
foreach (Renderer r in renderers)
|
||||
{
|
||||
if (r.enabled != isVisible)
|
||||
{
|
||||
r.enabled = isVisible;
|
||||
}
|
||||
}
|
||||
return obj.transform.position;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user