Files
Perekyp-2.0/Assets/Scripts/Car/Engine/OilDrainPlug.cs
T

188 lines
7.4 KiB
C#

using System.Collections;
using UnityEngine;
/// <summary>
/// Сливная пробка масляного поддона. Работает без домкрата (для заезда на эстакаду/рампу):
/// откручивается, сливает старое масло в таз и закручивается обратно перед заливом свежего масла.
/// </summary>
public class OilDrainPlug : MonoBehaviour, IInteractable
{
[Header("Настройки")]
[Tooltip("Если включить — откручивать и закручивать пробку можно только с гаечным ключом в руках")]
[SerializeField] private bool requireWrench = false;
[SerializeField] private float drainDuration = 3f;
private CarFluids fluids;
private Renderer[] plugRenderers;
private bool isUnscrewed;
private bool draining;
public bool IsUnscrewed => isUnscrewed;
public bool IsDraining => draining;
private void Awake()
{
fluids = GetComponentInParent<CarFluids>();
plugRenderers = GetComponentsInChildren<Renderer>(true);
}
private bool HasRequiredTool()
{
if (!requireWrench) return true;
return PlayerToolManager.Instance == null
|| PlayerToolManager.Instance.currentTool == ToolType.Wrench;
}
public string GetPrompt()
{
if (fluids == null) fluids = GetComponentInParent<CarFluids>();
if (fluids == null) return "Сливная пробка картера";
if (draining) return "Сливаем старое масло в таз...";
if (!HasRequiredTool())
{
return isUnscrewed
? "Сливная пробка выкручена (возьмите гаечный ключ [Tab], чтобы закрутить)"
: "Сливная пробка картера (нужен гаечный ключ [Tab])";
}
if (isUnscrewed)
return "[E] Закрутить сливную пробку";
float liters = fluids.EngineOil.currentLiters;
if (liters < 0.05f)
return "[E] Открутить сливную пробку (картер пуст)";
return $"[E] Открутить сливную пробку и слить масло ({liters:F1} л, состояние {Mathf.RoundToInt(fluids.EngineOil.quality * 100f)}%)";
}
public void Interact(GameObject interactor)
{
if (draining || !HasRequiredTool()) return;
if (fluids == null) fluids = GetComponentInParent<CarFluids>();
if (fluids == null) return;
// Если пробка выкручена — закручиваем её обратно
if (isUnscrewed)
{
isUnscrewed = false;
SetPlugVisible(true);
ProceduralAudioManager.Instance?.Play(SfxId.Ratchet, transform.position, 0.7f);
GameHUD.Notify("Сливная пробка закручена. Теперь можно залить свежее масло сверху", GameUI.Accent);
return;
}
// Откручиваем пробку
isUnscrewed = true;
SetPlugVisible(false);
ProceduralAudioManager.Instance?.Play(SfxId.Ratchet, transform.position, 0.7f);
if (fluids.EngineOil.currentLiters >= 0.05f)
{
StartCoroutine(DrainRoutine());
}
else
{
GameHUD.Notify("Сливная пробка выкручена (в картере нет масла)", GameUI.Muted);
}
}
private void SetPlugVisible(bool visible)
{
if (plugRenderers == null) return;
foreach (Renderer r in plugRenderers)
{
if (r != null) r.enabled = visible;
}
}
private Vector3 FindGroundBelowPlug()
{
Transform carRoot = fluids != null ? fluids.transform : transform.root;
RaycastHit[] hits = Physics.RaycastAll(transform.position, Vector3.down, 4f, ~0, QueryTriggerInteraction.Ignore);
System.Array.Sort(hits, (a, b) => a.distance.CompareTo(b.distance));
foreach (RaycastHit h in hits)
{
if (carRoot != null && h.collider.transform.IsChildOf(carRoot)) continue;
if (h.collider.GetComponentInParent<PlayerMovement>() != null) continue;
return h.point;
}
return transform.position + Vector3.down * 1.2f;
}
private IEnumerator DrainRoutine()
{
draining = true;
Vector3 ground = FindGroundBelowPlug();
float dropHeight = Mathf.Max(0.3f, transform.position.y - ground.y);
GameObject basin = EnginePartFactory.Prim(PrimitiveType.Cylinder, null, "OilBasin", ground + Vector3.up * 0.04f,
new Vector3(0.5f, 0.04f, 0.5f), EnginePartFactory.Metal);
GameObject oilSurface = EnginePartFactory.Prim(PrimitiveType.Cylinder, basin.transform, "Oil", new Vector3(0f, 0.2f, 0f),
new Vector3(0.9f, 0.1f, 0.9f), EnginePartFactory.Black);
oilSurface.transform.localScale = new Vector3(0.9f, 0.05f, 0.9f);
ParticleSystem stream = CreateStream(dropHeight);
ProceduralAudioManager.Instance?.Play(SfxId.OilDrain, transform.position, 0.8f);
float total = fluids.EngineOil.currentLiters;
float t = 0f;
float duration = Mathf.Max(0.5f, drainDuration);
while (t < duration)
{
t += Time.deltaTime;
float k = Mathf.Clamp01(t / duration);
fluids.EngineOil.currentLiters = Mathf.Lerp(total, 0f, k);
oilSurface.transform.localPosition = new Vector3(0f, Mathf.Lerp(-0.3f, 0.6f, k), 0f);
yield return null;
}
fluids.DrainEngineOil();
if (stream != null)
{
stream.Stop();
Destroy(stream.gameObject, 1.2f);
}
Destroy(basin, 25f);
draining = false;
GameHUD.Notify("Старое масло слито. Закрутите пробку [E] и залейте свежее масло сверху", GameUI.Accent);
}
private ParticleSystem CreateStream(float dropHeight)
{
GameObject pObj = new GameObject("OilStream");
pObj.transform.position = transform.position;
pObj.transform.rotation = Quaternion.LookRotation(Vector3.down);
ParticleSystem ps = pObj.AddComponent<ParticleSystem>();
// Подбираем время жизни струи под высоту рампы, чтобы частицы долетали до таза
const float startSpeed = 1.6f;
const float g = 9.81f;
float fallTime = (-startSpeed + Mathf.Sqrt(startSpeed * startSpeed + 2f * g * dropHeight)) / g;
var main = ps.main;
main.startLifetime = Mathf.Clamp(fallTime, 0.25f, 1.5f);
main.startSpeed = startSpeed;
main.startSize = 0.03f;
main.startColor = new Color(0.12f, 0.08f, 0.02f, 1f);
main.simulationSpace = ParticleSystemSimulationSpace.World;
main.gravityModifier = 1f;
var emission = ps.emission;
emission.rateOverTime = 80f;
var shape = ps.shape;
shape.shapeType = ParticleSystemShapeType.Cone;
shape.angle = 3f;
shape.radius = 0.01f;
var r = pObj.GetComponent<ParticleSystemRenderer>();
r.sharedMaterial = PartCatalog.ParticleMaterial;
ps.Play();
return ps;
}
}