Снятие колес работает, покраска тоже более менее. Физика просто говно щяс

This commit is contained in:
bybohka committed 2026-10-20 17:54:31 +03:00
1 parent d4c84b10df
commit 2ce853999d
67 files changed
+155919 -1996

No files matched your search

+17 -49
View File
@@ -1,24 +1,11 @@
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Стадии ремонта кузовной детали. Вычисляются из значений прогресса, отдельно хранить не нужно.
/// </summary>
public enum RepairStage
{
Healthy, // деталь целая, ржавчины нет
Rusted, // есть ржавчина - нужна зачистка
Cleaned, // ржавчина счищена, голый металл - нужна шпаклёвка
Puttied, // зашпаклёвано - нужна шлифовка
Sanded, // отшлифовано - нужна покраска
Repaired // покрашено, ремонт завершён
Healthy, Rusted, Cleaned, Puttied, Sanded, Repaired
}
/// <summary>
/// Состояние внешнего вида детали и стадии ремонта. Значения передаются в шейдер CarPaint_Rust
/// через MaterialPropertyBlock, только в те слоты материалов, где этот шейдер есть
/// (стёкла, фары и т.п. на той же детали не затрагиваются).
/// </summary>
[DisallowMultipleComponent]
public class CarPartVisuals : MonoBehaviour
{
@@ -29,13 +16,12 @@ public class CarPartVisuals : MonoBehaviour
private static readonly int SandProp = Shader.PropertyToID("_SandProgress");
private static readonly int PaintProp = Shader.PropertyToID("_PaintProgress");
// Порог, после которого стадия считается завершённой (и значение "защёлкивается" до 100%)
private const float DoneThreshold = 0.98f;
private const float RustCleanThreshold = 0.02f;
[Header("Состояние (можно крутить в инспекторе во время Play)")]
[Range(0f, 1f)] [SerializeField] private float rustInitial; // сколько детали было поражено
[Range(0f, 1f)] [SerializeField] private float rustCurrent; // сколько ржавчины осталось
[Header("Состояние детали")]
[Range(0f, 1f)] [SerializeField] private float rustInitial;
[Range(0f, 1f)] [SerializeField] private float rustCurrent;
[Range(0f, 1f)] [SerializeField] private float putty;
[Range(0f, 1f)] [SerializeField] private float sanding;
[Range(0f, 1f)] [SerializeField] private float paint;
@@ -50,6 +36,7 @@ public class CarPartVisuals : MonoBehaviour
private readonly List<Slot> slots = new List<Slot>();
private MaterialPropertyBlock block;
private bool initialized;
private bool colorInitialized;
public float CurrentRust => rustCurrent;
public float InitialRust => rustInitial;
@@ -68,7 +55,6 @@ public class CarPartVisuals : MonoBehaviour
}
}
/// <summary>Прогресс текущей стадии 0..1 (для подсказок и UI).</summary>
public float StageProgress
{
get
@@ -84,8 +70,6 @@ public class CarPartVisuals : MonoBehaviour
}
}
// ---------- Инициализация ----------
private void EnsureInit()
{
if (initialized) return;
@@ -96,35 +80,33 @@ public class CarPartVisuals : MonoBehaviour
foreach (Renderer r in GetComponentsInChildren<Renderer>(true))
{
// Не трогаем рендереры вложенных деталей (например, зеркало внутри двери)
if (owner != null && r.GetComponentInParent<CarPart>(true) != owner) continue;
Material[] mats = r.sharedMaterials;
for (int i = 0; i < mats.Length; i++)
{
if (mats[i] != null && mats[i].HasProperty(RustAmountProp))
{
// Автоматически запоминаем родной цвет машины из материала (например, синий!)
if (!colorInitialized && mats[i].HasProperty(BaseColorProp))
{
paintColor = mats[i].GetColor(BaseColorProp);
colorInitialized = true;
}
slots.Add(new Slot { renderer = r, materialIndex = i });
}
}
}
if (slots.Count == 0)
{
Debug.LogWarning($"[{name}] Нет материалов с шейдером CarPaint_Rust (свойство _RustAmount). " +
"Ржавчина и ремонт на этой детали не будут видны.", this);
}
}
private void OnValidate()
{
// Позволяет двигать слайдеры в инспекторе и сразу видеть результат
if (Application.isPlaying && initialized) Apply();
}
// ---------- Установка состояния ----------
/// <summary>Задать начальное повреждение детали (0 = целая). Сбрасывает все стадии ремонта.</summary>
public void SetDamage(float amount)
{
EnsureInit();
amount = Mathf.Clamp01(amount);
if (amount <= 0.001f) amount = 0f;
@@ -136,21 +118,17 @@ public class CarPartVisuals : MonoBehaviour
Apply();
}
/// <summary>Задать цвет краски без проверок (для генератора состояния).</summary>
public void SetPaintColor(Color newColor)
{
EnsureInit();
paintColor = newColor;
colorInitialized = true;
Apply();
}
// ---------- Действия инструментов ----------
// amount01 - доля полной работы за этот кадр (deltaTime / время полной обработки).
// Возвращают false, если инструмент сейчас не подходит этой стадии.
public bool CleanRust(float amount01)
{
if (Stage != RepairStage.Rusted) return false;
rustCurrent -= rustInitial * amount01;
if (rustCurrent <= RustCleanThreshold) rustCurrent = 0f;
Apply();
@@ -160,7 +138,6 @@ public class CarPartVisuals : MonoBehaviour
public bool ApplyPutty(float amount01)
{
if (Stage != RepairStage.Cleaned) return false;
putty = Mathf.Min(1f, putty + amount01);
if (putty >= DoneThreshold) putty = 1f;
Apply();
@@ -170,7 +147,6 @@ public class CarPartVisuals : MonoBehaviour
public bool Sand(float amount01)
{
if (Stage != RepairStage.Puttied) return false;
sanding = Mathf.Min(1f, sanding + amount01);
if (sanding >= DoneThreshold) sanding = 1f;
Apply();
@@ -180,34 +156,26 @@ public class CarPartVisuals : MonoBehaviour
public bool PaintRepair(float amount01)
{
if (Stage != RepairStage.Sanded) return false;
paint = Mathf.Min(1f, paint + amount01);
if (paint >= DoneThreshold) paint = 1f;
Apply();
return true;
}
/// <summary>Перекраска целой или уже отремонтированной детали в другой цвет.</summary>
public bool Recolor(Color newColor)
{
RepairStage s = Stage;
if (s != RepairStage.Healthy && s != RepairStage.Repaired) return false;
paintColor = newColor;
Apply();
SetPaintColor(newColor);
return true;
}
// ---------- Передача в шейдер ----------
private void Apply()
{
EnsureInit();
foreach (Slot s in slots)
{
if (s.renderer == null) continue;
s.renderer.GetPropertyBlock(block, s.materialIndex);
block.SetColor(BaseColorProp, paintColor);
block.SetFloat(RustInitialProp, rustInitial);