можно ставить на стены объекты
This commit is contained in:
1 parent
f40af3c880
commit
1779420734
6 files changed
+419
-122
No files matched your search
@@ -9,9 +9,7 @@ public class FurnitureController : MonoBehaviour
|
||||
public GameObject currentPrefab;
|
||||
public LayerMask floorLayer;
|
||||
public LayerMask wallLayer;
|
||||
|
||||
[Tooltip("Слой мебели (чтобы кликать по уже стоящим объектам)")]
|
||||
public LayerMask furnitureLayer; // НОВАЯ ПЕРЕМЕННАЯ
|
||||
public LayerMask furnitureLayer;
|
||||
|
||||
[SerializeField] private GameObject shopPanel;
|
||||
|
||||
@@ -36,9 +34,7 @@ public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
_cam = Camera.main;
|
||||
if (cameraController == null && _cam != null)
|
||||
{
|
||||
cameraController = _cam.GetComponent("CameraController") as MonoBehaviour;
|
||||
}
|
||||
|
||||
currentPrefab = null;
|
||||
editPanel.SetActive(false);
|
||||
@@ -47,32 +43,24 @@ public class FurnitureController : MonoBehaviour
|
||||
|
||||
void Update()
|
||||
{
|
||||
// 1. Если мы УЖЕ редактируем объект
|
||||
if (_activeFurniture != null)
|
||||
{
|
||||
HandleEditing();
|
||||
}
|
||||
// 2. Если мы выбрали НОВУЮ мебель в магазине и хотим её поставить
|
||||
else if (currentPrefab != null)
|
||||
{
|
||||
if (Input.GetMouseButtonDown(0) && !shopPanel.activeSelf && !IsPointerOverUI())
|
||||
{
|
||||
TryPlaceFurniture();
|
||||
}
|
||||
}
|
||||
// 3. НОВОЕ: Если ничего не выбрано, пытаемся кликнуть по УЖЕ СТОЯЩЕЙ мебели
|
||||
else
|
||||
{
|
||||
if (Input.GetMouseButtonDown(0) && !shopPanel.activeSelf && !IsPointerOverUI())
|
||||
{
|
||||
TrySelectPlacedFurniture();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleEditing()
|
||||
{
|
||||
// 1. НАЧАЛО ВЗАИМОДЕЙСТВИЯ
|
||||
if (Input.GetMouseButtonDown(0) && !IsPointerOverUI())
|
||||
{
|
||||
_lastInputPos = Input.mousePosition;
|
||||
@@ -94,7 +82,8 @@ public class FurnitureController : MonoBehaviour
|
||||
|
||||
if (foundFurniture)
|
||||
{
|
||||
if (Physics.Raycast(ray, out RaycastHit floorHit, 100f, floorLayer))
|
||||
// Для пола считаем смещение, настенные предметы просто цепляем к курсору
|
||||
if (!_activeFurnitureScript.isWallObject && Physics.Raycast(ray, out RaycastHit floorHit, 100f, floorLayer))
|
||||
{
|
||||
_dragOffset = _activeFurniture.transform.position - floorHit.point;
|
||||
_dragOffset.y = 0;
|
||||
@@ -110,101 +99,101 @@ public class FurnitureController : MonoBehaviour
|
||||
}
|
||||
}
|
||||
|
||||
// 2. ПРОЦЕСС
|
||||
if (Input.GetMouseButton(0) && _isInteracting)
|
||||
{
|
||||
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
|
||||
|
||||
if (_currentTool == EditTool.Move)
|
||||
{
|
||||
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, floorLayer))
|
||||
// === ЛОГИКА ДЛЯ НАСТЕННЫХ ПРЕДМЕТОВ ===
|
||||
if (_activeFurnitureScript.isWallObject)
|
||||
{
|
||||
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)
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, wallLayer))
|
||||
{
|
||||
BoxCollider box = _activeFurniture.GetComponent<BoxCollider>();
|
||||
if (box != null)
|
||||
_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)
|
||||
{
|
||||
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))
|
||||
BoxCollider box = _activeFurniture.GetComponent<BoxCollider>();
|
||||
if (box != null)
|
||||
{
|
||||
float safeDist = Mathf.Max(0f, wallHit.distance - 0.01f);
|
||||
Vector3 remainingMove = moveDir - (moveDir.normalized * safeDist);
|
||||
Vector3 slideMove = Vector3.ProjectOnPlane(remainingMove, wallHit.normal);
|
||||
Vector3 center = _activeFurniture.transform.TransformPoint(box.center);
|
||||
Vector3 halfExtents = Vector3.Scale(box.size, _activeFurniture.transform.lossyScale) * 0.49f;
|
||||
|
||||
if (slideMove.magnitude > 0.001f)
|
||||
if (Physics.BoxCast(center, halfExtents, moveDir.normalized, out RaycastHit wallHit, _activeFurniture.transform.rotation, moveDist, wallLayer))
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
float safeDist = Mathf.Max(0f, wallHit.distance - 0.01f);
|
||||
Vector3 remainingMove = moveDir - (moveDir.normalized * safeDist);
|
||||
Vector3 slideMove = Vector3.ProjectOnPlane(remainingMove, wallHit.normal);
|
||||
|
||||
targetPos = currentPos + (moveDir.normalized * safeDist) + slideMove;
|
||||
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;
|
||||
}
|
||||
|
||||
targetPos.y = currentPos.y;
|
||||
_activeFurniture.transform.position = targetPos;
|
||||
}
|
||||
}
|
||||
else if (_currentTool == EditTool.Rotate)
|
||||
{
|
||||
float deltaX = Input.mousePosition.x - _lastInputPos.x;
|
||||
_activeFurniture.transform.Rotate(Vector3.up, -deltaX * rotationSpeed * 0.2f);
|
||||
|
||||
// Настенные предметы крутим вокруг своей оси 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;
|
||||
}
|
||||
|
||||
// 3. КОНЕЦ ВЗАИМОДЕЙСТВИЯ
|
||||
if (Input.GetMouseButtonUp(0) && _isInteracting)
|
||||
{
|
||||
EndInteraction();
|
||||
}
|
||||
|
||||
// 4. ПОЗИЦИОНИРОВАНИЕ UI
|
||||
if (!_isInteracting)
|
||||
{
|
||||
UpdateUIPosition();
|
||||
}
|
||||
if (Input.GetMouseButtonUp(0) && _isInteracting) EndInteraction();
|
||||
if (!_isInteracting) UpdateUIPosition();
|
||||
}
|
||||
|
||||
// === НОВЫЙ МЕТОД: Выделение уже стоящей мебели ===
|
||||
private void TrySelectPlacedFurniture()
|
||||
{
|
||||
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
|
||||
|
||||
// Пускаем луч, который ищет ТОЛЬКО объекты на слое FurnitureLayer
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, furnitureLayer))
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 1000f, furnitureLayer, QueryTriggerInteraction.Collide))
|
||||
{
|
||||
// Ищем скрипт FurnitureObject на объекте (или его родителях)
|
||||
FurnitureObject furnScript = hit.collider.GetComponentInParent<FurnitureObject>();
|
||||
if (furnScript != null)
|
||||
{
|
||||
_activeFurniture = furnScript.gameObject;
|
||||
_activeFurnitureScript = furnScript;
|
||||
|
||||
// Включаем зеленую подсветку
|
||||
_activeFurnitureScript.SetEditMode(true);
|
||||
|
||||
// Сбрасываем инструмент на Move
|
||||
_currentTool = EditTool.Move;
|
||||
if (rotate90Button != null) rotate90Button.SetActive(false);
|
||||
|
||||
_isInteracting = false;
|
||||
LockCamera(false);
|
||||
|
||||
// Моментально показываем меню над мебелью
|
||||
UpdateUIPosition();
|
||||
}
|
||||
}
|
||||
@@ -228,11 +217,9 @@ public class FurnitureController : MonoBehaviour
|
||||
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;
|
||||
@@ -242,27 +229,33 @@ public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
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);
|
||||
}
|
||||
else if (editPanel.activeSelf) editPanel.SetActive(false);
|
||||
}
|
||||
|
||||
void TryPlaceFurniture()
|
||||
{
|
||||
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, floorLayer))
|
||||
|
||||
// Определяем, куда пускать луч при установке в зависимости от типа предмета
|
||||
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);
|
||||
_activeFurnitureScript = _activeFurniture.GetComponent<FurnitureObject>();
|
||||
|
||||
// Если это стена - сразу поворачиваем спиной к ней
|
||||
if (prefabScript.isWallObject)
|
||||
{
|
||||
_activeFurniture.transform.rotation = Quaternion.LookRotation(hit.normal);
|
||||
}
|
||||
|
||||
_activeFurnitureScript = _activeFurniture.GetComponent<FurnitureObject>();
|
||||
_activeFurnitureScript.SetEditMode(true);
|
||||
|
||||
_currentTool = EditTool.Move;
|
||||
@@ -271,7 +264,6 @@ public class FurnitureController : MonoBehaviour
|
||||
currentPrefab = null;
|
||||
_isInteracting = false;
|
||||
LockCamera(false);
|
||||
|
||||
UpdateUIPosition();
|
||||
}
|
||||
}
|
||||
@@ -280,25 +272,22 @@ public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
if (_activeFurniture != null)
|
||||
{
|
||||
float currentY = _activeFurniture.transform.eulerAngles.y;
|
||||
float snappedY = Mathf.Round(currentY / 90f) * 90f;
|
||||
_activeFurniture.transform.rotation = Quaternion.Euler(0, snappedY + 90f, 0);
|
||||
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 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()
|
||||
{
|
||||
@@ -330,13 +319,7 @@ public class FurnitureController : MonoBehaviour
|
||||
shopPanel.SetActive(false);
|
||||
}
|
||||
|
||||
private void LockCamera(bool isLocked)
|
||||
{
|
||||
if (cameraController != null)
|
||||
{
|
||||
cameraController.enabled = !isLocked;
|
||||
}
|
||||
}
|
||||
private void LockCamera(bool isLocked) { if (cameraController != null) cameraController.enabled = !isLocked; }
|
||||
|
||||
private bool IsPointerOverUI()
|
||||
{
|
||||
|
||||
@@ -2,13 +2,15 @@ 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;
|
||||
|
||||
@@ -20,30 +22,18 @@ public class FurnitureObject : MonoBehaviour
|
||||
private void CreateHighlightBox()
|
||||
{
|
||||
BoxCollider col = GetComponent<BoxCollider>();
|
||||
if (col == null)
|
||||
{
|
||||
Debug.LogError("На префабе мебели нет BoxCollider! Коробка не появится.");
|
||||
return;
|
||||
}
|
||||
if (col == null) return;
|
||||
|
||||
// 1. Создаем обычный куб
|
||||
_highlightBox = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
|
||||
// 2. Удаляем с него коллайдер, чтобы он не мешал физике
|
||||
Destroy(_highlightBox.GetComponent<Collider>());
|
||||
|
||||
// 3. Делаем куб дочерним к мебели и задаем размеры коллайдера
|
||||
_highlightBox.transform.SetParent(transform);
|
||||
_highlightBox.transform.localPosition = col.center;
|
||||
_highlightBox.transform.localRotation = Quaternion.identity;
|
||||
_highlightBox.transform.localScale = col.size;
|
||||
|
||||
// 4. Магия: Создаем прозрачный материал через код.
|
||||
// Шейдер "Sprites/Default" есть в Unity всегда, он светится в темноте и поддерживает прозрачность.
|
||||
_highlightMaterial = new Material(Shader.Find("Sprites/Default"));
|
||||
_highlightBox.GetComponent<Renderer>().material = _highlightMaterial;
|
||||
|
||||
// Выключаем куб при старте
|
||||
_highlightBox.SetActive(false);
|
||||
}
|
||||
|
||||
@@ -78,7 +68,6 @@ public class FurnitureObject : MonoBehaviour
|
||||
{
|
||||
if (_highlightMaterial != null)
|
||||
{
|
||||
// Зеленый или красный цвет (0.4f - это степень прозрачности)
|
||||
Color targetColor = IsPlacementValid ? new Color(0, 1, 0, 0.4f) : new Color(1, 0, 0, 0.4f);
|
||||
_highlightMaterial.color = targetColor;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user