using UnityEngine; [RequireComponent(typeof(BoxCollider))] public class FluidCanister : MonoBehaviour, IInteractable { public enum CanisterState { OnGround, InHand } [Header("Тип и объем жидкости")] [SerializeField] private FluidType fluidType = FluidType.EngineOil; [SerializeField] private string canisterName = "Моторное масло 5W-40 (4L)"; [SerializeField] private float maxCapacityLiters = 4.0f; [SerializeField] private float currentLiters = 4.0f; [SerializeField] private float pourSpeedLitersPerSec = 0.85f; [SerializeField] private Color liquidColor = new Color(0.85f, 0.62f, 0.12f, 0.95f); [Header("Позиционирование в руках")] [SerializeField] private Vector3 inHandPositionOffset = new Vector3(0.24f, -0.22f, 0.55f); // Канистра держится справа внизу кадра и не закрывает подкапотное пространство private static readonly Vector3 HandPos = new Vector3(0.42f, -0.4f, 0.7f); private const float HandScale = 0.65f; private Vector3 groundScale; [SerializeField] private Vector3 inHandRotationOffset = new Vector3(0f, -25f, 0f); [Header("Точка носика канистры для струи")] [SerializeField] private Transform spoutPoint; private CanisterState state = CanisterState.OnGround; private Transform currentHoldPoint; private PlayerHands holderHands; private Rigidbody rb; private Collider col; private ParticleSystem pourParticleSystem; private bool isPouring = false; public FluidType Type => fluidType; public string FluidName => canisterName; public float CurrentLiters => currentLiters; public float MaxLiters => maxCapacityLiters; public Color LiquidColor => liquidColor; public CanisterState State => state; public float Fill01 => maxCapacityLiters > 0f ? currentLiters / maxCapacityLiters : 0f; /// Настройка канистры из кода (магазин автохимии, автонастройка). public void Configure(FluidType type, string title, float liters, Color color) { fluidType = type; canisterName = title; maxCapacityLiters = liters; currentLiters = liters; liquidColor = color; if (pourParticleSystem != null) { var main = pourParticleSystem.main; main.startColor = liquidColor; } } public static string GetDefaultTitle(FluidType type) { switch (type) { case FluidType.EngineOil: return "Моторное масло 5W-40 (4 л)"; case FluidType.Coolant: return "Антифриз G12 (5 л)"; case FluidType.BrakeFluid: return "Тормозная жидкость DOT-4 (1 л)"; case FluidType.WasherFluid: return "Омывайка -25°C (4 л)"; default: return "Канистра"; } } public static float GetDefaultLiters(FluidType type) { switch (type) { case FluidType.EngineOil: return 4f; case FluidType.Coolant: return 5f; case FluidType.BrakeFluid: return 1f; default: return 4f; } } public static Color GetDefaultColor(FluidType type) { switch (type) { case FluidType.EngineOil: return new Color(0.85f, 0.62f, 0.12f, 0.95f); case FluidType.Coolant: return new Color(0.95f, 0.20f, 0.45f, 0.95f); case FluidType.BrakeFluid: return new Color(0.95f, 0.93f, 0.8f, 0.95f); default: return new Color(0.15f, 0.65f, 1.0f, 0.95f); } } private void Awake() { col = GetComponent(); rb = GetComponent(); EnsurePourParticles(); } private void EnsurePourParticles() { if (pourParticleSystem != null) return; GameObject pObj = new GameObject("PourStreamParticles"); pObj.transform.SetParent(spoutPoint != null ? spoutPoint : transform, false); pObj.transform.localPosition = (spoutPoint == null) ? new Vector3(0f, 0.18f, 0.08f) : Vector3.zero; pObj.transform.localRotation = Quaternion.Euler(90f, 0f, 0f); pourParticleSystem = pObj.AddComponent(); var main = pourParticleSystem.main; main.startLifetime = 0.35f; main.startSpeed = 1.8f; main.startSize = 0.025f; main.startColor = liquidColor; main.simulationSpace = ParticleSystemSimulationSpace.World; main.playOnAwake = false; var emission = pourParticleSystem.emission; emission.rateOverTime = 65f; var shape = pourParticleSystem.shape; shape.shapeType = ParticleSystemShapeType.Cone; shape.angle = 4f; shape.radius = 0.008f; var renderer = pObj.GetComponent(); renderer.sharedMaterial = PartCatalog.ParticleMaterial; pourParticleSystem.Stop(); } public string GetPrompt() { if (state == CanisterState.OnGround) { int percent = Mathf.RoundToInt((currentLiters / maxCapacityLiters) * 100f); return $"[E] Взять {canisterName} ({currentLiters:F1} л / {percent}%)"; } return string.Empty; } public void Interact(GameObject interactor) { if (state == CanisterState.OnGround) { TakeToHands(interactor); } } private void TakeToHands(GameObject interactor) { PlayerHands hands = interactor.GetComponentInChildren(); if (hands == null) hands = interactor.GetComponentInParent(); if (hands == null || hands.IsHoldingAnything) return; state = CanisterState.InHand; holderHands = hands; hands.SetHeldCanister(this); Transform anchor = hands.HoldPoint != null && hands.HoldPoint.parent != null ? hands.HoldPoint.parent : hands.transform; currentHoldPoint = anchor; if (rb != null) Destroy(rb); if (col != null) col.enabled = false; ProceduralAudioManager.Instance?.Play(SfxId.Pickup, transform.position, 0.5f); transform.SetParent(anchor); transform.localPosition = HandPos; groundScale = transform.localScale; transform.localScale = groundScale * HandScale; transform.localRotation = Quaternion.Euler(inHandRotationOffset); } public void DropCanister() { if (state != CanisterState.InHand) return; StopPouring(); if (capMarker != null) capMarker.SetActive(false); state = CanisterState.OnGround; if (holderHands != null) holderHands.SetHeldCanister(null); holderHands = null; transform.SetParent(null); if (groundScale != Vector3.zero) transform.localScale = groundScale; if (currentHoldPoint != null) transform.position = currentHoldPoint.position + currentHoldPoint.forward * 0.5f; currentHoldPoint = null; if (col != null) col.enabled = true; if (rb == null) rb = gameObject.AddComponent(); rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; rb.mass = 4f; rb.linearDamping = 1.0f; rb.angularDamping = 2.5f; } private void Update() { if (state != CanisterState.InHand) return; if (GameInputLock.IsLocked) { StopPouring(); return; } // Сбросить канистру по клавише G или правой кнопке мыши if (Input.GetKeyDown(KeyCode.G) || Input.GetMouseButtonDown(1)) { DropCanister(); return; } // Проверяем прицеливание в горловину автомобиля Camera cam = currentHoldPoint != null ? currentHoldPoint.GetComponentInParent() : null; if (cam == null) cam = Camera.main; if (cam == null) return; Ray ray = new Ray(cam.transform.position, cam.transform.forward); bool aimingAtValidCap = false; CarFluidCap targetCap = null; if (Physics.Raycast(ray, out RaycastHit hit, 2.6f, ~0, QueryTriggerInteraction.Collide)) { targetCap = hit.collider.GetComponentInParent(); } if (targetCap != null && targetCap.Reservoir != null) { aimingAtValidCap = true; HandlePouringAtCap(targetCap); } else { StopPouring(); RestorationHUD.Instance?.Hide(); // подсказка поиска горловины выводится в строке прицела } UpdateCapMarker(targetCap); // Плавная анимация наклона канистры при заливании Quaternion targetRot = isPouring ? Quaternion.Euler(inHandRotationOffset + new Vector3(55f, -15f, -25f)) : Quaternion.Euler(inHandRotationOffset); Vector3 targetPos = isPouring ? HandPos + new Vector3(-0.22f, 0.14f, 0.12f) : HandPos; transform.localPosition = Vector3.Lerp(transform.localPosition, targetPos, Time.deltaTime * 10f); transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRot, Time.deltaTime * 10f); } private void HandlePouringAtCap(CarFluidCap cap) { if (!cap.IsOpen) { StopPouring(); RestorationHUD.Instance?.ShowCustomMessage($"Крышка закрыта!\nНажмите [E], чтобы открыть {cap.Reservoir.title}"); if (Input.GetKeyDown(KeyCode.E)) cap.Interact(gameObject); return; } if (cap.Reservoir.fluidType != fluidType) { StopPouring(); RestorationHUD.Instance?.ShowCustomMessage($"(!) Несовместимо!\nНельзя заливать {canisterName} в {cap.Reservoir.title}!"); return; } if (cap.Reservoir.IsFull) { StopPouring(); RestorationHUD.Instance?.ShowCustomMessage($"{cap.Reservoir.title} заполнен!\nУровень в норме (100%). Закрутите крышку [E]."); if (Input.GetKeyDown(KeyCode.E)) cap.Interact(gameObject); return; } if (currentLiters <= 0.01f) { StopPouring(); RestorationHUD.Instance?.ShowCustomMessage($"(!) Канистра пуста!\nВ канистре закончилась жидкость."); return; } // Показываем игроку статус заливки в HUD int carPercent = Mathf.RoundToInt(cap.Reservoir.FillPercent * 100f); int canPercent = Mathf.RoundToInt((currentLiters / maxCapacityLiters) * 100f); RestorationHUD.Instance?.ShowFluidPouringHUD( cap.Reservoir.title, fluidType, cap.Reservoir.currentLiters, cap.Reservoir.maxLiters, currentLiters, liquidColor); // Удержание левой кнопки мыши или E для заливания if (Input.GetMouseButton(0) || Input.GetKey(KeyCode.E)) { StartPouring(); float dt = Time.deltaTime; float poured = pourSpeedLitersPerSec * dt; poured = Mathf.Min(poured, currentLiters); float spaceInCar = cap.Reservoir.maxLiters - cap.Reservoir.currentLiters; poured = Mathf.Min(poured, spaceInCar); currentLiters -= poured; cap.Owner.Pour(fluidType, poured, 1f); ProceduralAudioManager.Instance?.SetLoop(this, LoopId.Pour, true, transform.position, 0.7f); } else { StopPouring(); } } private void StartPouring() { if (!isPouring) { isPouring = true; if (pourParticleSystem != null && !pourParticleSystem.isPlaying) pourParticleSystem.Play(); } } private void StopPouring() { if (isPouring) { isPouring = false; if (pourParticleSystem != null && pourParticleSystem.isPlaying) pourParticleSystem.Stop(); if (ProceduralAudioManager.Existing != null) ProceduralAudioManager.Existing.SetLoop(this, LoopId.Pour, false, transform.position); } } private void OnDisable() { StopPouring(); if (capMarker != null) capMarker.SetActive(false); } // ===================== ПОДСВЕТКА НУЖНОЙ ГОРЛОВИНЫ ===================== private static GameObject capMarker; private CarFluidCap bestCap; private float capSearchTimer; private static string FluidHuman(FluidType t) { switch (t) { case FluidType.EngineOil: return "горловину моторного масла (крышка на двигателе)"; case FluidType.Coolant: return "расширительный бачок антифриза"; case FluidType.BrakeFluid: return "бачок тормозной жидкости (у перегородки салона)"; default: return "бачок омывайки (синяя крышка)"; } } public string StatusHint => BuildSearchHint(); private string BuildSearchHint() { string head = $"{canisterName}: {currentLiters:F1} л"; if (bestCap == null) return $"{head}\nПодойдите к машине с открытым капотом — нужна {FluidHuman(fluidType)} | [G] Поставить"; VehicleInteraction car = bestCap.GetComponentInParent(); if (car != null) { foreach (CarPartAnimator a in car.GetComponentsInChildren()) { if (a.name.ToLowerInvariant().Contains("hood") && !a.IsOpen) return $"{head}\nКапот закрыт! Поставьте канистру [G] и откройте капот [E]"; } } int pct = Mathf.RoundToInt(bestCap.Reservoir.FillPercent * 100f); return $"{head}\nНаведите прицел на {FluidHuman(fluidType)} — отмечено зеленым шаром (сейчас {pct}%)\n[ЛКМ / E] лить | [G] поставить канистру"; } private void UpdateCapMarker(CarFluidCap aimed) { capSearchTimer -= Time.deltaTime; if (capSearchTimer <= 0f) { capSearchTimer = 0.5f; bestCap = null; float best = 6f; foreach (CarFluidCap cap in FindObjectsByType(FindObjectsSortMode.None)) { if (cap.Reservoir == null || cap.Reservoir.fluidType != fluidType) continue; float d = Vector3.Distance(cap.transform.position, transform.position); if (d < best) { best = d; bestCap = cap; } } } if (capMarker == null) { capMarker = GameObject.CreatePrimitive(PrimitiveType.Sphere); capMarker.name = "CapHighlightMarker"; Destroy(capMarker.GetComponent()); Renderer r = capMarker.GetComponent(); r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; r.sharedMaterial = PartCatalog.CreateUnlitMaterial(new Color(0.2f, 1f, 0.45f, 0.45f), true); } bool show = bestCap != null && aimed != bestCap && state == CanisterState.InHand; capMarker.SetActive(show); if (show) { float pulse = 0.17f + Mathf.Sin(Time.time * 6f) * 0.03f; capMarker.transform.position = bestCap.transform.position + Vector3.up * 0.1f; capMarker.transform.localScale = Vector3.one * pulse; } } }