Система ржавчины типо пашет. Еще очень сырая
This commit is contained in:
1 parent
5c934702c0
commit
f9eb14868d
18 files changed
+3885
-3634
No files matched your search
@@ -4,6 +4,7 @@ public class CarConditionGenerator : MonoBehaviour
|
||||
{
|
||||
[Header("Настройки спавна")]
|
||||
[Range(0f, 1f)] [SerializeField] private float rustProbability = 0.7f; // Шанс появления ржавчины
|
||||
[SerializeField] private float minRustAmount = 0.2f;
|
||||
[SerializeField] private float maxRustAmount = 0.85f;
|
||||
[SerializeField] private Color baseCarColor = Color.gray;
|
||||
|
||||
@@ -17,31 +18,27 @@ public class CarConditionGenerator : MonoBehaviour
|
||||
{
|
||||
CarPart[] allParts = GetComponentsInChildren<CarPart>(true);
|
||||
|
||||
foreach (var part in allParts)
|
||||
foreach (CarPart part in allParts)
|
||||
{
|
||||
CarPartVisuals visuals = part.GetComponent<CarPartVisuals>();
|
||||
if (visuals == null) visuals = part.gameObject.AddComponent<CarPartVisuals>();
|
||||
|
||||
// 1. Устанавливаем базовый цвет кузова
|
||||
// 1. Базовый цвет кузова
|
||||
visuals.SetPaintColor(baseCarColor);
|
||||
|
||||
// 2. Если деталь пластиковая (бампер) — пропускаем ржавчину
|
||||
// 2. Пластиковые детали (бампер) не ржавеют
|
||||
if (part.Data != null && !part.Data.canRust)
|
||||
{
|
||||
visuals.SetRust(0f);
|
||||
visuals.SetDamage(0f);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 3. Рандомизируем ржавчину для металла
|
||||
if (Random.value < rustProbability)
|
||||
{
|
||||
float randomRust = Random.Range(0.2f, maxRustAmount);
|
||||
visuals.SetRust(randomRust);
|
||||
}
|
||||
else
|
||||
{
|
||||
visuals.SetRust(0f);
|
||||
}
|
||||
// 3. Для металла - случайное начальное повреждение
|
||||
float damage = Random.value < rustProbability
|
||||
? Random.Range(minRustAmount, maxRustAmount)
|
||||
: 0f;
|
||||
|
||||
visuals.SetDamage(damage);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,45 +1,221 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(Renderer))]
|
||||
/// <summary>
|
||||
/// Стадии ремонта кузовной детали. Вычисляются из значений прогресса, отдельно хранить не нужно.
|
||||
/// </summary>
|
||||
public enum RepairStage
|
||||
{
|
||||
Healthy, // деталь целая, ржавчины нет
|
||||
Rusted, // есть ржавчина - нужна зачистка
|
||||
Cleaned, // ржавчина счищена, голый металл - нужна шпаклёвка
|
||||
Puttied, // зашпаклёвано - нужна шлифовка
|
||||
Sanded, // отшлифовано - нужна покраска
|
||||
Repaired // покрашено, ремонт завершён
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Состояние внешнего вида детали и стадии ремонта. Значения передаются в шейдер CarPaint_Rust
|
||||
/// через MaterialPropertyBlock, только в те слоты материалов, где этот шейдер есть
|
||||
/// (стёкла, фары и т.п. на той же детали не затрагиваются).
|
||||
/// </summary>
|
||||
[DisallowMultipleComponent]
|
||||
public class CarPartVisuals : MonoBehaviour
|
||||
{
|
||||
private Renderer partRenderer;
|
||||
private MaterialPropertyBlock propertyBlock;
|
||||
private static readonly int BaseColorProp = Shader.PropertyToID("_BaseColor");
|
||||
private static readonly int RustAmountProp = Shader.PropertyToID("_RustAmount");
|
||||
private static readonly int RustInitialProp = Shader.PropertyToID("_RustInitial");
|
||||
private static readonly int PuttyProp = Shader.PropertyToID("_PuttyProgress");
|
||||
private static readonly int SandProp = Shader.PropertyToID("_SandProgress");
|
||||
private static readonly int PaintProp = Shader.PropertyToID("_PaintProgress");
|
||||
|
||||
private static readonly int RustAmountProp = Shader.PropertyToID("_RustAmount");
|
||||
private static readonly int BaseColorProp = Shader.PropertyToID("_BaseColor");
|
||||
// Порог, после которого стадия считается завершённой (и значение "защёлкивается" до 100%)
|
||||
private const float DoneThreshold = 0.98f;
|
||||
private const float RustCleanThreshold = 0.02f;
|
||||
|
||||
[Range(0f, 1f)] [SerializeField] private float currentRust = 0f;
|
||||
[SerializeField] private Color currentColor = Color.white;
|
||||
[Header("Состояние (можно крутить в инспекторе во время Play)")]
|
||||
[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;
|
||||
[SerializeField] private Color paintColor = Color.white;
|
||||
|
||||
public float CurrentRust => currentRust;
|
||||
public Color CurrentColor => currentColor;
|
||||
|
||||
private void Awake()
|
||||
private struct Slot
|
||||
{
|
||||
partRenderer = GetComponent<Renderer>();
|
||||
propertyBlock = new MaterialPropertyBlock();
|
||||
public Renderer renderer;
|
||||
public int materialIndex;
|
||||
}
|
||||
|
||||
public void SetRust(float amount)
|
||||
private readonly List<Slot> slots = new List<Slot>();
|
||||
private MaterialPropertyBlock block;
|
||||
private bool initialized;
|
||||
|
||||
public float CurrentRust => rustCurrent;
|
||||
public float InitialRust => rustInitial;
|
||||
public Color CurrentColor => paintColor;
|
||||
|
||||
public RepairStage Stage
|
||||
{
|
||||
currentRust = Mathf.Clamp01(amount);
|
||||
ApplyProperties();
|
||||
get
|
||||
{
|
||||
if (rustInitial <= 0.001f) return RepairStage.Healthy;
|
||||
if (rustCurrent > RustCleanThreshold) return RepairStage.Rusted;
|
||||
if (putty < DoneThreshold) return RepairStage.Cleaned;
|
||||
if (sanding < DoneThreshold) return RepairStage.Puttied;
|
||||
if (paint < DoneThreshold) return RepairStage.Sanded;
|
||||
return RepairStage.Repaired;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Прогресс текущей стадии 0..1 (для подсказок и UI).</summary>
|
||||
public float StageProgress
|
||||
{
|
||||
get
|
||||
{
|
||||
switch (Stage)
|
||||
{
|
||||
case RepairStage.Rusted: return 1f - rustCurrent / Mathf.Max(rustInitial, 0.001f);
|
||||
case RepairStage.Cleaned: return putty;
|
||||
case RepairStage.Puttied: return sanding;
|
||||
case RepairStage.Sanded: return paint;
|
||||
default: return 1f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Инициализация ----------
|
||||
|
||||
private void EnsureInit()
|
||||
{
|
||||
if (initialized) return;
|
||||
initialized = true;
|
||||
block = new MaterialPropertyBlock();
|
||||
|
||||
CarPart owner = GetComponent<CarPart>();
|
||||
|
||||
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))
|
||||
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)
|
||||
{
|
||||
amount = Mathf.Clamp01(amount);
|
||||
if (amount <= 0.001f) amount = 0f;
|
||||
|
||||
rustInitial = amount;
|
||||
rustCurrent = amount;
|
||||
putty = 0f;
|
||||
sanding = 0f;
|
||||
paint = 0f;
|
||||
Apply();
|
||||
}
|
||||
|
||||
/// <summary>Задать цвет краски без проверок (для генератора состояния).</summary>
|
||||
public void SetPaintColor(Color newColor)
|
||||
{
|
||||
currentColor = newColor;
|
||||
ApplyProperties();
|
||||
paintColor = newColor;
|
||||
Apply();
|
||||
}
|
||||
|
||||
private void ApplyProperties()
|
||||
{
|
||||
if (partRenderer == null) return;
|
||||
// ---------- Действия инструментов ----------
|
||||
// amount01 - доля полной работы за этот кадр (deltaTime / время полной обработки).
|
||||
// Возвращают false, если инструмент сейчас не подходит этой стадии.
|
||||
|
||||
partRenderer.GetPropertyBlock(propertyBlock);
|
||||
propertyBlock.SetFloat(RustAmountProp, currentRust);
|
||||
propertyBlock.SetColor(BaseColorProp, currentColor);
|
||||
partRenderer.SetPropertyBlock(propertyBlock);
|
||||
public bool CleanRust(float amount01)
|
||||
{
|
||||
if (Stage != RepairStage.Rusted) return false;
|
||||
|
||||
rustCurrent -= rustInitial * amount01;
|
||||
if (rustCurrent <= RustCleanThreshold) rustCurrent = 0f;
|
||||
Apply();
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool ApplyPutty(float amount01)
|
||||
{
|
||||
if (Stage != RepairStage.Cleaned) return false;
|
||||
|
||||
putty = Mathf.Min(1f, putty + amount01);
|
||||
if (putty >= DoneThreshold) putty = 1f;
|
||||
Apply();
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool Sand(float amount01)
|
||||
{
|
||||
if (Stage != RepairStage.Puttied) return false;
|
||||
|
||||
sanding = Mathf.Min(1f, sanding + amount01);
|
||||
if (sanding >= DoneThreshold) sanding = 1f;
|
||||
Apply();
|
||||
return true;
|
||||
}
|
||||
|
||||
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();
|
||||
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);
|
||||
block.SetFloat(RustAmountProp, rustCurrent);
|
||||
block.SetFloat(PuttyProp, putty);
|
||||
block.SetFloat(SandProp, sanding);
|
||||
block.SetFloat(PaintProp, paint);
|
||||
s.renderer.SetPropertyBlock(block, s.materialIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class CarRestorationTool : MonoBehaviour
|
||||
{
|
||||
[Header("Параметры")]
|
||||
[SerializeField] private float cleanSpeed = 0.25f; // Сколько ржавчины снимается в секунду
|
||||
[SerializeField] private float range = 2.5f;
|
||||
[SerializeField] private LayerMask interactableLayer;
|
||||
|
||||
private Camera playerCamera;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
playerCamera = Camera.main;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
// Зажата ЛКМ — процесс чистки
|
||||
if (Input.GetMouseButton(0))
|
||||
{
|
||||
TryCleanPart();
|
||||
}
|
||||
}
|
||||
|
||||
private void TryCleanPart()
|
||||
{
|
||||
Ray ray = new Ray(playerCamera.transform.position, playerCamera.transform.forward);
|
||||
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, range, interactableLayer))
|
||||
{
|
||||
CarPartVisuals visuals = hit.collider.GetComponentInParent<CarPartVisuals>();
|
||||
|
||||
if (visuals != null && visuals.CurrentRust > 0f)
|
||||
{
|
||||
float newRust = visuals.CurrentRust - (cleanSpeed * Time.deltaTime);
|
||||
visuals.SetRust(newRust);
|
||||
|
||||
// Здесь можно запустить систему частиц искр (Particles) и звук шлифмашинки
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: be6ae3f5845047c6b571b3e3a10b5b44
|
||||
timeCreated: 1791330653
|
||||
Reference in new issue
Block a user