папочка навёл порядок в папках
This commit is contained in:
1 parent
9374a984e6
commit
b407380203
1123 files changed
+2764
-133233
No files matched your search
@@ -0,0 +1,198 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class CameraController : MonoBehaviour
|
||||
{
|
||||
[Header("Настройки позиции камеры (Зум)")]
|
||||
public float distance = 10f;
|
||||
public float minDistance = 3f;
|
||||
public float maxDistance = 30f;
|
||||
public float zoomSpeed = 0.05f;
|
||||
|
||||
[Header("Настройки цели (Ось Y)")]
|
||||
public float targetY = 0f;
|
||||
public float minTargetY = 0f;
|
||||
public float maxTargetY = 15f;
|
||||
public float moveTargetSpeed = 0.02f;
|
||||
public float addingHeight = 3f;
|
||||
|
||||
[Header("Настройки вращения")]
|
||||
public float rotationSpeed = 0.2f;
|
||||
[SerializeField]
|
||||
private float currentAngle = -45f;
|
||||
|
||||
[Header("Настройки смещения (Pan - НОВОЕ)")]
|
||||
[Tooltip("Скорость смещения камеры по горизонтали")]
|
||||
public float panSpeed = 0.03f;
|
||||
[Tooltip("При каком отдалении камеры разрешено смещение? (Если отдалить дальше - смещение сбросится)")]
|
||||
public float zoomThresholdForPan = 15f;
|
||||
[Tooltip("Максимальное смещение от центра комнаты")]
|
||||
public float maxPanDistance = 10f;
|
||||
|
||||
[Header("Настройки плавности (Сглаживание)")]
|
||||
[Range(0.01f, 0.5f)]
|
||||
public float smoothTime = 0.1f;
|
||||
public float touchDeadZone = 1.5f;
|
||||
|
||||
// ЦЕЛЕВЫЕ значения
|
||||
private float _targetAngle;
|
||||
private float _targetY;
|
||||
private float _targetDistance;
|
||||
|
||||
// НОВОЕ: Целевое и текущее смещение по осям X и Z
|
||||
private Vector2 _targetPanOffset;
|
||||
private Vector2 _currentPanOffset;
|
||||
|
||||
// Внутренние переменные скорости для 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();
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
HandleInput();
|
||||
CheckPanReset(); // Проверяем, не пора ли сбросить смещение
|
||||
SmoothMovement();
|
||||
UpdateCameraPosition();
|
||||
}
|
||||
|
||||
private void HandleInput()
|
||||
{
|
||||
// === 1. УПРАВЛЕНИЕ ОДНИМ ПАЛЬЦЕМ (Вращение и высота) ===
|
||||
if (Input.touchCount == 1)
|
||||
{
|
||||
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. УПРАВЛЕНИЕ ДВУМЯ ПАЛЬЦАМИ (Зум и Смещение) ===
|
||||
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;
|
||||
|
||||
float prevMagnitude = (touch0PrevPos - touch1PrevPos).magnitude;
|
||||
float currentMagnitude = (touch0.position - touch1.position).magnitude;
|
||||
|
||||
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))
|
||||
{
|
||||
_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)
|
||||
{
|
||||
_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)
|
||||
{
|
||||
_targetPanOffset = _targetPanOffset.normalized * maxPanDistance;
|
||||
}
|
||||
}
|
||||
|
||||
// НОВЫЙ МЕТОД: Сброс смещения при отдалении
|
||||
private void CheckPanReset()
|
||||
{
|
||||
if (_targetDistance > zoomThresholdForPan)
|
||||
{
|
||||
// Если отдалились слишком сильно - обнуляем целевое смещение.
|
||||
// Благодаря SmoothDamp камера вернется в центр плавно!
|
||||
_targetPanOffset = Vector2.zero;
|
||||
}
|
||||
}
|
||||
|
||||
private void SmoothMovement()
|
||||
{
|
||||
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()
|
||||
{
|
||||
// НОВОЕ: Теперь цель вращения учитывает наше смещение по осям X и Z
|
||||
Vector3 targetPoint = new Vector3(_currentPanOffset.x, targetY, _currentPanOffset.y);
|
||||
|
||||
float radians = currentAngle * Mathf.Deg2Rad;
|
||||
|
||||
float x = targetPoint.x + distance * Mathf.Sin(radians);
|
||||
float z = targetPoint.z + distance * Mathf.Cos(radians);
|
||||
|
||||
transform.position = new Vector3(x, targetY + addingHeight, z);
|
||||
transform.LookAt(targetPoint);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f29cc249ac44dd54c967d23bfb3b0316
|
||||
@@ -0,0 +1,38 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
public class CeilingVisibility : MonoBehaviour
|
||||
{
|
||||
private Renderer _renderer;
|
||||
private Camera _cam;
|
||||
|
||||
void Start()
|
||||
{
|
||||
_renderer = GetComponent<Renderer>();
|
||||
_cam = Camera.main;
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
if (_cam == null || _renderer == null) return;
|
||||
|
||||
// Если камера находится ВЫШЕ потолка
|
||||
if (_cam.transform.position.y > transform.position.y)
|
||||
{
|
||||
// Делаем сам потолок невидимым, но заставляем его отбрасывать тень в комнату!
|
||||
if (_renderer.shadowCastingMode != ShadowCastingMode.ShadowsOnly)
|
||||
{
|
||||
_renderer.shadowCastingMode = ShadowCastingMode.ShadowsOnly;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Если камера опустилась ВНУТРЬ комнаты (ниже потолка)
|
||||
if (_renderer.shadowCastingMode != ShadowCastingMode.On)
|
||||
{
|
||||
// Возвращаем потолку видимость
|
||||
_renderer.shadowCastingMode = ShadowCastingMode.On;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 85a21ba56c50a1c4eb56a91f4e77df19
|
||||
@@ -0,0 +1,333 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
|
||||
public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
public enum EditTool { Move, Rotate }
|
||||
|
||||
[Header("Настройки")]
|
||||
public GameObject currentPrefab;
|
||||
public LayerMask floorLayer;
|
||||
public LayerMask wallLayer;
|
||||
public LayerMask furnitureLayer;
|
||||
|
||||
[SerializeField] private GameObject shopPanel;
|
||||
|
||||
[Header("Режим редактирования (UI)")]
|
||||
[SerializeField] private GameObject editPanel;
|
||||
[SerializeField] private GameObject rotate90Button;
|
||||
public float rotationSpeed = 5f;
|
||||
|
||||
[Header("Связь с камерой")]
|
||||
public MonoBehaviour cameraController;
|
||||
|
||||
private GameObject _activeFurniture;
|
||||
private FurnitureObject _activeFurnitureScript;
|
||||
private EditTool _currentTool = EditTool.Move;
|
||||
private Camera _cam;
|
||||
|
||||
private bool _isInteracting = false;
|
||||
private Vector3 _lastInputPos;
|
||||
private Vector3 _dragOffset;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
_cam = Camera.main;
|
||||
if (cameraController == null && _cam != null)
|
||||
cameraController = _cam.GetComponent("CameraController") as MonoBehaviour;
|
||||
|
||||
currentPrefab = null;
|
||||
editPanel.SetActive(false);
|
||||
if (rotate90Button != null) rotate90Button.SetActive(false);
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (_activeFurniture != null)
|
||||
{
|
||||
HandleEditing();
|
||||
}
|
||||
else if (currentPrefab != null)
|
||||
{
|
||||
if (Input.GetMouseButtonDown(0) && !shopPanel.activeSelf && !IsPointerOverUI())
|
||||
TryPlaceFurniture();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Input.GetMouseButtonDown(0) && !shopPanel.activeSelf && !IsPointerOverUI())
|
||||
TrySelectPlacedFurniture();
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleEditing()
|
||||
{
|
||||
if (Input.GetMouseButtonDown(0) && !IsPointerOverUI())
|
||||
{
|
||||
_lastInputPos = Input.mousePosition;
|
||||
|
||||
if (_currentTool == EditTool.Move)
|
||||
{
|
||||
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
|
||||
RaycastHit[] hits = Physics.SphereCastAll(ray, 0.5f, 100f);
|
||||
|
||||
bool foundFurniture = false;
|
||||
foreach (var hit in hits)
|
||||
{
|
||||
if (hit.transform.IsChildOf(_activeFurniture.transform) || hit.transform == _activeFurniture.transform)
|
||||
{
|
||||
foundFurniture = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (foundFurniture)
|
||||
{
|
||||
// Для пола считаем смещение, настенные предметы просто цепляем к курсору
|
||||
if (!_activeFurnitureScript.isWallObject && Physics.Raycast(ray, out RaycastHit floorHit, 100f, floorLayer))
|
||||
{
|
||||
_dragOffset = _activeFurniture.transform.position - floorHit.point;
|
||||
_dragOffset.y = 0;
|
||||
}
|
||||
else _dragOffset = Vector3.zero;
|
||||
|
||||
StartInteraction();
|
||||
}
|
||||
}
|
||||
else if (_currentTool == EditTool.Rotate)
|
||||
{
|
||||
StartInteraction();
|
||||
}
|
||||
}
|
||||
|
||||
if (Input.GetMouseButton(0) && _isInteracting)
|
||||
{
|
||||
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
|
||||
|
||||
if (_currentTool == EditTool.Move)
|
||||
{
|
||||
// === ЛОГИКА ДЛЯ НАСТЕННЫХ ПРЕДМЕТОВ ===
|
||||
if (_activeFurnitureScript.isWallObject)
|
||||
{
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, wallLayer))
|
||||
{
|
||||
_activeFurniture.transform.position = hit.point;
|
||||
// Магия: Поворачиваем объект "лицом" от стены
|
||||
_activeFurniture.transform.rotation = Quaternion.LookRotation(hit.normal);
|
||||
}
|
||||
}
|
||||
// === ЛОГИКА ДЛЯ НАПОЛЬНЫХ ПРЕДМЕТОВ (Старая) ===
|
||||
else
|
||||
{
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, floorLayer))
|
||||
{
|
||||
Vector3 currentPos = _activeFurniture.transform.position;
|
||||
Vector3 targetPos = hit.point + _dragOffset;
|
||||
targetPos.y = currentPos.y;
|
||||
|
||||
Vector3 moveDir = targetPos - currentPos;
|
||||
float moveDist = moveDir.magnitude;
|
||||
|
||||
if (moveDist > 0.001f)
|
||||
{
|
||||
BoxCollider box = _activeFurniture.GetComponent<BoxCollider>();
|
||||
if (box != null)
|
||||
{
|
||||
Vector3 center = _activeFurniture.transform.TransformPoint(box.center);
|
||||
Vector3 halfExtents = Vector3.Scale(box.size, _activeFurniture.transform.lossyScale) * 0.49f;
|
||||
|
||||
if (Physics.BoxCast(center, halfExtents, moveDir.normalized, out RaycastHit wallHit, _activeFurniture.transform.rotation, moveDist, wallLayer))
|
||||
{
|
||||
float safeDist = Mathf.Max(0f, wallHit.distance - 0.01f);
|
||||
Vector3 remainingMove = moveDir - (moveDir.normalized * safeDist);
|
||||
Vector3 slideMove = Vector3.ProjectOnPlane(remainingMove, wallHit.normal);
|
||||
|
||||
if (slideMove.magnitude > 0.001f)
|
||||
{
|
||||
Vector3 newCenter = center + moveDir.normalized * safeDist;
|
||||
if (Physics.BoxCast(newCenter, halfExtents, slideMove.normalized, out RaycastHit slideHit, _activeFurniture.transform.rotation, slideMove.magnitude, wallLayer))
|
||||
{
|
||||
slideMove = slideMove.normalized * Mathf.Max(0f, slideHit.distance - 0.01f);
|
||||
}
|
||||
}
|
||||
|
||||
targetPos = currentPos + (moveDir.normalized * safeDist) + slideMove;
|
||||
}
|
||||
}
|
||||
}
|
||||
targetPos.y = currentPos.y;
|
||||
_activeFurniture.transform.position = targetPos;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (_currentTool == EditTool.Rotate)
|
||||
{
|
||||
float deltaX = Input.mousePosition.x - _lastInputPos.x;
|
||||
|
||||
// Настенные предметы крутим вокруг своей оси Z (по циферблату), а напольные - вокруг мировой Y
|
||||
if (_activeFurnitureScript.isWallObject)
|
||||
_activeFurniture.transform.Rotate(Vector3.forward, -deltaX * rotationSpeed * 0.2f, Space.Self);
|
||||
else
|
||||
_activeFurniture.transform.Rotate(Vector3.up, -deltaX * rotationSpeed * 0.2f, Space.World);
|
||||
}
|
||||
|
||||
_lastInputPos = Input.mousePosition;
|
||||
}
|
||||
|
||||
if (Input.GetMouseButtonUp(0) && _isInteracting) EndInteraction();
|
||||
if (!_isInteracting) UpdateUIPosition();
|
||||
}
|
||||
|
||||
private void TrySelectPlacedFurniture()
|
||||
{
|
||||
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 1000f, furnitureLayer, QueryTriggerInteraction.Collide))
|
||||
{
|
||||
FurnitureObject furnScript = hit.collider.GetComponentInParent<FurnitureObject>();
|
||||
if (furnScript != null)
|
||||
{
|
||||
_activeFurniture = furnScript.gameObject;
|
||||
_activeFurnitureScript = furnScript;
|
||||
_activeFurnitureScript.SetEditMode(true);
|
||||
|
||||
_currentTool = EditTool.Move;
|
||||
if (rotate90Button != null) rotate90Button.SetActive(false);
|
||||
|
||||
_isInteracting = false;
|
||||
LockCamera(false);
|
||||
UpdateUIPosition();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void StartInteraction()
|
||||
{
|
||||
_isInteracting = true;
|
||||
if (editPanel.activeSelf) editPanel.SetActive(false);
|
||||
if (_currentTool == EditTool.Move) LockCamera(true);
|
||||
}
|
||||
|
||||
private void EndInteraction()
|
||||
{
|
||||
_isInteracting = false;
|
||||
UpdateUIPosition();
|
||||
editPanel.SetActive(true);
|
||||
if (_currentTool == EditTool.Move) LockCamera(false);
|
||||
}
|
||||
|
||||
private void UpdateUIPosition()
|
||||
{
|
||||
Vector3 screenPos = _cam.WorldToScreenPoint(_activeFurniture.transform.position);
|
||||
if (screenPos.z > 0)
|
||||
{
|
||||
if (!editPanel.activeSelf) editPanel.SetActive(true);
|
||||
float yOffset = Screen.height * 0.15f;
|
||||
float targetX = screenPos.x;
|
||||
float targetY = screenPos.y + yOffset;
|
||||
|
||||
RectTransform rect = editPanel.GetComponent<RectTransform>();
|
||||
if (rect != null)
|
||||
{
|
||||
float paddingX = (rect.rect.width / 2f) * editPanel.transform.lossyScale.x;
|
||||
float paddingY = (rect.rect.height / 2f) * editPanel.transform.lossyScale.y;
|
||||
targetX = Mathf.Clamp(targetX, paddingX, Screen.width - paddingX);
|
||||
targetY = Mathf.Clamp(targetY, paddingY, Screen.height - paddingY);
|
||||
}
|
||||
editPanel.transform.position = new Vector3(targetX, targetY, editPanel.transform.position.z);
|
||||
}
|
||||
else if (editPanel.activeSelf) editPanel.SetActive(false);
|
||||
}
|
||||
|
||||
void TryPlaceFurniture()
|
||||
{
|
||||
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
|
||||
|
||||
// Определяем, куда пускать луч при установке в зависимости от типа предмета
|
||||
FurnitureObject prefabScript = currentPrefab.GetComponent<FurnitureObject>();
|
||||
LayerMask targetLayer = prefabScript.isWallObject ? wallLayer : floorLayer;
|
||||
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, targetLayer))
|
||||
{
|
||||
_activeFurniture = Instantiate(currentPrefab, hit.point, Quaternion.identity);
|
||||
|
||||
// Если это стена - сразу поворачиваем спиной к ней
|
||||
if (prefabScript.isWallObject)
|
||||
{
|
||||
_activeFurniture.transform.rotation = Quaternion.LookRotation(hit.normal);
|
||||
}
|
||||
|
||||
_activeFurnitureScript = _activeFurniture.GetComponent<FurnitureObject>();
|
||||
_activeFurnitureScript.SetEditMode(true);
|
||||
|
||||
_currentTool = EditTool.Move;
|
||||
if (rotate90Button != null) rotate90Button.SetActive(false);
|
||||
|
||||
currentPrefab = null;
|
||||
_isInteracting = false;
|
||||
LockCamera(false);
|
||||
UpdateUIPosition();
|
||||
}
|
||||
}
|
||||
|
||||
public void Rotate90Degrees()
|
||||
{
|
||||
if (_activeFurniture != null)
|
||||
{
|
||||
if (_activeFurnitureScript.isWallObject)
|
||||
{
|
||||
// Настенные объекты поворачиваем по их локальной оси Z (как часы)
|
||||
_activeFurniture.transform.Rotate(0, 0, 90f, Space.Self);
|
||||
}
|
||||
else
|
||||
{
|
||||
float currentY = _activeFurniture.transform.eulerAngles.y;
|
||||
float snappedY = Mathf.Round(currentY / 90f) * 90f;
|
||||
_activeFurniture.transform.rotation = Quaternion.Euler(0, snappedY + 90f, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void SelectMoveTool() { _currentTool = EditTool.Move; if (rotate90Button != null) rotate90Button.SetActive(false); LockCamera(false); }
|
||||
public void SelectRotateTool() { _currentTool = EditTool.Rotate; if (rotate90Button != null) rotate90Button.SetActive(true); LockCamera(true); }
|
||||
|
||||
public void ConfirmPlacement()
|
||||
{
|
||||
if (_activeFurnitureScript != null && _activeFurnitureScript.IsPlacementValid)
|
||||
{
|
||||
_activeFurnitureScript.SetEditMode(false);
|
||||
_activeFurniture = null;
|
||||
_activeFurnitureScript = null;
|
||||
editPanel.SetActive(false);
|
||||
LockCamera(false);
|
||||
}
|
||||
}
|
||||
|
||||
public void CancelPlacement()
|
||||
{
|
||||
if (_activeFurniture != null)
|
||||
{
|
||||
Destroy(_activeFurniture);
|
||||
_activeFurniture = null;
|
||||
_activeFurnitureScript = null;
|
||||
editPanel.SetActive(false);
|
||||
LockCamera(false);
|
||||
}
|
||||
}
|
||||
|
||||
public void SelectFurnitureAndCloseShop(GameObject prefabToSelect)
|
||||
{
|
||||
currentPrefab = prefabToSelect;
|
||||
shopPanel.SetActive(false);
|
||||
}
|
||||
|
||||
private void LockCamera(bool isLocked) { if (cameraController != null) cameraController.enabled = !isLocked; }
|
||||
|
||||
private bool IsPointerOverUI()
|
||||
{
|
||||
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,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 37c5b010452efc242ae2c7e3114721a7
|
||||
@@ -0,0 +1,75 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class FurnitureObject : MonoBehaviour
|
||||
{
|
||||
[Header("Тип объекта")]
|
||||
public bool isWallObject = false; // ГАЛОЧКА: Это настенный предмет?
|
||||
|
||||
[Header("Настройки")]
|
||||
public LayerMask obstacleLayers;
|
||||
|
||||
private int _obstaclesCount = 0;
|
||||
public bool IsPlacementValid => _obstaclesCount == 0;
|
||||
|
||||
private GameObject _highlightBox;
|
||||
private Material _highlightMaterial;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
CreateHighlightBox();
|
||||
}
|
||||
|
||||
private void CreateHighlightBox()
|
||||
{
|
||||
BoxCollider col = GetComponent<BoxCollider>();
|
||||
if (col == null) return;
|
||||
|
||||
_highlightBox = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
Destroy(_highlightBox.GetComponent<Collider>());
|
||||
|
||||
_highlightBox.transform.SetParent(transform);
|
||||
_highlightBox.transform.localPosition = col.center;
|
||||
_highlightBox.transform.localRotation = Quaternion.identity;
|
||||
_highlightBox.transform.localScale = col.size;
|
||||
|
||||
_highlightMaterial = new Material(Shader.Find("Sprites/Default"));
|
||||
_highlightBox.GetComponent<Renderer>().material = _highlightMaterial;
|
||||
_highlightBox.SetActive(false);
|
||||
}
|
||||
|
||||
public void SetEditMode(bool active)
|
||||
{
|
||||
if (_highlightBox != null)
|
||||
{
|
||||
_highlightBox.SetActive(active);
|
||||
if (active) 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()
|
||||
{
|
||||
if (_highlightMaterial != null)
|
||||
{
|
||||
Color targetColor = IsPlacementValid ? new Color(0, 1, 0, 0.4f) : new Color(1, 0, 0, 0.4f);
|
||||
_highlightMaterial.color = targetColor;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7196b5f65c7bcd143b0f035424936bef
|
||||
@@ -0,0 +1,115 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
[System.Serializable]
|
||||
public class PillarData
|
||||
{
|
||||
public GameObject pillarObject;
|
||||
public GameObject connectedWall1;
|
||||
public GameObject connectedWall2;
|
||||
}
|
||||
|
||||
public class RoomVisibilityController : MonoBehaviour
|
||||
{
|
||||
[Header("Центр комнаты")]
|
||||
public Transform roomCenter;
|
||||
|
||||
[Header("Стены (Просто перетащите 4 стены)")]
|
||||
public GameObject[] walls;
|
||||
|
||||
[Header("Столбики")]
|
||||
public PillarData[] pillars;
|
||||
|
||||
[Header("Настройки видимости")]
|
||||
[Range(-0.5f, 0.5f)]
|
||||
public float hideThreshold = 0.1f;
|
||||
|
||||
private Camera _mainCamera;
|
||||
private Dictionary<GameObject, bool> _wallHiddenStates = new Dictionary<GameObject, bool>();
|
||||
|
||||
// Кэшируем Renderer'ы для оптимизации (чтобы не делать GetComponent каждый кадр)
|
||||
private Dictionary<GameObject, Renderer[]> _objectRenderers = new Dictionary<GameObject, Renderer[]>();
|
||||
|
||||
void Start()
|
||||
{
|
||||
_mainCamera = Camera.main;
|
||||
|
||||
// При старте игры находим и запоминаем все Renderer'ы
|
||||
foreach (var wall in walls) { CacheRenderers(wall); }
|
||||
foreach (var pillar in pillars) { CacheRenderers(pillar.pillarObject); }
|
||||
}
|
||||
|
||||
private void CacheRenderers(GameObject obj)
|
||||
{
|
||||
if (obj != null && !_objectRenderers.ContainsKey(obj))
|
||||
{
|
||||
_objectRenderers[obj] = obj.GetComponentsInChildren<Renderer>();
|
||||
}
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
if (_mainCamera == null || roomCenter == null) return;
|
||||
|
||||
Vector3 dirToCamera = _mainCamera.transform.position - roomCenter.position;
|
||||
dirToCamera.y = 0; // Игнорируем высоту
|
||||
|
||||
// 1. СТЕНЫ
|
||||
foreach (var wall in walls)
|
||||
{
|
||||
if (wall == null) continue;
|
||||
|
||||
Vector3 targetPos = GetRealCenter(wall);
|
||||
Vector3 dirToWall = targetPos - roomCenter.position;
|
||||
dirToWall.y = 0;
|
||||
|
||||
bool isHidden = Vector3.Dot(dirToCamera.normalized, dirToWall.normalized) > hideThreshold;
|
||||
|
||||
// Включаем или выключаем графику стены моментально
|
||||
SetVisibility(wall, !isHidden);
|
||||
_wallHiddenStates[wall] = isHidden;
|
||||
|
||||
Debug.DrawLine(roomCenter.position, targetPos, isHidden ? Color.red : Color.green);
|
||||
}
|
||||
|
||||
// 2. СТОЛБИКИ
|
||||
foreach (var pillar in pillars)
|
||||
{
|
||||
if (pillar.pillarObject == null || pillar.connectedWall1 == null || pillar.connectedWall2 == null)
|
||||
continue;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// Метод для быстрого включения/выключения отрисовки объекта
|
||||
private void SetVisibility(GameObject obj, bool isVisible)
|
||||
{
|
||||
if (obj == null || !_objectRenderers.ContainsKey(obj)) return;
|
||||
|
||||
Renderer[] renderers = _objectRenderers[obj];
|
||||
foreach (Renderer r in renderers)
|
||||
{
|
||||
if (r.enabled != isVisible)
|
||||
{
|
||||
r.enabled = isVisible;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Vector3 GetRealCenter(GameObject obj)
|
||||
{
|
||||
Renderer r = obj.GetComponentInChildren<Renderer>();
|
||||
if (r != null)
|
||||
{
|
||||
return r.bounds.center;
|
||||
}
|
||||
return obj.transform.position;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 95bc6e27b7d341a4493014fef624b5eb
|
||||
@@ -0,0 +1,52 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI; // Обязательно добавляем для работы с интерфейсом
|
||||
|
||||
// Этот класс - наша "карточка товара". Он хранит иконку и 3D-модель.
|
||||
[System.Serializable] // Позволяет отображать этот класс в инспекторе Unity
|
||||
public class FurnitureItem
|
||||
{
|
||||
public string itemName; // Название (просто для вашего удобства в инспекторе)
|
||||
public Sprite icon; // Иконка для магазина
|
||||
public GameObject prefab; // 3D-модель для установки
|
||||
}
|
||||
|
||||
public class ShopManager : MonoBehaviour
|
||||
{
|
||||
[Header("Связи")]
|
||||
public FurnitureController builder; // Ссылка на ваш скрипт строительства
|
||||
public GameObject buttonTemplate; // Наш префаб кнопки магазина
|
||||
public Transform contentPanel; // Тот самый объект Content с Grid Layout Group
|
||||
|
||||
[Header("Каталог мебели")]
|
||||
public List<FurnitureItem> items; // Список всей мебели в игре
|
||||
|
||||
void Start()
|
||||
{
|
||||
// Как только игра запускается, генерируем магазин
|
||||
GenerateShop();
|
||||
}
|
||||
|
||||
void GenerateShop()
|
||||
{
|
||||
// Проходимся по каждому предмету в нашем каталоге
|
||||
foreach (FurnitureItem item in items)
|
||||
{
|
||||
// 1. Создаем копию шаблона кнопки внутри панели Content
|
||||
GameObject newButton = Instantiate(buttonTemplate, contentPanel);
|
||||
|
||||
// 2. Находим компонент Image на этой кнопке и меняем картинку на нашу иконку
|
||||
newButton.GetComponent<Image>().sprite = item.icon;
|
||||
|
||||
// 3. Находим компонент Button, чтобы настроить клик
|
||||
Button btn = newButton.GetComponent<Button>();
|
||||
|
||||
// Сохраняем префаб в локальную переменную (это важно для правильной работы кода)
|
||||
GameObject prefabToSelect = item.prefab;
|
||||
|
||||
// 4. Программно добавляем действие при клике (то же самое, что плюсик в инспекторе)
|
||||
// Мы вызываем метод из вашего прошлого скрипта!
|
||||
btn.onClick.AddListener(() => builder.SelectFurnitureAndCloseShop(prefabToSelect));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 07c4fd35416ae7d4aa742d551654809f
|
||||
Reference in new issue
Block a user