using UnityEngine; public enum PartState { Installed, InHand, Dropped } public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable { [Header("Данные")] [SerializeField] private CarPartData partData; [SerializeField] private float mass = 12f; [Header("Позиционирование в руках")] [SerializeField] private Vector3 inHandPositionOffset = Vector3.zero; [SerializeField] private Vector3 inHandRotationOffset = Vector3.zero; private CarPartAnimator partAnimator; private PartState currentState = PartState.Installed; private Transform originalParent; private Vector3 originalLocalPos; private Quaternion originalLocalRot; private Vector3 originalLocalScale; private WheelBolt[] wheelBolts; private WheelCollider linkedWheelCollider; private Transform currentHoldPoint; private Vector3 targetInHandLocalPos; private Quaternion targetInHandLocalRot; // Родная сторона меша колеса (-1 = левое, +1 = правое) private float nativeWheelSideSign = 0f; private Rigidbody rb; private Collider partCollider; private bool installAsTrigger; private GameObject currentMountZone; private float unboltDuration => (partData != null && partData.boltDuration > 0f) ? partData.boltDuration : 1.2f; private float unboltProgress = 0f; public float UnboltProgress01 => Mathf.Clamp01(unboltProgress / unboltDuration); public void ResetUnbolt() => unboltProgress = 0f; public CarPartData Data => partData; public PartState State => currentState; public bool HasAnimator => partAnimator != null; public int TotalBoltsCount => wheelBolts != null ? wheelBolts.Length : 0; public WheelCollider LinkedWheelCollider => linkedWheelCollider; public WheelBrickSupport SpawnedBrickSupport { get; private set; } public bool IsWheel => linkedWheelCollider != null || (wheelBolts != null && wheelBolts.Length > 0); /// Назначение данных детали из кода (автонастройка и процедурные агрегаты). public void SetData(CarPartData data, float newMass) { if (data != null) partData = data; if (newMass > 0f) mass = newMass; if (rb != null) rb.mass = mass; } public string DisplayName { get { EnginePart ep = GetComponent(); if (ep != null) return ep.DisplayName; if (partData != null && !string.IsNullOrEmpty(partData.partName)) return char.ToUpper(partData.partName[0]) + partData.partName.Substring(1); return gameObject.name; } } /// Состояние детали 0–100% (для склада и продажи на Куфар). public float ConditionPercent { get { EnginePart ep = GetComponent(); if (ep != null) return ep.condition; CarWheelCondition wc = GetComponent(); if (wc != null) return wc.IsFlat ? 35f : 90f; CarPartVisuals v = GetComponent(); if (v != null) { switch (v.Stage) { case RepairStage.Healthy: case RepairStage.Repaired: return 95f; case RepairStage.Rusted: return Mathf.Lerp(90f, 25f, v.CurrentRust); default: return 60f; } } return 80f; } } public int TightenedBoltsCount { get { if (wheelBolts == null || wheelBolts.Length == 0) return 0; int count = 0; foreach (var b in wheelBolts) if (b != null && b.IsTightened) count++; return count; } } private void Awake() { partCollider = GetComponent(); if (partCollider != null) installAsTrigger = partCollider.isTrigger; partAnimator = GetComponent(); wheelBolts = GetComponentsInChildren(true); originalParent = transform.parent; originalLocalPos = transform.localPosition; originalLocalRot = transform.localRotation; originalLocalScale = transform.localScale; // Определяем родную сторону модели колеса по его имени или позиции DetectNativeWheelSide(); VehicleInteraction car = GetComponentInParent(); if (car != null) { foreach (WheelCollider wc in car.GetComponentsInChildren(true)) { if (wc.name == gameObject.name) { linkedWheelCollider = wc; break; } } if (linkedWheelCollider != null && partCollider != null) { if (partCollider is MeshCollider mc) mc.convex = true; partCollider.isTrigger = true; } } else { InitializeAsLoosePart(); } } private void DetectNativeWheelSide() { string n = gameObject.name.ToUpperInvariant(); if (n.Contains("_FL") || n.Contains("_RL") || n.Contains("_L")) nativeWheelSideSign = -1f; else if (n.Contains("_FR") || n.Contains("_RR") || n.Contains("_R")) nativeWheelSideSign = 1f; else if (Mathf.Abs(originalLocalPos.x) > 0.1f) nativeWheelSideSign = Mathf.Sign(originalLocalPos.x); else nativeWheelSideSign = -1f; } public void InitializeAsLoosePart() { currentState = PartState.Dropped; if (wheelBolts != null) { foreach (var b in wheelBolts) { if (b == null) continue; b.SetTightenedImmediate(false); Collider bc = b.GetComponent(); if (bc != null) bc.enabled = false; } } if (partCollider != null) { if (partCollider is MeshCollider mc) mc.convex = true; partCollider.isTrigger = false; partCollider.enabled = true; } SetupDroppedRigidbody(); } private void SetupDroppedRigidbody() { if (rb == null) rb = GetComponent(); if (rb == null) rb = gameObject.AddComponent(); rb.mass = mass; rb.interpolation = RigidbodyInterpolation.Interpolate; rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; // Демпфирование полностью убирает мелкую дрожь колеса на асфальте rb.linearDamping = 1.2f; rb.angularDamping = 3.0f; } private void LateUpdate() { if (currentState == PartState.InHand && currentHoldPoint != null) { transform.localPosition = targetInHandLocalPos; transform.localRotation = targetInHandLocalRot; } } public string GetPrompt() { if (partData == null) return "Деталь (E)"; if (currentState == PartState.Installed) { if (wheelBolts != null && wheelBolts.Length > 0) { if (!CarJack.IsWheelLifted(transform)) return "Колесо под нагрузкой! Поднимите эту сторону домкратом"; if (TightenedBoltsCount > 0) return $"Сначала открутите болты ({TightenedBoltsCount}/{wheelBolts.Length})"; return $"[E] Снять {partData.partName}"; } EnginePart engine = GetComponent(); if (engine != null) { string status = engine.StatusText; if (unboltProgress > 0f) return $"{status}\nСнимаем... {Mathf.RoundToInt(UnboltProgress01 * 100f)}%"; if (engine.RequiresWrench && !HasTool(ToolType.Wrench)) return $"{status}\nНужен гаечный ключ [Tab]"; if (!engine.RequiresWrench && !HasTool(ToolType.Hands)) return $"{status}\nСнимается руками — уберите инструмент [Tab → Руки]"; return $"{status}\n[Удерж. E] {(engine.RequiresWrench ? "Открутить ключом и снять" : "Снять")}"; } if (unboltProgress > 0f) return $"Откручивание болтов ({partData.partName})... {Mathf.RoundToInt(UnboltProgress01 * 100f)}%"; if (partAnimator != null) { string action = partAnimator.IsOpen ? "Закрыть" : "Открыть"; return $"[E] {action} {partData.partName} | [Удерж. R] Снять"; } return $"[Удерж. E] Снять {partData.partName}"; } if (currentState == PartState.Dropped) { EnginePart ep = GetComponent(); return ep != null ? $"[E] Взять: {ep.StatusText}" : $"[E] Взять {partData.partName} ({Mathf.RoundToInt(ConditionPercent)}%)"; } return string.Empty; } public void Interact(GameObject interactor) { if (currentState == PartState.Installed) { if (partAnimator != null) partAnimator.TogglePart(); else if (wheelBolts != null && wheelBolts.Length > 0 && TightenedBoltsCount == 0 && CarJack.IsWheelLifted(transform)) TakeToHands(interactor); } else if (currentState == PartState.Dropped) { TakeToHands(interactor); } } public void SecondaryInteract(GameObject interactor) { } public void ProcessUnbolting(GameObject interactor, float deltaTime) { if (currentState != PartState.Installed) return; if (wheelBolts != null && wheelBolts.Length > 0) { if (!CarJack.IsWheelLifted(transform) || TightenedBoltsCount > 0) return; TakeToHands(interactor); return; } EnginePart enginePart = GetComponent(); ToolType required = (enginePart != null && enginePart.RequiresWrench) ? ToolType.Wrench : ToolType.Hands; PlayerToolManager toolMgr = interactor.GetComponentInChildren(); if (toolMgr != null && toolMgr.currentTool != required) return; if (required == ToolType.Wrench && Mathf.Repeat(unboltProgress, 0.3f) < deltaTime) ProceduralAudioManager.Instance?.Play(SfxId.Ratchet, transform.position, 0.6f); unboltProgress += deltaTime; if (unboltProgress >= unboltDuration) { unboltProgress = 0f; TakeToHands(interactor); } } private void TakeToHands(GameObject interactor) { PlayerHands hands = interactor.GetComponentInChildren(); if (hands == null) hands = interactor.GetComponentInParent(); if (hands == null || hands.IsHoldingAnything) return; if (currentState == PartState.Installed) { if (partAnimator != null) partAnimator.ResetToClosed(); CreateMountZone(); } hands.PickUp(this); } public void OnPickedUp(Transform holdPoint) { currentState = PartState.InHand; currentHoldPoint = holdPoint; unboltProgress = 0f; if (rb != null) Destroy(rb); if (partCollider != null) partCollider.enabled = false; if (wheelBolts != null) { foreach (var b in wheelBolts) if (b != null && b.TryGetComponent(out var bc)) bc.enabled = false; } if (linkedWheelCollider != null) linkedWheelCollider.enabled = false; transform.SetParent(holdPoint); transform.localScale = originalLocalScale; transform.localRotation = Quaternion.Euler(inHandRotationOffset); transform.localPosition = Vector3.zero; Renderer meshRenderer = GetComponentInChildren(); if (meshRenderer != null) { Vector3 visualCenterWorld = meshRenderer.bounds.center; Vector3 offsetToCenter = holdPoint.position - visualCenterWorld; transform.position += offsetToCenter; transform.localPosition += inHandPositionOffset; } targetInHandLocalPos = transform.localPosition; targetInHandLocalRot = transform.localRotation; } public void OnDropped(Vector3 throwForce) { currentState = PartState.Dropped; unboltProgress = 0f; if (currentHoldPoint != null) transform.position = currentHoldPoint.position + currentHoldPoint.forward * 0.5f + Vector3.up * 0.1f; currentHoldPoint = null; transform.SetParent(null); transform.localScale = originalLocalScale; // Выключаем коллайдеры дочерних болтов, чтобы колесо на земле не дрожало! if (wheelBolts != null) { foreach (var b in wheelBolts) if (b != null && b.TryGetComponent(out var bc)) bc.enabled = false; } if (partCollider != null) { if (partCollider is MeshCollider meshCol) meshCol.convex = true; partCollider.isTrigger = false; partCollider.enabled = true; } SetupDroppedRigidbody(); if (throwForce != Vector3.zero) rb.AddForce(throwForce, ForceMode.Impulse); } public void Install() { currentState = PartState.Installed; currentHoldPoint = null; unboltProgress = 0f; if (rb != null) Destroy(rb); transform.SetParent(originalParent); transform.localPosition = originalLocalPos; transform.localRotation = originalLocalRot; transform.localScale = originalLocalScale; if (partCollider != null) { partCollider.enabled = true; if (linkedWheelCollider != null || GetComponent() != null || installAsTrigger) partCollider.isTrigger = true; } // Сначала обновляем радиус WheelCollider (чтобы хорошее колесо вернуло полный радиус!), и только потом включаем его CarWheelCondition cond = GetComponent(); if (cond != null) cond.UpdateWheelColliderPhysics(); if (linkedWheelCollider != null) { linkedWheelCollider.enabled = true; linkedWheelCollider.motorTorque = 0f; linkedWheelCollider.brakeTorque = 0f; } if (wheelBolts != null) { foreach (var b in wheelBolts) { if (b != null) b.RecalculateOutwardDirection(); } } } private void CreateMountZone() { if (currentMountZone != null) return; currentMountZone = new GameObject($"MountZone_{gameObject.name}"); currentMountZone.transform.SetParent(originalParent); currentMountZone.transform.localPosition = originalLocalPos; currentMountZone.transform.localRotation = originalLocalRot; currentMountZone.transform.localScale = originalLocalScale; CarPartMountZone zone = currentMountZone.AddComponent(); zone.Initialize(this); } public void MakeMissingAtStart(GameObject customBricksPrefab = null, bool enableBrickPhysics = true) { if (currentState != PartState.Installed) return; CreateMountZone(); // Кирпичи ставим ТОЛЬКО если отсутствующая деталь — это колесо! if (linkedWheelCollider != null) { linkedWheelCollider.enabled = false; if (enableBrickPhysics) SpawnedBrickSupport = WheelBrickSupport.CreateUnderWheel(this, customBricksPrefab); } currentState = PartState.Dropped; gameObject.SetActive(false); } public void InstallIntoZone( Transform newParent, Vector3 slotLocalPos, Quaternion slotLocalRot, Vector3 slotLocalScale, WheelCollider newWheelCol, string slotWheelName) { originalParent = newParent; originalLocalPos = slotLocalPos; originalLocalScale = slotLocalScale; linkedWheelCollider = newWheelCol; gameObject.name = slotWheelName; // Определяем сторону ступицы, куда ставится колесо (-1 = левая, +1 = правая) float targetHubSideSign = slotLocalPos.x < 0f ? -1f : 1f; if (Mathf.Abs(slotLocalPos.x) < 0.05f && newWheelCol != null) targetHubSideSign = newWheelCol.transform.localPosition.x < 0f ? -1f : 1f; // Разворачиваем на 180 градусов ТОЛЬКО если левую модель колеса ставят на правую сторону (или наоборот) bool needsFlip = newWheelCol != null && (nativeWheelSideSign * targetHubSideSign) < 0f; originalLocalRot = needsFlip ? (slotLocalRot * Quaternion.Euler(0f, 180f, 0f)) : slotLocalRot; Install(); if (wheelBolts != null) { foreach (var b in wheelBolts) { if (b == null) continue; b.SetTightenedImmediate(false); b.RecalculateOutwardDirection(); } } CarController controller = GetComponentInParent(); if (controller != null && linkedWheelCollider != null) { controller.ReplaceWheelMesh(linkedWheelCollider, transform); } } private static bool HasTool(ToolType tool) { PlayerToolManager tm = PlayerToolManager.Instance; return tm == null || tm.currentTool == tool; } /// /// Возвращает снятую/проданную оригинальную деталь как новую запчасть из магазина /// (лежит на столе выдачи без ржавчины и грязи). /// public void SpawnAsNewPart(Vector3 worldPos) { if (currentState == PartState.Installed && gameObject.activeSelf) return; gameObject.SetActive(true); transform.SetParent(null); transform.position = worldPos; transform.localScale = originalLocalScale; CarPartVisuals v = GetComponent(); if (v != null) { v.SetDamage(0f); v.SetDirt(0f); } CarWheelCondition wc = GetComponent(); if (wc != null) wc.ApplyState(CarWheelCondition.TireState.Normal); EnginePart ep = GetComponent(); if (ep != null) ep.SetAsNew(); InitializeAsLoosePart(); } /// Убрать деталь со сцены после продажи (оригинал скрывается, чтобы его можно было купить заново). public void HideAsSold() { currentState = PartState.Dropped; if (rb != null) Destroy(rb); transform.SetParent(null); gameObject.SetActive(false); } }