Сырая но рабочая система расстановки мебели
This commit is contained in:
1 parent
4ccd30d788
commit
6984717957
61 files changed
+6742
-149
No files matched your search
@@ -1,28 +1,44 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
|
||||
public class FurnitureBuilder : MonoBehaviour
|
||||
public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
public enum EditTool { Move, Rotate }
|
||||
|
||||
[Header("Настройки")]
|
||||
public GameObject currentPrefab;
|
||||
|
||||
[Tooltip("Слой пола (по нему кликаем)")]
|
||||
public LayerMask floorLayer;
|
||||
|
||||
[Tooltip("Слой стен (о них будем биться и скользить)")]
|
||||
public LayerMask wallLayer;
|
||||
|
||||
[SerializeField] private GameObject shopPanel;
|
||||
|
||||
[Header("Режим редактирования (UI)")]
|
||||
[SerializeField] private GameObject editPanel;
|
||||
public float rotationSpeed = 5f;
|
||||
|
||||
// Внутренние переменные состояния
|
||||
[Header("Связь с камерой")]
|
||||
public MonoBehaviour cameraController;
|
||||
|
||||
private GameObject _activeFurniture;
|
||||
private FurnitureObject _activeFurnitureScript; // <--- ИЗМЕНИЛИ ИМЯ ЗДЕСЬ
|
||||
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);
|
||||
}
|
||||
@@ -44,24 +60,148 @@ public class FurnitureBuilder : MonoBehaviour
|
||||
|
||||
private void HandleEditing()
|
||||
{
|
||||
Vector3 screenPos = _cam.WorldToScreenPoint(_activeFurniture.transform.position);
|
||||
editPanel.transform.position = screenPos + new Vector3(0, 100, 0);
|
||||
// 1. НАЧАЛО ВЗАИМОДЕЙСТВИЯ (Зажали палец)
|
||||
if (Input.GetMouseButtonDown(0) && !IsPointerOverUI())
|
||||
{
|
||||
_lastInputPos = Input.mousePosition;
|
||||
|
||||
if (Input.GetMouseButton(0) && !IsPointerOverUI())
|
||||
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 (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();
|
||||
}
|
||||
}
|
||||
|
||||
// 2. ПРОЦЕСС (Держим палец/мышь и ведем)
|
||||
if (Input.GetMouseButton(0) && _isInteracting)
|
||||
{
|
||||
if (_currentTool == EditTool.Move)
|
||||
{
|
||||
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, floorLayer))
|
||||
{
|
||||
_activeFurniture.transform.position = hit.point;
|
||||
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 rotX = Input.GetAxis("Mouse X");
|
||||
_activeFurniture.transform.Rotate(Vector3.up, -rotX * rotationSpeed);
|
||||
float deltaX = Input.mousePosition.x - _lastInputPos.x;
|
||||
_activeFurniture.transform.Rotate(Vector3.up, -deltaX * rotationSpeed * 0.2f);
|
||||
}
|
||||
|
||||
_lastInputPos = Input.mousePosition;
|
||||
}
|
||||
|
||||
// 3. КОНЕЦ ВЗАИМОДЕЙСТВИЯ (Отпустили палец)
|
||||
if (Input.GetMouseButtonUp(0) && _isInteracting)
|
||||
{
|
||||
EndInteraction();
|
||||
}
|
||||
|
||||
// 4. ПОЗИЦИОНИРОВАНИЕ UI
|
||||
if (!_isInteracting)
|
||||
{
|
||||
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;
|
||||
editPanel.transform.position = new Vector3(screenPos.x, screenPos.y + yOffset, editPanel.transform.position.z);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (editPanel.activeSelf) editPanel.SetActive(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,19 +211,30 @@ public class FurnitureBuilder : MonoBehaviour
|
||||
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;
|
||||
|
||||
_isInteracting = false;
|
||||
LockCamera(false);
|
||||
|
||||
UpdateUIPosition();
|
||||
}
|
||||
}
|
||||
|
||||
public void SelectMoveTool() { _currentTool = EditTool.Move; }
|
||||
public void SelectRotateTool() { _currentTool = EditTool.Rotate; }
|
||||
public void SelectMoveTool()
|
||||
{
|
||||
_currentTool = EditTool.Move;
|
||||
LockCamera(false);
|
||||
}
|
||||
|
||||
public void SelectRotateTool()
|
||||
{
|
||||
_currentTool = EditTool.Rotate;
|
||||
LockCamera(true);
|
||||
}
|
||||
|
||||
public void ConfirmPlacement()
|
||||
{
|
||||
@@ -92,11 +243,22 @@ public class FurnitureBuilder : MonoBehaviour
|
||||
_activeFurnitureScript.SetEditMode(false);
|
||||
_activeFurniture = null;
|
||||
_activeFurnitureScript = null;
|
||||
editPanel.SetActive(false);
|
||||
editPanel.SetActive(false);
|
||||
|
||||
LockCamera(false);
|
||||
}
|
||||
else
|
||||
}
|
||||
|
||||
public void CancelPlacement()
|
||||
{
|
||||
if (_activeFurniture != null)
|
||||
{
|
||||
Debug.Log("Нельзя поставить сюда! Мебель пересекается с препятствием.");
|
||||
Destroy(_activeFurniture);
|
||||
_activeFurniture = null;
|
||||
_activeFurnitureScript = null;
|
||||
editPanel.SetActive(false);
|
||||
|
||||
LockCamera(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +268,14 @@ public class FurnitureBuilder : MonoBehaviour
|
||||
shopPanel.SetActive(false);
|
||||
}
|
||||
|
||||
private void LockCamera(bool isLocked)
|
||||
{
|
||||
if (cameraController != null)
|
||||
{
|
||||
cameraController.enabled = !isLocked;
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsPointerOverUI()
|
||||
{
|
||||
if (EventSystem.current != null)
|
||||
|
||||
@@ -1,42 +1,59 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class FurnitureObject : MonoBehaviour
|
||||
{
|
||||
[Header("Настройки")]
|
||||
public LayerMask obstacleLayers; // Слои объектов, с которыми нельзя пересекаться
|
||||
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;
|
||||
|
||||
// Переменные для нашей "коробки"
|
||||
private GameObject _highlightBox;
|
||||
private Material _highlightMaterial;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
Renderer[] renderers = GetComponentsInChildren<Renderer>();
|
||||
foreach (var r in renderers)
|
||||
CreateHighlightBox();
|
||||
}
|
||||
|
||||
private void CreateHighlightBox()
|
||||
{
|
||||
BoxCollider col = GetComponent<BoxCollider>();
|
||||
if (col == null)
|
||||
{
|
||||
foreach (var mat in r.materials)
|
||||
{
|
||||
_materials.Add(mat);
|
||||
_originalColors.Add(mat.color);
|
||||
}
|
||||
Debug.LogError("На префабе мебели нет BoxCollider! Коробка не появится.");
|
||||
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);
|
||||
}
|
||||
|
||||
public void SetEditMode(bool active)
|
||||
{
|
||||
if (!active)
|
||||
if (_highlightBox != null)
|
||||
{
|
||||
for (int i = 0; i < _materials.Count; i++)
|
||||
{
|
||||
_materials[i].color = _originalColors[i];
|
||||
}
|
||||
return;
|
||||
_highlightBox.SetActive(active);
|
||||
if (active) UpdateColor();
|
||||
}
|
||||
|
||||
UpdateColor();
|
||||
}
|
||||
|
||||
private void OnTriggerEnter(Collider other)
|
||||
@@ -59,11 +76,11 @@ public class FurnitureObject : MonoBehaviour
|
||||
|
||||
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)
|
||||
if (_highlightMaterial != null)
|
||||
{
|
||||
mat.color = targetColor;
|
||||
// Зеленый или красный цвет (0.4f - это степень прозрачности)
|
||||
Color targetColor = IsPlacementValid ? new Color(0, 1, 0, 0.4f) : new Color(1, 0, 0, 0.4f);
|
||||
_highlightMaterial.color = targetColor;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ public class FurnitureItem
|
||||
public class ShopManager : MonoBehaviour
|
||||
{
|
||||
[Header("Связи")]
|
||||
public FurnitureBuilder builder; // Ссылка на ваш скрипт строительства
|
||||
public FurnitureController builder; // Ссылка на ваш скрипт строительства
|
||||
public GameObject buttonTemplate; // Наш префаб кнопки магазина
|
||||
public Transform contentPanel; // Тот самый объект Content с Grid Layout Group
|
||||
|
||||
|
||||
Reference in new issue
Block a user