using System.Collections; using UnityEngine; [RequireComponent(typeof(CarPartInteractable))] public class CarPartAnimator : MonoBehaviour { [Header("Настройки открытия")] [SerializeField] private Vector3 openRotation; // Например: (0, 0, 60) для капота [SerializeField] private float speed = 5f; private CarPartInteractable interactable; private Quaternion closedRot; private Quaternion openRot; private bool isOpen = false; private Coroutine animationCoroutine; private void Awake() { interactable = GetComponent(); // Запоминаем изначальное (закрытое) положение детали closedRot = transform.localRotation; // Конвертируем введенные углы Эйлера в Кватернион openRot = Quaternion.Euler(openRotation); } // Подписываемся при включении объекта private void OnEnable() { interactable.OnInteract += TogglePart; } // ОТПИСЫВАЕМСЯ при выключении/удалении (Критически важно!) private void OnDisable() { interactable.OnInteract -= TogglePart; } private void TogglePart() { isOpen = !isOpen; // Если деталь уже двигалась, останавливаем старую корутину, чтобы не было конфликтов if (animationCoroutine != null) StopCoroutine(animationCoroutine); animationCoroutine = StartCoroutine(AnimatePart(isOpen ? openRot : closedRot)); } private IEnumerator AnimatePart(Quaternion targetRot) { // Пока угол между текущим и целевым вращением больше 0.1 градуса while (Quaternion.Angle(transform.localRotation, targetRot) > 0.1f) { // Плавно вращаем деталь transform.localRotation = Quaternion.Lerp(transform.localRotation, targetRot, Time.deltaTime * speed); yield return null; // Ждем следующего кадра } // Принудительно доводим до идеального угла в конце transform.localRotation = targetRot; } }