Files
SummerGame/Assets/_Project/Scripts/MetaPart/FurnitureObject.cs
T

86 lines
2.9 KiB
C#

using UnityEngine;
public class FurnitureObject : MonoBehaviour
{
[Header("Настройки")]
public LayerMask obstacleLayers;
public bool isWallObject;
private int _obstaclesCount = 0;
public bool IsPlacementValid => _obstaclesCount == 0;
[HideInInspector] public FurnitureItemSO runtimeItemData;
private GameObject _highlightBox;
private Material _highlightMaterial;
void Awake()
{
CreateHighlightBox();
}
private void CreateHighlightBox()
{
// Ищем ВСЕ коллайдеры на объекте
BoxCollider[] colliders = GetComponents<BoxCollider>();
if (colliders.Length == 0) return;
// Создаем "виртуальную коробку", которая охватит первый коллайдер
Bounds totalBounds = new Bounds(colliders[0].center, colliders[0].size);
// Добавляем в эту коробку все остальные коллайдеры (для формы буквы Г)
for (int i = 1; i < colliders.Length; i++)
{
Bounds b = new Bounds(colliders[i].center, colliders[i].size);
totalBounds.Encapsulate(b);
}
_highlightBox = GameObject.CreatePrimitive(PrimitiveType.Cube);
Destroy(_highlightBox.GetComponent<Collider>());
_highlightBox.transform.SetParent(transform);
// Ставим зеленую коробку в общий центр и задаем общий размер
_highlightBox.transform.localPosition = totalBounds.center;
_highlightBox.transform.localRotation = Quaternion.identity;
// Умножаем на 1.02, чтобы зеленая коробка была чуть-чуть больше мебели (для красоты)
_highlightBox.transform.localScale = totalBounds.size * 1.02f;
_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;
}
}
}