First Commit
This commit is contained in:
commit
eed6b79efc
2836 files changed
+948481
No files matched your search
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6494620c5b7dcfc4c8bacbb928da92ce
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,451 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public enum SfxId { Ui, Error, Cash, Ratchet, JackClick, RelayClick, Starter, Notification, Drop, OilDrain, Pickup }
|
||||
public enum LoopId { Water, Pour, Grinder, Sander, Spray, Steam }
|
||||
|
||||
/// <summary>
|
||||
/// Процедурный аудио-синтезатор: все звуки игры генерируются через AudioClip.Create() без внешних файлов
|
||||
/// (струя мойки, бульканье жидкостей, трещотка ключа, болгарка, баллончик, домкрат, стартер, двигатель, касса, музыка).
|
||||
/// </summary>
|
||||
public class ProceduralAudioManager : MonoBehaviour
|
||||
{
|
||||
private const int SampleRate = 22050;
|
||||
|
||||
private static ProceduralAudioManager instance;
|
||||
private static bool quitting;
|
||||
|
||||
public static ProceduralAudioManager Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (instance != null) return instance;
|
||||
if (quitting || !Application.isPlaying) return null;
|
||||
instance = FindAnyObjectByType<ProceduralAudioManager>();
|
||||
if (instance == null)
|
||||
{
|
||||
GameObject go = new GameObject("ProceduralAudioManager");
|
||||
instance = go.AddComponent<ProceduralAudioManager>();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Существующий экземпляр без автосоздания (для OnDisable/OnDestroy).</summary>
|
||||
public static ProceduralAudioManager Existing => instance;
|
||||
|
||||
[Header("Громкость (сохраняется в PlayerPrefs)")]
|
||||
[Range(0f, 1f)] public float musicVolume = 0.35f;
|
||||
[Range(0f, 1f)] public float sfxVolume = 0.8f;
|
||||
|
||||
private readonly Dictionary<SfxId, AudioClip> sfx = new Dictionary<SfxId, AudioClip>();
|
||||
private readonly Dictionary<LoopId, AudioClip> loops = new Dictionary<LoopId, AudioClip>();
|
||||
private readonly Dictionary<object, AudioSource> loopSources = new Dictionary<object, AudioSource>();
|
||||
private readonly List<AudioSource> oneShotPool = new List<AudioSource>();
|
||||
private readonly List<AudioSource> engineSources = new List<AudioSource>();
|
||||
private AudioClip engineClip;
|
||||
private AudioSource musicSource;
|
||||
private System.Random rng = new System.Random(1337);
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (instance != null && instance != this)
|
||||
{
|
||||
Destroy(this);
|
||||
return;
|
||||
}
|
||||
instance = this;
|
||||
|
||||
musicVolume = PlayerPrefs.GetFloat("perekup_music", musicVolume);
|
||||
sfxVolume = PlayerPrefs.GetFloat("perekup_sfx", sfxVolume);
|
||||
|
||||
GenerateAll();
|
||||
|
||||
musicSource = gameObject.AddComponent<AudioSource>();
|
||||
musicSource.clip = GenerateMusic();
|
||||
musicSource.loop = true;
|
||||
musicSource.spatialBlend = 0f;
|
||||
musicSource.volume = musicVolume;
|
||||
musicSource.Play();
|
||||
}
|
||||
|
||||
private void OnApplicationQuit() => quitting = true;
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (instance == this) instance = null;
|
||||
}
|
||||
|
||||
public void SetVolumes(float music, float effects)
|
||||
{
|
||||
musicVolume = Mathf.Clamp01(music);
|
||||
sfxVolume = Mathf.Clamp01(effects);
|
||||
PlayerPrefs.SetFloat("perekup_music", musicVolume);
|
||||
PlayerPrefs.SetFloat("perekup_sfx", sfxVolume);
|
||||
if (musicSource != null) musicSource.volume = musicVolume;
|
||||
foreach (AudioSource s in engineSources)
|
||||
if (s != null) s.volume = Mathf.Min(s.volume, sfxVolume);
|
||||
}
|
||||
|
||||
// ===================== ПУБЛИЧНЫЙ API =====================
|
||||
|
||||
public void PlayUi() => Play(SfxId.Ui);
|
||||
|
||||
public void Play(SfxId id, Vector3? worldPos = null, float volume = 1f, float pitch = 1f)
|
||||
{
|
||||
if (!sfx.TryGetValue(id, out AudioClip clip) || clip == null) return;
|
||||
AudioSource src = GetFreeOneShot();
|
||||
src.transform.position = worldPos ?? Vector3.zero;
|
||||
src.spatialBlend = worldPos.HasValue ? 0.85f : 0f;
|
||||
src.pitch = pitch;
|
||||
src.volume = volume * sfxVolume;
|
||||
src.clip = clip;
|
||||
src.Play();
|
||||
}
|
||||
|
||||
/// <summary>Включает/выключает зацикленный звук для владельца (инструмент, канистра, двигатель).</summary>
|
||||
public void SetLoop(object owner, LoopId id, bool on, Vector3 worldPos, float volume = 1f, float pitch = 1f)
|
||||
{
|
||||
if (owner == null) return;
|
||||
loopSources.TryGetValue(owner, out AudioSource src);
|
||||
|
||||
if (!on)
|
||||
{
|
||||
if (src != null && src.isPlaying) src.Stop();
|
||||
return;
|
||||
}
|
||||
|
||||
if (src == null)
|
||||
{
|
||||
GameObject go = new GameObject("Loop_" + id);
|
||||
go.transform.SetParent(transform, false);
|
||||
src = go.AddComponent<AudioSource>();
|
||||
src.loop = true;
|
||||
src.playOnAwake = false;
|
||||
src.rolloffMode = AudioRolloffMode.Linear;
|
||||
src.maxDistance = 30f;
|
||||
loopSources[owner] = src;
|
||||
}
|
||||
|
||||
AudioClip clip = loops.TryGetValue(id, out AudioClip c) ? c : null;
|
||||
if (src.clip != clip)
|
||||
{
|
||||
src.clip = clip;
|
||||
src.Stop();
|
||||
}
|
||||
|
||||
src.transform.position = worldPos;
|
||||
src.spatialBlend = 0.6f;
|
||||
src.volume = volume * sfxVolume;
|
||||
src.pitch = pitch;
|
||||
if (!src.isPlaying && clip != null) src.Play();
|
||||
}
|
||||
|
||||
/// <summary>Создает источник звука двигателя на машине (тон меняется от SpeedKmH в CarController).</summary>
|
||||
public AudioSource CreateEngineSource(Transform car)
|
||||
{
|
||||
AudioSource src = car.gameObject.AddComponent<AudioSource>();
|
||||
src.clip = engineClip;
|
||||
src.loop = true;
|
||||
src.playOnAwake = false;
|
||||
src.spatialBlend = 0.75f;
|
||||
src.minDistance = 4f;
|
||||
src.maxDistance = 60f;
|
||||
src.rolloffMode = AudioRolloffMode.Linear;
|
||||
src.volume = 0f;
|
||||
engineSources.Add(src);
|
||||
return src;
|
||||
}
|
||||
|
||||
private AudioSource GetFreeOneShot()
|
||||
{
|
||||
foreach (AudioSource s in oneShotPool)
|
||||
if (s != null && !s.isPlaying) return s;
|
||||
|
||||
GameObject go = new GameObject("OneShot");
|
||||
go.transform.SetParent(transform, false);
|
||||
AudioSource src = go.AddComponent<AudioSource>();
|
||||
src.playOnAwake = false;
|
||||
src.rolloffMode = AudioRolloffMode.Linear;
|
||||
src.minDistance = 2f;
|
||||
src.maxDistance = 40f;
|
||||
oneShotPool.Add(src);
|
||||
return src;
|
||||
}
|
||||
|
||||
// ===================== СИНТЕЗ =====================
|
||||
|
||||
private float Rand() => (float)(rng.NextDouble() * 2.0 - 1.0);
|
||||
|
||||
private AudioClip MakeClip(string name, float[] data)
|
||||
{
|
||||
AudioClip clip = AudioClip.Create(name, data.Length, 1, SampleRate, false);
|
||||
clip.SetData(data, 0);
|
||||
return clip;
|
||||
}
|
||||
|
||||
private void GenerateAll()
|
||||
{
|
||||
sfx[SfxId.Ui] = MakeClip("ui", Tone(0.045f, 1250f, 0.25f, 60f));
|
||||
sfx[SfxId.Error] = MakeClip("error", Concat(Tone(0.12f, 220f, 0.35f, 12f), Silence(0.04f), Tone(0.16f, 180f, 0.35f, 10f)));
|
||||
sfx[SfxId.Notification] = MakeClip("notify", Concat(Tone(0.09f, 880f, 0.25f, 18f), Tone(0.14f, 1320f, 0.25f, 14f)));
|
||||
sfx[SfxId.Cash] = MakeClip("cash", Cash());
|
||||
sfx[SfxId.Ratchet] = MakeClip("ratchet", Clicks(3, 0.035f, 0.5f, 4200f));
|
||||
sfx[SfxId.JackClick] = MakeClip("jack", Clicks(1, 0.06f, 0.6f, 2300f));
|
||||
sfx[SfxId.RelayClick] = MakeClip("relay", Concat(Clicks(1, 0.02f, 0.7f, 1800f), Silence(0.09f), Clicks(1, 0.02f, 0.6f, 1600f), Silence(0.09f), Clicks(1, 0.02f, 0.6f, 1700f)));
|
||||
sfx[SfxId.Starter] = MakeClip("starter", Starter(1.1f));
|
||||
sfx[SfxId.Drop] = MakeClip("drop", Thud(0.25f));
|
||||
sfx[SfxId.Pickup] = MakeClip("pickup", Tone(0.06f, 520f, 0.3f, 40f));
|
||||
sfx[SfxId.OilDrain] = MakeClip("drain", Bubbles(2.5f, 0.7f));
|
||||
|
||||
loops[LoopId.Water] = MakeClip("water", NoiseLoop(2f, 0.30f, 0.55f, true));
|
||||
loops[LoopId.Pour] = MakeClip("pour", Bubbles(2f, 0.55f));
|
||||
loops[LoopId.Grinder] = MakeClip("grinder", Grinder(1f, 180f));
|
||||
loops[LoopId.Sander] = MakeClip("sander", Sander(1f));
|
||||
loops[LoopId.Spray] = MakeClip("spray", NoiseLoop(1.5f, 0.85f, 0.32f, false));
|
||||
loops[LoopId.Steam] = MakeClip("steam", NoiseLoop(2f, 0.6f, 0.35f, false));
|
||||
engineClip = MakeClip("engine", Engine(1f));
|
||||
}
|
||||
|
||||
private float[] Silence(float sec) => new float[Mathf.RoundToInt(sec * SampleRate)];
|
||||
|
||||
private float[] Concat(params float[][] parts)
|
||||
{
|
||||
int len = 0;
|
||||
foreach (float[] p in parts) len += p.Length;
|
||||
float[] r = new float[len];
|
||||
int o = 0;
|
||||
foreach (float[] p in parts)
|
||||
{
|
||||
p.CopyTo(r, o);
|
||||
o += p.Length;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
private float[] Tone(float sec, float freq, float amp, float decay)
|
||||
{
|
||||
int n = Mathf.RoundToInt(sec * SampleRate);
|
||||
float[] d = new float[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = (float)i / SampleRate;
|
||||
float env = Mathf.Exp(-t * decay) * Mathf.Clamp01(i / 60f);
|
||||
d[i] = Mathf.Sin(2f * Mathf.PI * freq * t) * amp * env;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
private float[] Clicks(int count, float spacing, float amp, float ring)
|
||||
{
|
||||
int n = Mathf.RoundToInt((count * spacing + 0.05f) * SampleRate);
|
||||
float[] d = new float[n];
|
||||
for (int c = 0; c < count; c++)
|
||||
{
|
||||
int start = Mathf.RoundToInt(c * spacing * SampleRate);
|
||||
for (int i = 0; i < 700 && start + i < n; i++)
|
||||
{
|
||||
float t = (float)i / SampleRate;
|
||||
float env = Mathf.Exp(-t * 180f);
|
||||
d[start + i] += (Rand() * 0.6f + Mathf.Sin(2f * Mathf.PI * ring * t) * 0.6f) * amp * env;
|
||||
}
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
private float[] Cash()
|
||||
{
|
||||
float[] a = Tone(0.7f, 1318.5f, 0.28f, 5f);
|
||||
float[] b = Tone(0.7f, 1760f, 0.22f, 6f);
|
||||
float[] coins = Clicks(4, 0.06f, 0.25f, 5200f);
|
||||
float[] r = new float[a.Length];
|
||||
int offB = Mathf.RoundToInt(0.08f * SampleRate);
|
||||
for (int i = 0; i < r.Length; i++)
|
||||
{
|
||||
r[i] = a[i];
|
||||
if (i >= offB && i - offB < b.Length) r[i] += b[i - offB];
|
||||
if (i < coins.Length) r[i] += coins[i];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
private float[] Thud(float sec)
|
||||
{
|
||||
int n = Mathf.RoundToInt(sec * SampleRate);
|
||||
float[] d = new float[n];
|
||||
float lp = 0f;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = (float)i / SampleRate;
|
||||
lp += (Rand() - lp) * 0.08f;
|
||||
d[i] = (Mathf.Sin(2f * Mathf.PI * 85f * t) * 0.6f + lp * 0.8f) * Mathf.Exp(-t * 22f);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
private float[] NoiseLoop(float sec, float brightness, float amp, bool gurgle)
|
||||
{
|
||||
int n = Mathf.RoundToInt(sec * SampleRate);
|
||||
float[] d = new float[n];
|
||||
float lp = 0f, lp2 = 0f;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = (float)i / SampleRate;
|
||||
float w = Rand();
|
||||
lp += (w - lp) * brightness;
|
||||
lp2 += (lp - lp2) * 0.5f;
|
||||
float v = brightness > 0.7f ? (w - lp2) : lp;
|
||||
float mod = gurgle ? 0.75f + 0.25f * Mathf.Sin(2f * Mathf.PI * 7f * t) * Mathf.Sin(2f * Mathf.PI * 3f * t) : 1f;
|
||||
d[i] = v * amp * mod;
|
||||
}
|
||||
d = Crossfade(d, 0.05f);
|
||||
return d;
|
||||
}
|
||||
|
||||
private float[] Bubbles(float sec, float amp)
|
||||
{
|
||||
int n = Mathf.RoundToInt(sec * SampleRate);
|
||||
float[] d = new float[n];
|
||||
float lp = 0f;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
lp += (Rand() - lp) * 0.12f;
|
||||
d[i] = lp * 0.25f * amp;
|
||||
}
|
||||
System.Random r = new System.Random(7);
|
||||
int glugs = Mathf.RoundToInt(sec * 9f);
|
||||
for (int g = 0; g < glugs; g++)
|
||||
{
|
||||
int start = r.Next(0, n - 2500);
|
||||
float f0 = 180f + (float)r.NextDouble() * 320f;
|
||||
for (int i = 0; i < 2400; i++)
|
||||
{
|
||||
float t = (float)i / SampleRate;
|
||||
float f = f0 * (1f + t * 9f);
|
||||
d[start + i] += Mathf.Sin(2f * Mathf.PI * f * t) * Mathf.Exp(-t * 45f) * 0.5f * amp;
|
||||
}
|
||||
}
|
||||
d = Crossfade(d, 0.05f);
|
||||
return d;
|
||||
}
|
||||
|
||||
private float[] Grinder(float sec, float freq)
|
||||
{
|
||||
int n = Mathf.RoundToInt(sec * SampleRate);
|
||||
float[] d = new float[n];
|
||||
float lp = 0f;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = (float)i / SampleRate;
|
||||
float v = 0f;
|
||||
for (int h = 1; h <= 6; h++)
|
||||
v += Mathf.Sin(2f * Mathf.PI * freq * h * t) / h;
|
||||
lp += (Rand() - lp) * 0.6f;
|
||||
d[i] = v * 0.18f + lp * 0.12f;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
private float[] Sander(float sec)
|
||||
{
|
||||
int n = Mathf.RoundToInt(sec * SampleRate);
|
||||
float[] d = new float[n];
|
||||
float lp = 0f;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = (float)i / SampleRate;
|
||||
lp += (Rand() - lp) * 0.35f;
|
||||
float scrape = 0.6f + 0.4f * Mathf.Sin(2f * Mathf.PI * 8f * t);
|
||||
d[i] = lp * 0.4f * scrape + Mathf.Sin(2f * Mathf.PI * 60f * t) * 0.08f;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
private float[] Starter(float sec)
|
||||
{
|
||||
int n = Mathf.RoundToInt(sec * SampleRate);
|
||||
float[] d = new float[n];
|
||||
float phase = 0f;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = (float)i / SampleRate;
|
||||
float f = 14f + t * 6f;
|
||||
phase += f / SampleRate;
|
||||
float pulse = Mathf.Pow(Mathf.Abs(Mathf.Sin(Mathf.PI * phase)), 6f);
|
||||
float whine = Mathf.Sin(2f * Mathf.PI * 340f * t) * 0.12f;
|
||||
d[i] = (pulse * 0.55f + whine + Rand() * 0.06f) * Mathf.Clamp01((sec - t) * 6f);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
private float[] Engine(float sec)
|
||||
{
|
||||
int n = Mathf.RoundToInt(sec * SampleRate);
|
||||
float[] d = new float[n];
|
||||
float lp = 0f;
|
||||
const float baseF = 45f;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = (float)i / SampleRate;
|
||||
float v = 0f;
|
||||
v += Mathf.Sin(2f * Mathf.PI * baseF * t) * 0.55f;
|
||||
v += Mathf.Sin(2f * Mathf.PI * baseF * 2f * t) * 0.35f;
|
||||
v += Mathf.Sin(2f * Mathf.PI * baseF * 3f * t) * 0.18f;
|
||||
v += Mathf.Sin(2f * Mathf.PI * baseF * 4f * t) * 0.10f;
|
||||
float firing = Mathf.Pow(Mathf.Abs(Mathf.Sin(Mathf.PI * baseF * 2f * t)), 4f);
|
||||
lp += (Rand() - lp) * 0.25f;
|
||||
d[i] = (v * 0.35f + firing * 0.25f + lp * 0.12f) * 0.8f;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
private AudioClip GenerateMusic()
|
||||
{
|
||||
// Спокойный эмбиент-пэд гаражного кооператива: Am – F – C – G по 4 секунды
|
||||
float[][] chords =
|
||||
{
|
||||
new[] { 220.00f, 261.63f, 329.63f },
|
||||
new[] { 174.61f, 220.00f, 261.63f },
|
||||
new[] { 196.00f, 261.63f, 329.63f },
|
||||
new[] { 196.00f, 246.94f, 293.66f }
|
||||
};
|
||||
const float chordLen = 4f;
|
||||
int per = Mathf.RoundToInt(chordLen * SampleRate);
|
||||
float[] d = new float[per * chords.Length];
|
||||
float lp = 0f;
|
||||
for (int c = 0; c < chords.Length; c++)
|
||||
{
|
||||
for (int i = 0; i < per; i++)
|
||||
{
|
||||
float t = (float)i / SampleRate;
|
||||
float env = Mathf.Clamp01(t / 1.2f) * Mathf.Clamp01((chordLen - t) / 1.2f);
|
||||
float v = 0f;
|
||||
foreach (float f in chords[c])
|
||||
{
|
||||
v += Mathf.Sin(2f * Mathf.PI * f * t) * 0.5f;
|
||||
v += Mathf.Sin(2f * Mathf.PI * f * 1.004f * t) * 0.35f;
|
||||
v += Mathf.Sin(2f * Mathf.PI * f * 0.5f * t) * 0.2f;
|
||||
}
|
||||
lp += (v - lp) * 0.08f;
|
||||
float tGlobal = (c * per + i) / (float)SampleRate;
|
||||
float bass = Mathf.Sin(2f * Mathf.PI * chords[c][0] * 0.25f * tGlobal) * 0.25f;
|
||||
d[c * per + i] = (lp * 0.09f + bass * 0.12f) * env;
|
||||
}
|
||||
}
|
||||
return MakeClip("music_ambient", d);
|
||||
}
|
||||
|
||||
/// <summary>Бесшовная петля: начало плавно смешивается с хвостом, хвост отрезается.</summary>
|
||||
private static float[] Crossfade(float[] d, float sec)
|
||||
{
|
||||
int n = Mathf.Min(d.Length / 2, Mathf.RoundToInt(sec * SampleRate));
|
||||
float[] r = new float[d.Length - n];
|
||||
System.Array.Copy(d, r, r.Length);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float a = (float)i / n;
|
||||
r[i] = d[i] * a + d[d.Length - n + i] * (1f - a);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 84c06286a75fdba499a5eb054dd50566
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d6f2d9e40ca94a6f91b1d7ae12a13b99
|
||||
timeCreated: 1789819363
|
||||
@@ -0,0 +1,99 @@
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Фары автомобиля: клавиша L в машине переключает Выключено → Ближний → Дальний свет.
|
||||
/// Прожекторы создаются автоматически по габаритам кузова; в темноте освещают дорогу.
|
||||
/// </summary>
|
||||
[DisallowMultipleComponent]
|
||||
public class CarLightingController : MonoBehaviour
|
||||
{
|
||||
public enum HeadlightMode { Off, Low, High }
|
||||
|
||||
[SerializeField] private KeyCode toggleKey = KeyCode.L;
|
||||
[SerializeField] private float lowRange = 32f, highRange = 75f;
|
||||
[SerializeField] private float lowAngle = 75f, highAngle = 48f;
|
||||
[SerializeField] private float lowIntensity = 6f, highIntensity = 14f;
|
||||
|
||||
public HeadlightMode Mode { get; private set; } = HeadlightMode.Off;
|
||||
|
||||
private Light[] headlights;
|
||||
private Light[] tailLights;
|
||||
private VehicleInteraction vehicle;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
vehicle = GetComponent<VehicleInteraction>();
|
||||
BuildLights();
|
||||
Apply();
|
||||
}
|
||||
|
||||
private void BuildLights()
|
||||
{
|
||||
Bounds b = EngineBayManager.LocalRendererBounds(transform, transform, null);
|
||||
float y = b.min.y + b.size.y * 0.42f;
|
||||
float x = b.size.x * 0.34f;
|
||||
|
||||
headlights = new Light[2];
|
||||
tailLights = new Light[2];
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
float side = i == 0 ? -1f : 1f;
|
||||
|
||||
GameObject h = new GameObject(i == 0 ? "Headlight_L" : "Headlight_R");
|
||||
h.transform.SetParent(transform, false);
|
||||
h.transform.localPosition = new Vector3(b.center.x + side * x, y, b.max.z - 0.05f);
|
||||
h.transform.localRotation = Quaternion.Euler(6f, 0f, 0f);
|
||||
Light l = h.AddComponent<Light>();
|
||||
l.type = LightType.Spot;
|
||||
l.color = new Color(1f, 0.95f, 0.82f);
|
||||
l.shadows = LightShadows.None;
|
||||
headlights[i] = l;
|
||||
|
||||
GameObject t = new GameObject(i == 0 ? "TailLight_L" : "TailLight_R");
|
||||
t.transform.SetParent(transform, false);
|
||||
t.transform.localPosition = new Vector3(b.center.x + side * x, y + 0.05f, b.min.z - 0.1f);
|
||||
Light tl = t.AddComponent<Light>();
|
||||
tl.type = LightType.Point;
|
||||
tl.color = new Color(1f, 0.1f, 0.05f);
|
||||
tl.range = 3.5f;
|
||||
tl.intensity = 1.5f;
|
||||
tl.shadows = LightShadows.None;
|
||||
tailLights[i] = tl;
|
||||
}
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (vehicle == null || !vehicle.isPlayerInside || GameInputLock.IsLocked) return;
|
||||
if (Input.GetKeyDown(toggleKey))
|
||||
{
|
||||
Mode = (HeadlightMode)(((int)Mode + 1) % 3);
|
||||
Apply();
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.RelayClick, transform.position, 0.3f, 1.6f);
|
||||
string text = Mode == HeadlightMode.Off ? "Фары выключены" : (Mode == HeadlightMode.Low ? "Ближний свет" : "Дальний свет");
|
||||
GameHUD.Notify(text, GameUI.Muted);
|
||||
}
|
||||
}
|
||||
|
||||
public void SetMode(HeadlightMode mode)
|
||||
{
|
||||
Mode = mode;
|
||||
Apply();
|
||||
}
|
||||
|
||||
private void Apply()
|
||||
{
|
||||
bool on = Mode != HeadlightMode.Off;
|
||||
foreach (Light l in headlights)
|
||||
{
|
||||
if (l == null) continue;
|
||||
l.enabled = on;
|
||||
l.range = Mode == HeadlightMode.High ? highRange : lowRange;
|
||||
l.spotAngle = Mode == HeadlightMode.High ? highAngle : lowAngle;
|
||||
l.intensity = Mode == HeadlightMode.High ? highIntensity : lowIntensity;
|
||||
l.transform.localRotation = Quaternion.Euler(Mode == HeadlightMode.High ? 2f : 7f, 0f, 0f);
|
||||
}
|
||||
foreach (Light l in tailLights)
|
||||
if (l != null) l.enabled = on;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1ab0b87950c3b294abdcfdc317abc444
|
||||
@@ -0,0 +1,60 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class CarOrbitCamera : MonoBehaviour
|
||||
{
|
||||
[Header("Цель")]
|
||||
private Transform target; // Убрали SerializeField, теперь цель задается через код
|
||||
[SerializeField] private Vector3 targetOffset = new Vector3(0, 1.2f, 0);
|
||||
|
||||
[Header("Настройки орбиты")]
|
||||
[SerializeField] private float distance = 5.5f;
|
||||
[SerializeField] private float mouseSensitivity = 150f;
|
||||
|
||||
[Header("Ограничения")]
|
||||
[SerializeField] private float yMinLimit = 0f;
|
||||
[SerializeField] private float yMaxLimit = 80f;
|
||||
|
||||
private float currentX = 0f;
|
||||
private float currentY = 20f;
|
||||
|
||||
// НОВЫЙ МЕТОД: Принимает новую машину и сразу сбрасывает углы
|
||||
public void SetTarget(Transform newTarget)
|
||||
{
|
||||
target = newTarget;
|
||||
ResetCameraAngles();
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
if (target != null)
|
||||
{
|
||||
currentX = target.eulerAngles.y;
|
||||
}
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
if (target == null) return; // Если цели нет (игрок пешком), камера ничего не делает
|
||||
|
||||
currentX += Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
|
||||
currentY -= Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
|
||||
|
||||
currentY = Mathf.Clamp(currentY, yMinLimit, yMaxLimit);
|
||||
|
||||
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
|
||||
Vector3 focusPoint = target.position + targetOffset;
|
||||
Vector3 position = focusPoint - (rotation * Vector3.forward * distance);
|
||||
|
||||
transform.position = position;
|
||||
transform.rotation = rotation;
|
||||
}
|
||||
|
||||
public void ResetCameraAngles()
|
||||
{
|
||||
if (target != null)
|
||||
{
|
||||
currentX = target.eulerAngles.y;
|
||||
currentY = 20f;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3eb72160ab004995bc77130c1806ee13
|
||||
timeCreated: 1789825076
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 12fd7b2e6f605954299e41bf16150c37
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,568 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Подкапотное пространство автомобиля: находит съемные агрегаты ДВС и бачки жидкостей,
|
||||
/// при отсутствии отдельных мешей в модели генерирует аккуратный 3D моторный отсек под капотом,
|
||||
/// моделирует запуск двигателя, мощность, тормоза, перегрев и коды ошибок OBD.
|
||||
/// </summary>
|
||||
[DisallowMultipleComponent]
|
||||
public class EngineBayManager : MonoBehaviour
|
||||
{
|
||||
[Header("Автонастройка")]
|
||||
[Tooltip("Достраивать недостающие узлы (АКБ, свечи, фильтры, радиатор, генератор, бачки) процедурно")]
|
||||
public bool autoBuildMissing = true;
|
||||
public Transform engineBayRoot;
|
||||
|
||||
[Header("Перегрев")]
|
||||
[SerializeField] private float overheatDelay = 30f;
|
||||
|
||||
private CarFluids fluids;
|
||||
private bool built;
|
||||
private float overheatTimer;
|
||||
private float steamTimer;
|
||||
private ParticleSystem steam;
|
||||
|
||||
public bool EngineRunning { get; private set; }
|
||||
public bool IsOverheating => overheatTimer >= overheatDelay;
|
||||
public CarFluids Fluids => fluids != null ? fluids : (fluids = GetComponent<CarFluids>());
|
||||
|
||||
private static bool Diploma => GameEconomyManager.Instance == null || GameEconomyManager.Instance.DiplomaFeatures;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
fluids = GetComponent<CarFluids>();
|
||||
if (fluids == null) fluids = gameObject.AddComponent<CarFluids>();
|
||||
EnsureBuilt();
|
||||
}
|
||||
|
||||
public void EnsureBuilt()
|
||||
{
|
||||
if (built) return;
|
||||
built = true;
|
||||
BuildEngineBay(transform, autoBuildMissing);
|
||||
if (fluids == null) fluids = GetComponent<CarFluids>();
|
||||
if (fluids != null) fluids.InitializeCaps();
|
||||
CreateSteamEffect();
|
||||
}
|
||||
|
||||
// ===================== ПОСТРОЕНИЕ ОТСЕКА =====================
|
||||
|
||||
/// <summary>
|
||||
/// Находит существующие подкапотные детали по данным/именам и добавляет им EnginePart,
|
||||
/// а недостающие узлы генерирует под капотом. Вызывается и из Editor-автонастройки, и в рантайме.
|
||||
/// </summary>
|
||||
public static void BuildEngineBay(Transform car, bool buildMissing)
|
||||
{
|
||||
PartCatalog cat = PartCatalog.Instance;
|
||||
HashSet<EnginePartType> present = new HashSet<EnginePartType>();
|
||||
|
||||
foreach (EnginePart ep in car.GetComponentsInChildren<EnginePart>(true))
|
||||
present.Add(ep.partType);
|
||||
|
||||
// 1. Существующие CarPart с данными агрегатов
|
||||
foreach (CarPart part in car.GetComponentsInChildren<CarPart>(true))
|
||||
{
|
||||
if (part.GetComponent<EnginePart>() != null) continue;
|
||||
if (TryDetectType(part.Data, part.name, cat, out EnginePartType type) && !present.Contains(type))
|
||||
{
|
||||
EnginePart ep = part.gameObject.AddComponent<EnginePart>();
|
||||
ep.partType = type;
|
||||
ep.SetAsNew();
|
||||
if (part.Data == null) part.SetData(cat.GetEngineData(type), EnginePartFactory.GetMass(type));
|
||||
present.Add(type);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Меши агрегатов без CarPart (например, covet_Alternator) превращаем в съемные детали
|
||||
foreach (MeshRenderer r in car.GetComponentsInChildren<MeshRenderer>(true))
|
||||
{
|
||||
if (r.GetComponent<CarPart>() != null || r.GetComponentInParent<CarPart>() != null) continue;
|
||||
string n = r.name.ToLowerInvariant();
|
||||
EnginePartType type;
|
||||
if (n.Contains("alternator")) type = EnginePartType.Alternator;
|
||||
else if (n.Contains("battery")) type = EnginePartType.Battery;
|
||||
else continue;
|
||||
if (present.Contains(type)) continue;
|
||||
|
||||
GameObject go = r.gameObject;
|
||||
go.layer = EnginePartFactory.InteractLayer;
|
||||
if (go.GetComponent<Collider>() == null)
|
||||
{
|
||||
BoxCollider bc = go.AddComponent<BoxCollider>();
|
||||
bc.isTrigger = true;
|
||||
}
|
||||
CarPart cp = go.AddComponent<CarPart>();
|
||||
cp.SetData(cat.GetEngineData(type), EnginePartFactory.GetMass(type));
|
||||
EnginePart ep = go.AddComponent<EnginePart>();
|
||||
ep.partType = type;
|
||||
ep.SetAsNew();
|
||||
present.Add(type);
|
||||
}
|
||||
|
||||
if (!buildMissing) return;
|
||||
|
||||
// 3. Геометрия моторного отсека в координатах машины
|
||||
ComputeBayFrame(car, out Vector3 center, out float width, out float length, out float yTop, out float panY);
|
||||
|
||||
Transform bay = car.Find("Engine_Bay");
|
||||
if (bay == null)
|
||||
{
|
||||
bay = new GameObject("Engine_Bay").transform;
|
||||
bay.SetParent(car, false);
|
||||
bay.localPosition = Vector3.zero;
|
||||
bay.localRotation = Quaternion.identity;
|
||||
}
|
||||
|
||||
float zFront = center.z + length * 0.5f;
|
||||
float zRear = center.z - length * 0.5f;
|
||||
float cx = center.x;
|
||||
|
||||
void Make(EnginePartType t, Vector3 p)
|
||||
{
|
||||
if (present.Contains(t)) return;
|
||||
EnginePartFactory.CreatePart(t, bay, p, Quaternion.identity, width);
|
||||
present.Add(t);
|
||||
}
|
||||
|
||||
Make(EnginePartType.Battery, new Vector3(cx - width * 0.34f, yTop - 0.17f, zRear + length * 0.36f));
|
||||
Make(EnginePartType.SparkPlugs, new Vector3(cx, yTop - 0.15f, center.z - length * 0.04f));
|
||||
Make(EnginePartType.AirFilter, new Vector3(cx + width * 0.30f, yTop - 0.12f, zRear + length * 0.38f));
|
||||
Make(EnginePartType.Radiator, new Vector3(cx, yTop - 0.27f, zFront - 0.03f));
|
||||
Make(EnginePartType.Alternator, new Vector3(cx + width * 0.14f, yTop - 0.33f, zFront - length * 0.32f));
|
||||
Make(EnginePartType.OilFilter, new Vector3(cx - width * 0.12f, yTop - 0.40f, center.z));
|
||||
|
||||
// Бачки и горловины технических жидкостей
|
||||
HashSet<FluidType> caps = new HashSet<FluidType>();
|
||||
foreach (Transform t in car.GetComponentsInChildren<Transform>(true))
|
||||
{
|
||||
string n = t.name.ToLowerInvariant().Replace(" ", "");
|
||||
if (n.Contains("oilcap")) caps.Add(FluidType.EngineOil);
|
||||
else if (n.Contains("coolantcap") || n.Contains("radcap") || n.Contains("radiatorcap")) caps.Add(FluidType.Coolant);
|
||||
else if (n.Contains("washerfluidcap") || n.Contains("washercap")) caps.Add(FluidType.WasherFluid);
|
||||
else if (n.Contains("brakefluidcap") || n.Contains("brakecap")) caps.Add(FluidType.BrakeFluid);
|
||||
}
|
||||
|
||||
if (!caps.Contains(FluidType.EngineOil))
|
||||
EnginePartFactory.CreateReservoir(FluidType.EngineOil, bay, new Vector3(cx + 0.1f, yTop - 0.09f, center.z + length * 0.12f));
|
||||
if (!caps.Contains(FluidType.Coolant))
|
||||
EnginePartFactory.CreateReservoir(FluidType.Coolant, bay, new Vector3(cx + width * 0.36f, yTop - 0.15f, zFront - length * 0.26f));
|
||||
if (!caps.Contains(FluidType.BrakeFluid))
|
||||
EnginePartFactory.CreateReservoir(FluidType.BrakeFluid, bay, new Vector3(cx - width * 0.30f, yTop - 0.10f, zRear + 0.07f));
|
||||
if (!caps.Contains(FluidType.WasherFluid))
|
||||
EnginePartFactory.CreateReservoir(FluidType.WasherFluid, bay, new Vector3(cx - width * 0.36f, yTop - 0.17f, zFront - length * 0.14f));
|
||||
|
||||
if (car.GetComponentInChildren<OilDipstick>(true) == null)
|
||||
EnginePartFactory.CreateDipstick(bay, new Vector3(cx - 0.17f, yTop - 0.07f, center.z + length * 0.08f));
|
||||
|
||||
if (car.GetComponentInChildren<OilDrainPlug>(true) == null)
|
||||
EnginePartFactory.CreateOilPan(bay, new Vector3(cx, panY, center.z - length * 0.1f), width);
|
||||
}
|
||||
|
||||
private static bool TryDetectType(CarPartData data, string objName, PartCatalog cat, out EnginePartType type)
|
||||
{
|
||||
type = EnginePartType.Battery;
|
||||
if (data != null)
|
||||
{
|
||||
if (data == cat.battery) { type = EnginePartType.Battery; return true; }
|
||||
if (data == cat.sparkPlugs) { type = EnginePartType.SparkPlugs; return true; }
|
||||
if (data == cat.airFilter) { type = EnginePartType.AirFilter; return true; }
|
||||
if (data == cat.oilFilter) { type = EnginePartType.OilFilter; return true; }
|
||||
if (data == cat.radiator) { type = EnginePartType.Radiator; return true; }
|
||||
if (data == cat.alternator) { type = EnginePartType.Alternator; return true; }
|
||||
if (data == cat.fuelFilter) { type = EnginePartType.FuelFilter; return true; }
|
||||
}
|
||||
|
||||
string n = ((data != null ? data.name + " " + data.partName : "") + " " + objName).ToLowerInvariant();
|
||||
if (n.Contains("battery") || n.Contains("аккумул")) { type = EnginePartType.Battery; return true; }
|
||||
if (n.Contains("spark") || n.Contains("свеч")) { type = EnginePartType.SparkPlugs; return true; }
|
||||
if (n.Contains("airfilter") || n.Contains("воздушн") || n.Contains("carburettor")) { type = EnginePartType.AirFilter; return true; }
|
||||
if (n.Contains("oilfilter") || n.Contains("масляный фильтр")) { type = EnginePartType.OilFilter; return true; }
|
||||
if (n.Contains("fuelfilter") || n.Contains("fuilfilter") || n.Contains("топлив")) { type = EnginePartType.FuelFilter; return true; }
|
||||
if (n.Contains("radiator") || n.Contains("радиатор")) { type = EnginePartType.Radiator; return true; }
|
||||
if (n.Contains("alternator") || n.Contains("генератор")) { type = EnginePartType.Alternator; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Рассчитывает зону моторного отсека под капотом в локальных координатах машины.</summary>
|
||||
public static void ComputeBayFrame(Transform car, out Vector3 center, out float width, out float length, out float yTop, out float panY)
|
||||
{
|
||||
Bounds carB = LocalRendererBounds(car, car, null);
|
||||
Transform hood = null;
|
||||
foreach (CarPart p in car.GetComponentsInChildren<CarPart>(true))
|
||||
{
|
||||
string n = (p.name + " " + (p.Data != null ? p.Data.partName : "")).ToLowerInvariant();
|
||||
if ((n.Contains("hood") || n.Contains("капот")) && !n.Contains("scoop"))
|
||||
{
|
||||
hood = p.transform;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (hood == null)
|
||||
{
|
||||
foreach (CarPart p in car.GetComponentsInChildren<CarPart>(true))
|
||||
if (p.name.ToLowerInvariant().Contains("hood")) { hood = p.transform; break; }
|
||||
}
|
||||
|
||||
float groundY = carB.min.y;
|
||||
WheelCollider[] wcs = car.GetComponentsInChildren<WheelCollider>(true);
|
||||
if (wcs.Length > 0)
|
||||
{
|
||||
float sum = 0f;
|
||||
foreach (WheelCollider wc in wcs)
|
||||
sum += car.InverseTransformPoint(wc.transform.position).y - wc.radius;
|
||||
groundY = sum / wcs.Length;
|
||||
}
|
||||
|
||||
if (hood != null)
|
||||
{
|
||||
Bounds hb = LocalRendererBounds(car, hood, null);
|
||||
width = Mathf.Clamp(hb.size.x * 0.82f, 0.9f, 1.5f);
|
||||
length = Mathf.Clamp(hb.size.z * 0.82f, 0.6f, 1.3f);
|
||||
center = new Vector3(hb.center.x, 0f, hb.center.z - hb.size.z * 0.02f);
|
||||
yTop = hb.min.y + Mathf.Min(0.06f, hb.size.y * 0.3f) - 0.03f;
|
||||
}
|
||||
else
|
||||
{
|
||||
width = Mathf.Clamp(carB.size.x * 0.62f, 0.9f, 1.5f);
|
||||
length = Mathf.Clamp(carB.size.z * 0.24f, 0.6f, 1.2f);
|
||||
center = new Vector3(carB.center.x, 0f, carB.max.z - length * 0.5f - 0.3f);
|
||||
yTop = groundY + carB.size.y * 0.62f;
|
||||
}
|
||||
|
||||
// Капот не должен «проваливаться» ниже уровня колес
|
||||
yTop = Mathf.Max(yTop, groundY + 0.62f);
|
||||
panY = groundY + 0.2f;
|
||||
}
|
||||
|
||||
public static Bounds LocalRendererBounds(Transform space, Transform root, Transform exclude)
|
||||
{
|
||||
bool has = false;
|
||||
Bounds result = new Bounds(Vector3.zero, Vector3.zero);
|
||||
foreach (MeshFilter mf in root.GetComponentsInChildren<MeshFilter>(true))
|
||||
{
|
||||
if (mf.sharedMesh == null) continue;
|
||||
if (exclude != null && mf.transform.IsChildOf(exclude)) continue;
|
||||
Renderer r = mf.GetComponent<Renderer>();
|
||||
if (r == null || !r.enabled) continue;
|
||||
Bounds mb = mf.sharedMesh.bounds;
|
||||
Vector3 e = mb.extents;
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
Vector3 corner = mb.center + new Vector3(i % 2 == 0 ? -e.x : e.x, (i / 2) % 2 == 0 ? -e.y : e.y, i / 4 == 0 ? -e.z : e.z);
|
||||
Vector3 p = space.InverseTransformPoint(mf.transform.TransformPoint(corner));
|
||||
if (!has) { result = new Bounds(p, Vector3.zero); has = true; }
|
||||
else result.Encapsulate(p);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void CreateSteamEffect()
|
||||
{
|
||||
if (steam != null || !Application.isPlaying) return;
|
||||
ComputeBayFrame(transform, out Vector3 center, out _, out _, out float yTop, out _);
|
||||
|
||||
GameObject pObj = new GameObject("EngineSteam");
|
||||
pObj.transform.SetParent(transform, false);
|
||||
pObj.transform.localPosition = new Vector3(center.x, yTop + 0.05f, center.z);
|
||||
pObj.transform.localRotation = Quaternion.LookRotation(Vector3.up);
|
||||
|
||||
steam = pObj.AddComponent<ParticleSystem>();
|
||||
var main = steam.main;
|
||||
main.startLifetime = 2.2f;
|
||||
main.startSpeed = 1.4f;
|
||||
main.startSize = new ParticleSystem.MinMaxCurve(0.35f, 0.8f);
|
||||
main.startColor = new Color(0.95f, 0.95f, 0.95f, 0.45f);
|
||||
main.simulationSpace = ParticleSystemSimulationSpace.World;
|
||||
main.playOnAwake = false;
|
||||
main.maxParticles = 300;
|
||||
var emission = steam.emission;
|
||||
emission.rateOverTime = 35f;
|
||||
var shape = steam.shape;
|
||||
shape.shapeType = ParticleSystemShapeType.Box;
|
||||
shape.scale = new Vector3(0.6f, 0.6f, 0.05f);
|
||||
var sol = steam.sizeOverLifetime;
|
||||
sol.enabled = true;
|
||||
sol.size = new ParticleSystem.MinMaxCurve(1f, AnimationCurve.Linear(0f, 0.6f, 1f, 2.2f));
|
||||
var col = steam.colorOverLifetime;
|
||||
col.enabled = true;
|
||||
Gradient g = new Gradient();
|
||||
g.SetKeys(new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) },
|
||||
new[] { new GradientAlphaKey(0.5f, 0f), new GradientAlphaKey(0f, 1f) });
|
||||
col.color = g;
|
||||
pObj.GetComponent<ParticleSystemRenderer>().sharedMaterial = PartCatalog.ParticleMaterial;
|
||||
steam.Stop();
|
||||
}
|
||||
|
||||
// ===================== СОСТОЯНИЕ АГРЕГАТОВ =====================
|
||||
|
||||
public EnginePart GetPart(EnginePartType type)
|
||||
{
|
||||
foreach (EnginePart ep in GetComponentsInChildren<EnginePart>(false))
|
||||
if (ep.partType == type && ep.IsInstalled) return ep;
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<EnginePart> InstalledParts()
|
||||
{
|
||||
List<EnginePart> list = new List<EnginePart>();
|
||||
foreach (EnginePart ep in GetComponentsInChildren<EnginePart>(false))
|
||||
if (ep.IsInstalled) list.Add(ep);
|
||||
return list;
|
||||
}
|
||||
|
||||
public bool TryStart(out string reason)
|
||||
{
|
||||
reason = string.Empty;
|
||||
if (!Diploma)
|
||||
{
|
||||
EngineRunning = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
EnginePart battery = GetPart(EnginePartType.Battery);
|
||||
EnginePart plugs = GetPart(EnginePartType.SparkPlugs);
|
||||
|
||||
if (battery == null)
|
||||
reason = "Двигатель не заводится! Нет аккумулятора — установите АКБ под капотом";
|
||||
else if (battery.charge < 20f)
|
||||
reason = "Двигатель не заводится! Аккумулятор разряжен. Проверьте аккумулятор и свечи под капотом";
|
||||
else if (plugs == null)
|
||||
reason = "Двигатель не заводится! Нет свечей зажигания. Проверьте аккумулятор и свечи под капотом";
|
||||
else if (plugs.condition < 5f)
|
||||
reason = "Двигатель не заводится! Свечи зажигания убиты";
|
||||
|
||||
if (!string.IsNullOrEmpty(reason))
|
||||
{
|
||||
EngineRunning = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Пуск стартером немного садит АКБ
|
||||
battery.charge = Mathf.Max(0f, battery.charge - 1.5f);
|
||||
EngineRunning = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void StopEngine() => EngineRunning = false;
|
||||
|
||||
/// <summary>Коэффициент мощности двигателя 0.4–1.0 (свечи, воздушный фильтр, масло, перегрев).</summary>
|
||||
public float PowerMultiplier
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!Diploma) return 1f;
|
||||
float m = 1f;
|
||||
|
||||
EnginePart plugs = GetPart(EnginePartType.SparkPlugs);
|
||||
if (plugs != null && plugs.condition < 30f) m *= 0.7f;
|
||||
|
||||
EnginePart air = GetPart(EnginePartType.AirFilter);
|
||||
if (air == null || air.condition < 30f) m *= 0.8f;
|
||||
|
||||
CarFluids f = Fluids;
|
||||
if (f != null && (f.EngineOil.FillPercent < 0.15f || f.EngineOil.quality < 0.2f)) m *= 0.5f;
|
||||
|
||||
if (IsOverheating) m *= 0.65f;
|
||||
return Mathf.Clamp(m, 0.4f, 1f);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Коэффициент тормозного усилия 0.35–1.0 по уровню тормозной жидкости.</summary>
|
||||
public float BrakeMultiplier
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!Diploma) return 1f;
|
||||
CarFluids f = Fluids;
|
||||
if (f == null) return 1f;
|
||||
float level = f.BrakeFluid.FillPercent;
|
||||
return level < 0.3f ? 0.4f : 1f;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsMisfiring
|
||||
{
|
||||
get
|
||||
{
|
||||
EnginePart plugs = GetPart(EnginePartType.SparkPlugs);
|
||||
return Diploma && plugs != null && plugs.condition < 30f;
|
||||
}
|
||||
}
|
||||
|
||||
public bool OilKnocking => Diploma && Fluids != null && (Fluids.EngineOil.FillPercent < 0.15f || Fluids.EngineOil.quality < 0.2f);
|
||||
|
||||
public float MaxSpeedLimit => IsOverheating ? 45f : float.MaxValue;
|
||||
|
||||
public bool BatteryWarning
|
||||
{
|
||||
get
|
||||
{
|
||||
EnginePart b = GetPart(EnginePartType.Battery);
|
||||
EnginePart a = GetPart(EnginePartType.Alternator);
|
||||
return b == null || b.charge < 20f || a == null || a.condition < 30f;
|
||||
}
|
||||
}
|
||||
|
||||
public bool OilWarning => Fluids != null && (Fluids.EngineOil.FillPercent < 0.25f || Fluids.EngineOil.quality < 0.2f);
|
||||
public bool TempWarning => IsOverheating || (Fluids != null && Fluids.Coolant.FillPercent < 0.25f);
|
||||
public bool BrakeWarning => Fluids != null && Fluids.BrakeFluid.FillPercent < 0.3f;
|
||||
|
||||
/// <summary>Коды ошибок для OBD-сканера.</summary>
|
||||
public List<string> GetObdCodes()
|
||||
{
|
||||
List<string> codes = new List<string>();
|
||||
EnginePart plugs = GetPart(EnginePartType.SparkPlugs);
|
||||
EnginePart battery = GetPart(EnginePartType.Battery);
|
||||
EnginePart alt = GetPart(EnginePartType.Alternator);
|
||||
EnginePart air = GetPart(EnginePartType.AirFilter);
|
||||
EnginePart rad = GetPart(EnginePartType.Radiator);
|
||||
CarFluids f = Fluids;
|
||||
|
||||
if (plugs == null) codes.Add("P0300 — Пропуски зажигания (свечи отсутствуют)");
|
||||
else if (plugs.condition < 30f) codes.Add($"P0300 — Пропуски зажигания в цилиндрах (свечи {Mathf.RoundToInt(plugs.condition)}%)");
|
||||
|
||||
if (f != null && (f.EngineOil.FillPercent < 0.25f || f.EngineOil.quality < 0.2f))
|
||||
codes.Add($"P0520 — Низкое давление масла (уровень {Mathf.RoundToInt(f.EngineOil.FillPercent * 100f)}%, состояние {Mathf.RoundToInt(f.EngineOil.quality * 100f)}%)");
|
||||
|
||||
if (IsOverheating || (f != null && f.Coolant.FillPercent < 0.25f))
|
||||
codes.Add($"P0217 — Перегрев охлаждающей жидкости (уровень ОЖ {Mathf.RoundToInt((f != null ? f.Coolant.FillPercent : 0f) * 100f)}%)");
|
||||
if (rad == null || rad.condition < 30f)
|
||||
codes.Add("P0128 — Неисправность системы охлаждения (радиатор течет)");
|
||||
|
||||
if (battery == null) codes.Add("P0562 — Низкое напряжение бортсети (АКБ отсутствует)");
|
||||
else if (battery.charge < 30f) codes.Add($"P0562 — Низкое напряжение бортсети (заряд АКБ {Mathf.RoundToInt(battery.charge)}%)");
|
||||
|
||||
if (alt == null || alt.condition < 30f) codes.Add("P0620 — Неисправность цепи генератора (нет зарядки)");
|
||||
if (air == null || air.condition < 30f) codes.Add("P0101 — Расходомер воздуха: забит воздушный фильтр");
|
||||
|
||||
if (f != null && f.BrakeFluid.FillPercent < 0.3f)
|
||||
codes.Add($"C1241 — Низкий уровень тормозной жидкости ({Mathf.RoundToInt(f.BrakeFluid.FillPercent * 100f)}%)");
|
||||
|
||||
return codes;
|
||||
}
|
||||
|
||||
/// <summary>Подкапотное пространство готово к продаже: агрегаты > 80%, жидкости > 85%.</summary>
|
||||
public bool IsReadyForSale(List<string> issues)
|
||||
{
|
||||
bool ok = true;
|
||||
foreach (EnginePartType t in new[] { EnginePartType.Battery, EnginePartType.SparkPlugs, EnginePartType.AirFilter, EnginePartType.OilFilter, EnginePartType.Radiator, EnginePartType.Alternator })
|
||||
{
|
||||
EnginePart p = GetPart(t);
|
||||
bool hadOne = HasSlotFor(t);
|
||||
if (!hadOne) continue;
|
||||
if (p == null)
|
||||
{
|
||||
ok = false;
|
||||
issues?.Add($"Не установлен: {EnginePart.GetDisplayName(t)}");
|
||||
}
|
||||
else if (!p.IsHealthy)
|
||||
{
|
||||
ok = false;
|
||||
issues?.Add($"{p.DisplayName}: {p.ShortStatus}");
|
||||
}
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
public bool AreFluidsFresh(List<string> issues)
|
||||
{
|
||||
CarFluids f = Fluids;
|
||||
if (f == null) return true;
|
||||
bool ok = true;
|
||||
foreach (CarFluids.FluidReservoir r in f.All)
|
||||
{
|
||||
bool good = r.fluidType == FluidType.WasherFluid ? r.FillPercent >= 0.85f : r.IsGood;
|
||||
if (!good)
|
||||
{
|
||||
ok = false;
|
||||
issues?.Add($"{r.title}: {Mathf.RoundToInt(r.FillPercent * 100f)}% / состояние {Mathf.RoundToInt(r.quality * 100f)}%");
|
||||
}
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
private bool HasSlotFor(EnginePartType t)
|
||||
{
|
||||
foreach (EnginePart ep in GetComponentsInChildren<EnginePart>(true))
|
||||
if (ep.partType == t) return true;
|
||||
foreach (CarPartMountZone z in GetComponentsInChildren<CarPartMountZone>(true))
|
||||
{
|
||||
CarPartData d = z.TargetData;
|
||||
if (d != null && d == PartCatalog.Instance.GetEngineData(t)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ===================== СИМУЛЯЦИЯ =====================
|
||||
|
||||
public void SetRunning(bool running) => EngineRunning = running;
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (!Diploma)
|
||||
{
|
||||
overheatTimer = 0f;
|
||||
UpdateSteam(false);
|
||||
return;
|
||||
}
|
||||
|
||||
float dt = Time.deltaTime;
|
||||
CarFluids f = Fluids;
|
||||
|
||||
if (EngineRunning)
|
||||
{
|
||||
EnginePart battery = GetPart(EnginePartType.Battery);
|
||||
EnginePart alt = GetPart(EnginePartType.Alternator);
|
||||
if (battery != null)
|
||||
{
|
||||
if (alt != null && alt.condition >= 30f)
|
||||
battery.charge = Mathf.Min(100f, battery.charge + 0.25f * dt);
|
||||
else
|
||||
battery.charge = Mathf.Max(0f, battery.charge - 0.35f * dt);
|
||||
|
||||
if (battery.charge <= 0.5f)
|
||||
{
|
||||
EngineRunning = false;
|
||||
GameHUD.Notify("Двигатель заглох: аккумулятор полностью разряжен (неисправен генератор)", GameUI.Red);
|
||||
}
|
||||
}
|
||||
|
||||
EnginePart rad = GetPart(EnginePartType.Radiator);
|
||||
if (f != null)
|
||||
{
|
||||
if (rad == null || rad.condition < 30f)
|
||||
f.Leak(FluidType.Coolant, 0.015f * dt);
|
||||
|
||||
bool coolingBad = f.Coolant.FillPercent < 0.25f || rad == null;
|
||||
overheatTimer = coolingBad ? overheatTimer + dt : Mathf.Max(0f, overheatTimer - dt * 3f);
|
||||
|
||||
f.EngineOil.quality = Mathf.Max(0f, f.EngineOil.quality - 0.0003f * dt);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
overheatTimer = Mathf.Max(0f, overheatTimer - dt * 2f);
|
||||
}
|
||||
|
||||
if (IsOverheating) steamTimer = 8f;
|
||||
else if (steamTimer > 0f) steamTimer -= dt;
|
||||
UpdateSteam(steamTimer > 0f);
|
||||
}
|
||||
|
||||
private void UpdateSteam(bool on)
|
||||
{
|
||||
if (steam == null) return;
|
||||
if (on && !steam.isPlaying) steam.Play();
|
||||
else if (!on && steam.isPlaying) steam.Stop();
|
||||
if (on || ProceduralAudioManager.Existing != null)
|
||||
ProceduralAudioManager.Instance?.SetLoop(this, LoopId.Steam, on, steam.transform.position, 0.5f);
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
if (ProceduralAudioManager.Existing != null)
|
||||
ProceduralAudioManager.Existing.SetLoop(this, LoopId.Steam, false, Vector3.zero);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c2e4d640de4a56448b3cca1b20f30a43
|
||||
@@ -0,0 +1,98 @@
|
||||
using UnityEngine;
|
||||
|
||||
public enum EnginePartType { Battery, SparkPlugs, AirFilter, OilFilter, Radiator, Alternator, FuelFilter }
|
||||
|
||||
/// <summary>
|
||||
/// Съемный агрегат подкапотного пространства (работает совместно с CarPart):
|
||||
/// хранит состояние 0–100% и, для аккумулятора, заряд 0–100%.
|
||||
/// </summary>
|
||||
[RequireComponent(typeof(CarPart))]
|
||||
[DisallowMultipleComponent]
|
||||
public class EnginePart : MonoBehaviour
|
||||
{
|
||||
public EnginePartType partType = EnginePartType.Battery;
|
||||
[Range(0f, 100f)] public float condition = 100f;
|
||||
[Tooltip("Только для аккумулятора")]
|
||||
[Range(0f, 100f)] public float charge = 100f;
|
||||
|
||||
private CarPart carPart;
|
||||
|
||||
public CarPart Part
|
||||
{
|
||||
get
|
||||
{
|
||||
if (carPart == null) carPart = GetComponent<CarPart>();
|
||||
return carPart;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsInstalled => Part != null && Part.State == PartState.Installed && gameObject.activeInHierarchy;
|
||||
|
||||
/// <summary>Свечи, генератор и радиатор откручиваются гаечным ключом, остальное — руками.</summary>
|
||||
public bool RequiresWrench => partType == EnginePartType.SparkPlugs || partType == EnginePartType.Alternator || partType == EnginePartType.Radiator;
|
||||
|
||||
public bool IsHealthy => condition >= 80f && (partType != EnginePartType.Battery || charge >= 60f);
|
||||
|
||||
public string DisplayName => GetDisplayName(partType);
|
||||
|
||||
public static string GetDisplayName(EnginePartType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case EnginePartType.Battery: return "Аккумулятор 12V";
|
||||
case EnginePartType.SparkPlugs: return "Свечи зажигания / Катушки";
|
||||
case EnginePartType.AirFilter: return "Воздушный фильтр";
|
||||
case EnginePartType.OilFilter: return "Масляный фильтр";
|
||||
case EnginePartType.Radiator: return "Радиатор охлаждения";
|
||||
case EnginePartType.Alternator: return "Генератор";
|
||||
case EnginePartType.FuelFilter: return "Топливный фильтр";
|
||||
default: return "Агрегат";
|
||||
}
|
||||
}
|
||||
|
||||
public static float GetDefaultPrice(EnginePartType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case EnginePartType.Battery: return 95f;
|
||||
case EnginePartType.SparkPlugs: return 35f;
|
||||
case EnginePartType.AirFilter: return 18f;
|
||||
case EnginePartType.OilFilter: return 12f;
|
||||
case EnginePartType.Radiator: return 140f;
|
||||
case EnginePartType.Alternator: return 160f;
|
||||
case EnginePartType.FuelFilter: return 15f;
|
||||
default: return 30f;
|
||||
}
|
||||
}
|
||||
|
||||
public float BasePrice => Part != null && Part.Data != null && Part.Data.basePrice > 0f ? Part.Data.basePrice : GetDefaultPrice(partType);
|
||||
|
||||
public string StatusText
|
||||
{
|
||||
get
|
||||
{
|
||||
string cond = $"Состояние: <color={ColorFor(condition)}>{Mathf.RoundToInt(condition)}%</color>";
|
||||
if (partType == EnginePartType.Battery)
|
||||
cond += $" | Заряд: <color={ColorFor(charge)}>{Mathf.RoundToInt(charge)}%</color>";
|
||||
return $"{DisplayName} | {cond}";
|
||||
}
|
||||
}
|
||||
|
||||
public string ShortStatus
|
||||
{
|
||||
get
|
||||
{
|
||||
string s = $"{Mathf.RoundToInt(condition)}%";
|
||||
if (partType == EnginePartType.Battery) s += $" / заряд {Mathf.RoundToInt(charge)}%";
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
private static string ColorFor(float v) => v >= 80f ? "#4CD07D" : (v >= 30f ? "#F2A93B" : "#E5534B");
|
||||
|
||||
public void SetAsNew()
|
||||
{
|
||||
condition = 100f;
|
||||
charge = 100f;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 12919e8cda18b5c4eb0e026ca1bf6c1b
|
||||
@@ -0,0 +1,267 @@
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Процедурная генерация 3D-узлов моторного отсека (используется EngineBayManager для машин без
|
||||
/// отдельных подкапотных мешей и магазином запчастей для новых агрегатов).
|
||||
/// </summary>
|
||||
public static class EnginePartFactory
|
||||
{
|
||||
public static int InteractLayer
|
||||
{
|
||||
get
|
||||
{
|
||||
int l = LayerMask.NameToLayer("Interactble");
|
||||
if (l < 0) l = LayerMask.NameToLayer("Interactable");
|
||||
return l < 0 ? 0 : l;
|
||||
}
|
||||
}
|
||||
|
||||
private static Material M(string key, Color c) => PartCatalog.Instance.GetMaterial(key, c);
|
||||
|
||||
public static Material Black => M("eb_black", new Color(0.07f, 0.07f, 0.08f));
|
||||
public static Material DarkGrey => M("eb_darkgrey", new Color(0.18f, 0.19f, 0.21f));
|
||||
public static Material Metal => M("eb_metal", new Color(0.62f, 0.63f, 0.66f));
|
||||
public static Material Red => M("eb_red", new Color(0.8f, 0.12f, 0.1f));
|
||||
public static Material Yellow => M("eb_yellow", new Color(0.95f, 0.75f, 0.1f));
|
||||
public static Material Blue => M("eb_blue", new Color(0.12f, 0.35f, 0.85f));
|
||||
public static Material Orange => M("eb_orange", new Color(0.92f, 0.45f, 0.08f));
|
||||
public static Material Pink => M("eb_pink", new Color(0.95f, 0.3f, 0.55f));
|
||||
public static Material TankWhite => M("eb_tank", new Color(0.88f, 0.86f, 0.8f));
|
||||
public static Material Copper => M("eb_copper", new Color(0.72f, 0.42f, 0.2f));
|
||||
|
||||
public static string GetObjectName(EnginePartType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case EnginePartType.Battery: return "Battery_12V";
|
||||
case EnginePartType.SparkPlugs: return "SparkPlugs";
|
||||
case EnginePartType.AirFilter: return "AirFilter";
|
||||
case EnginePartType.OilFilter: return "OilFilter";
|
||||
case EnginePartType.Radiator: return "Radiator";
|
||||
case EnginePartType.Alternator: return "Alternator";
|
||||
case EnginePartType.FuelFilter: return "FuelFilter";
|
||||
default: return "EnginePart";
|
||||
}
|
||||
}
|
||||
|
||||
public static float GetMass(EnginePartType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case EnginePartType.Battery: return 14f;
|
||||
case EnginePartType.Radiator: return 6f;
|
||||
case EnginePartType.Alternator: return 5f;
|
||||
case EnginePartType.SparkPlugs: return 1.5f;
|
||||
default: return 1f;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Создает съемный агрегат. asLoose = true — новая деталь из магазина, лежащая отдельно от машины.</summary>
|
||||
public static EnginePart CreatePart(EnginePartType type, Transform parent, Vector3 localPos, Quaternion localRot, float widthHint = 0.6f, bool asLoose = false)
|
||||
{
|
||||
GameObject root = new GameObject(GetObjectName(type));
|
||||
root.layer = InteractLayer;
|
||||
if (parent != null) root.transform.SetParent(parent, false);
|
||||
root.transform.localPosition = localPos;
|
||||
root.transform.localRotation = localRot;
|
||||
|
||||
BuildVisual(type, root.transform, widthHint);
|
||||
SetLayerRecursive(root, InteractLayer);
|
||||
|
||||
BoxCollider box = root.AddComponent<BoxCollider>();
|
||||
Bounds b = LocalBounds(root.transform);
|
||||
box.center = b.center;
|
||||
box.size = b.size + Vector3.one * 0.02f;
|
||||
box.isTrigger = !asLoose;
|
||||
|
||||
CarPart cp = root.AddComponent<CarPart>();
|
||||
CarPartData data = PartCatalog.Instance.GetEngineData(type);
|
||||
cp.SetData(data, GetMass(type));
|
||||
|
||||
EnginePart ep = root.AddComponent<EnginePart>();
|
||||
ep.partType = type;
|
||||
ep.SetAsNew();
|
||||
return ep;
|
||||
}
|
||||
|
||||
private static void BuildVisual(EnginePartType type, Transform root, float width)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case EnginePartType.Battery:
|
||||
Prim(PrimitiveType.Cube, root, "Case", new Vector3(0f, 0f, 0f), new Vector3(0.24f, 0.18f, 0.17f), Black);
|
||||
Prim(PrimitiveType.Cube, root, "Lid", new Vector3(0f, 0.095f, 0f), new Vector3(0.245f, 0.02f, 0.175f), DarkGrey);
|
||||
Prim(PrimitiveType.Cube, root, "Label", new Vector3(0f, 0.01f, 0.086f), new Vector3(0.2f, 0.07f, 0.004f), Yellow);
|
||||
Prim(PrimitiveType.Cylinder, root, "Terminal_Plus", new Vector3(0.08f, 0.115f, 0.05f), new Vector3(0.028f, 0.015f, 0.028f), Red);
|
||||
Prim(PrimitiveType.Cylinder, root, "Terminal_Minus", new Vector3(-0.08f, 0.115f, 0.05f), new Vector3(0.028f, 0.015f, 0.028f), Black);
|
||||
break;
|
||||
|
||||
case EnginePartType.SparkPlugs:
|
||||
Prim(PrimitiveType.Cube, root, "CoilRail", Vector3.zero, new Vector3(0.42f, 0.04f, 0.07f), DarkGrey);
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
float x = -0.15f + i * 0.1f;
|
||||
Prim(PrimitiveType.Cylinder, root, $"Coil_{i + 1}", new Vector3(x, 0.045f, 0f), new Vector3(0.04f, 0.035f, 0.04f), Black);
|
||||
Prim(PrimitiveType.Cylinder, root, $"Boot_{i + 1}", new Vector3(x, 0.09f, 0f), new Vector3(0.022f, 0.012f, 0.022f), Red);
|
||||
}
|
||||
break;
|
||||
|
||||
case EnginePartType.AirFilter:
|
||||
Prim(PrimitiveType.Cylinder, root, "Housing", Vector3.zero, new Vector3(0.3f, 0.05f, 0.3f), Black);
|
||||
Prim(PrimitiveType.Cylinder, root, "Lid", new Vector3(0f, 0.055f, 0f), new Vector3(0.24f, 0.01f, 0.24f), DarkGrey);
|
||||
Prim(PrimitiveType.Cylinder, root, "WingNut", new Vector3(0f, 0.07f, 0f), new Vector3(0.05f, 0.012f, 0.05f), Metal);
|
||||
Prim(PrimitiveType.Cube, root, "Snout", new Vector3(0f, 0f, -0.19f), new Vector3(0.09f, 0.06f, 0.14f), Black);
|
||||
break;
|
||||
|
||||
case EnginePartType.OilFilter:
|
||||
Prim(PrimitiveType.Cylinder, root, "Canister", Vector3.zero, new Vector3(0.09f, 0.06f, 0.09f), Orange);
|
||||
Prim(PrimitiveType.Cylinder, root, "Base", new Vector3(0f, -0.065f, 0f), new Vector3(0.095f, 0.006f, 0.095f), Metal);
|
||||
break;
|
||||
|
||||
case EnginePartType.Radiator:
|
||||
{
|
||||
float w = Mathf.Clamp(width * 0.75f, 0.45f, 0.8f);
|
||||
Prim(PrimitiveType.Cube, root, "Core", Vector3.zero, new Vector3(w, 0.38f, 0.035f), DarkGrey);
|
||||
for (int i = 0; i < 9; i++)
|
||||
Prim(PrimitiveType.Cube, root, $"Fin_{i}", new Vector3(0f, -0.16f + i * 0.04f, 0.019f), new Vector3(w * 0.96f, 0.006f, 0.004f), Metal);
|
||||
Prim(PrimitiveType.Cube, root, "TopTank", new Vector3(0f, 0.21f, 0f), new Vector3(w + 0.02f, 0.04f, 0.06f), Black);
|
||||
Prim(PrimitiveType.Cube, root, "BottomTank", new Vector3(0f, -0.21f, 0f), new Vector3(w + 0.02f, 0.04f, 0.06f), Black);
|
||||
break;
|
||||
}
|
||||
|
||||
case EnginePartType.Alternator:
|
||||
Prim(PrimitiveType.Cylinder, root, "Body", Vector3.zero, new Vector3(0.13f, 0.055f, 0.13f), Metal, new Vector3(0f, 0f, 90f));
|
||||
Prim(PrimitiveType.Cylinder, root, "Pulley", new Vector3(0.065f, 0f, 0f), new Vector3(0.07f, 0.008f, 0.07f), Black, new Vector3(0f, 0f, 90f));
|
||||
Prim(PrimitiveType.Cube, root, "Bracket", new Vector3(-0.02f, -0.07f, 0f), new Vector3(0.08f, 0.03f, 0.05f), DarkGrey);
|
||||
break;
|
||||
|
||||
case EnginePartType.FuelFilter:
|
||||
Prim(PrimitiveType.Cylinder, root, "Body", Vector3.zero, new Vector3(0.06f, 0.05f, 0.06f), TankWhite);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Пластиковый бачок с крышкой. Крышка получает имя, по которому её находит CarFluids.</summary>
|
||||
public static Transform CreateReservoir(FluidType type, Transform parent, Vector3 localPos)
|
||||
{
|
||||
GameObject root = new GameObject($"Reservoir_{type}");
|
||||
root.layer = InteractLayer;
|
||||
root.transform.SetParent(parent, false);
|
||||
root.transform.localPosition = localPos;
|
||||
|
||||
Material capMat;
|
||||
Material fillMat;
|
||||
Vector3 tankSize;
|
||||
string capName;
|
||||
switch (type)
|
||||
{
|
||||
case FluidType.Coolant:
|
||||
tankSize = new Vector3(0.14f, 0.13f, 0.10f); capMat = Black; fillMat = Pink; capName = "Gen_CoolantCap"; break;
|
||||
case FluidType.BrakeFluid:
|
||||
tankSize = new Vector3(0.09f, 0.08f, 0.06f); capMat = Yellow; fillMat = TankWhite; capName = "Gen_BrakeFluidCap"; break;
|
||||
case FluidType.WasherFluid:
|
||||
tankSize = new Vector3(0.16f, 0.17f, 0.12f); capMat = Blue; fillMat = Blue; capName = "Gen_WasherFluidCap"; break;
|
||||
default:
|
||||
tankSize = Vector3.zero; capMat = Yellow; fillMat = Black; capName = "Gen_OilCap"; break;
|
||||
}
|
||||
|
||||
float capY = 0.012f;
|
||||
if (tankSize != Vector3.zero)
|
||||
{
|
||||
Prim(PrimitiveType.Cube, root.transform, "Tank", Vector3.zero, tankSize, TankWhite);
|
||||
Prim(PrimitiveType.Cube, root.transform, "FluidLevel", new Vector3(0f, -tankSize.y * 0.2f, tankSize.z * 0.51f), new Vector3(tankSize.x * 0.8f, tankSize.y * 0.45f, 0.004f), fillMat);
|
||||
capY = tankSize.y * 0.5f + 0.012f;
|
||||
}
|
||||
else
|
||||
{
|
||||
Prim(PrimitiveType.Cylinder, root.transform, "FillerNeck", new Vector3(0f, -0.02f, 0f), new Vector3(0.045f, 0.02f, 0.045f), DarkGrey);
|
||||
}
|
||||
|
||||
GameObject cap = Prim(PrimitiveType.Cylinder, root.transform, capName, new Vector3(0f, capY, 0f), new Vector3(0.055f, 0.012f, 0.055f), capMat);
|
||||
BoxCollider bc = cap.AddComponent<BoxCollider>();
|
||||
bc.isTrigger = true;
|
||||
bc.size = new Vector3(2.4f, 3.5f, 2.4f); // относительно масштаба крышки — удобная зона наведения
|
||||
SetLayerRecursive(root, InteractLayer);
|
||||
return cap.transform;
|
||||
}
|
||||
|
||||
public static OilDipstick CreateDipstick(Transform parent, Vector3 localPos)
|
||||
{
|
||||
GameObject root = new GameObject("OilDipstick");
|
||||
root.transform.SetParent(parent, false);
|
||||
root.transform.localPosition = localPos;
|
||||
Prim(PrimitiveType.Cylinder, root.transform, "Ring", new Vector3(0f, 0.03f, 0f), new Vector3(0.045f, 0.005f, 0.045f), Yellow);
|
||||
Prim(PrimitiveType.Cylinder, root.transform, "Rod", new Vector3(0f, -0.04f, 0f), new Vector3(0.008f, 0.07f, 0.008f), Metal);
|
||||
SphereCollider sc = root.AddComponent<SphereCollider>();
|
||||
sc.isTrigger = true;
|
||||
sc.radius = 0.05f;
|
||||
sc.center = new Vector3(0f, 0.03f, 0f);
|
||||
SetLayerRecursive(root, InteractLayer);
|
||||
return root.AddComponent<OilDipstick>();
|
||||
}
|
||||
|
||||
public static OilDrainPlug CreateOilPan(Transform parent, Vector3 localPos, float width)
|
||||
{
|
||||
GameObject pan = new GameObject("OilPan");
|
||||
pan.transform.SetParent(parent, false);
|
||||
pan.transform.localPosition = localPos;
|
||||
Prim(PrimitiveType.Cube, pan.transform, "Sump", Vector3.zero, new Vector3(Mathf.Clamp(width * 0.45f, 0.3f, 0.5f), 0.08f, 0.32f), DarkGrey);
|
||||
|
||||
GameObject plug = Prim(PrimitiveType.Cylinder, pan.transform, "OilDrainPlug", new Vector3(0f, -0.045f, -0.08f), new Vector3(0.04f, 0.008f, 0.04f), Metal);
|
||||
SphereCollider sc = plug.AddComponent<SphereCollider>();
|
||||
sc.isTrigger = true;
|
||||
sc.radius = 3.2f; // ~13 см с учетом масштаба пробки
|
||||
SetLayerRecursive(pan, InteractLayer);
|
||||
return plug.AddComponent<OilDrainPlug>();
|
||||
}
|
||||
|
||||
public static GameObject Prim(PrimitiveType type, Transform parent, string name, Vector3 localPos, Vector3 localScale, Material mat, Vector3? euler = null)
|
||||
{
|
||||
GameObject go = GameObject.CreatePrimitive(type);
|
||||
go.name = name;
|
||||
Collider c = go.GetComponent<Collider>();
|
||||
if (c != null)
|
||||
{
|
||||
if (Application.isPlaying) Object.Destroy(c);
|
||||
else Object.DestroyImmediate(c);
|
||||
}
|
||||
go.transform.SetParent(parent, false);
|
||||
go.transform.localPosition = localPos;
|
||||
go.transform.localRotation = Quaternion.Euler(euler ?? Vector3.zero);
|
||||
go.transform.localScale = localScale;
|
||||
Renderer r = go.GetComponent<Renderer>();
|
||||
if (r != null && mat != null) r.sharedMaterial = mat;
|
||||
return go;
|
||||
}
|
||||
|
||||
public static void SetLayerRecursive(GameObject go, int layer)
|
||||
{
|
||||
foreach (Transform t in go.GetComponentsInChildren<Transform>(true))
|
||||
t.gameObject.layer = layer;
|
||||
}
|
||||
|
||||
/// <summary>Габариты всех мешей объекта в его локальных координатах.</summary>
|
||||
public static Bounds LocalBounds(Transform root)
|
||||
{
|
||||
bool has = false;
|
||||
Bounds result = new Bounds(Vector3.zero, Vector3.zero);
|
||||
foreach (MeshFilter mf in root.GetComponentsInChildren<MeshFilter>(true))
|
||||
{
|
||||
if (mf.sharedMesh == null) continue;
|
||||
Bounds mb = mf.sharedMesh.bounds;
|
||||
Vector3 e = mb.extents;
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
Vector3 corner = mb.center + new Vector3(i % 2 == 0 ? -e.x : e.x, (i / 2) % 2 == 0 ? -e.y : e.y, i / 4 == 0 ? -e.z : e.z);
|
||||
Vector3 p = root.InverseTransformPoint(mf.transform.TransformPoint(corner));
|
||||
if (!has)
|
||||
{
|
||||
result = new Bounds(p, Vector3.zero);
|
||||
has = true;
|
||||
}
|
||||
else result.Encapsulate(p);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1d0a91fa461f63f4895460d7adb1bd69
|
||||
@@ -0,0 +1,43 @@
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>Масляный щуп: при наведении показывает уровень и состояние моторного масла.</summary>
|
||||
public class OilDipstick : MonoBehaviour, IInteractable
|
||||
{
|
||||
private CarFluids fluids;
|
||||
private Vector3 restLocalPos;
|
||||
private float pulledTimer;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
fluids = GetComponentInParent<CarFluids>();
|
||||
restLocalPos = transform.localPosition;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (pulledTimer > 0f) pulledTimer -= Time.deltaTime;
|
||||
Vector3 target = restLocalPos + (pulledTimer > 0f ? Vector3.up * 0.14f : Vector3.zero);
|
||||
transform.localPosition = Vector3.Lerp(transform.localPosition, target, Time.deltaTime * 8f);
|
||||
}
|
||||
|
||||
public string GetPrompt()
|
||||
{
|
||||
if (fluids == null) fluids = GetComponentInParent<CarFluids>();
|
||||
if (fluids == null) return "Масляный щуп";
|
||||
|
||||
CarFluids.FluidReservoir oil = fluids.EngineOil;
|
||||
int level = Mathf.RoundToInt(oil.FillPercent * 100f);
|
||||
int quality = Mathf.RoundToInt(oil.quality * 100f);
|
||||
string qText = oil.currentLiters < 0.05f ? "масла нет!" : oil.QualityText;
|
||||
string color = (oil.FillPercent < 0.5f || oil.quality < 0.5f) ? "#E5534B" : "#4CD07D";
|
||||
return $"Масляный щуп [E] — вытащить\n<color={color}>Уровень: {level}% | Состояние: {quality}% ({qText})</color>";
|
||||
}
|
||||
|
||||
public void Interact(GameObject interactor)
|
||||
{
|
||||
pulledTimer = 2.5f;
|
||||
CarOwnership own = CarOwnership.Get(gameObject);
|
||||
if (own != null) own.hoodInspected = true;
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.Pickup, transform.position, 0.6f);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9a0bfdd388cbd6344a8b91ce969fc760
|
||||
@@ -0,0 +1,120 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Сливная пробка масляного поддона. Доступна, когда передняя часть авто поднята домкратом:
|
||||
/// старое масло сливается в таз, после чего свежее заливается сверху из канистры.
|
||||
/// </summary>
|
||||
public class OilDrainPlug : MonoBehaviour, IInteractable
|
||||
{
|
||||
private CarFluids fluids;
|
||||
private bool draining;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
fluids = GetComponentInParent<CarFluids>();
|
||||
}
|
||||
|
||||
private bool IsFrontLifted()
|
||||
{
|
||||
VehicleInteraction car = GetComponentInParent<VehicleInteraction>();
|
||||
if (car == null) return true;
|
||||
|
||||
foreach (CarPart part in car.GetComponentsInChildren<CarPart>(true))
|
||||
{
|
||||
if (part.TotalBoltsCount == 0 && part.LinkedWheelCollider == null) continue;
|
||||
Vector3 local = car.transform.InverseTransformPoint(part.transform.position);
|
||||
if (local.z > 0f && CarJack.IsWheelLifted(part.transform)) return true;
|
||||
}
|
||||
|
||||
foreach (WheelCollider wc in car.GetComponentsInChildren<WheelCollider>(true))
|
||||
{
|
||||
Vector3 local = car.transform.InverseTransformPoint(wc.transform.position);
|
||||
if (local.z > 0f && CarJack.IsWheelLifted(wc.transform)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public string GetPrompt()
|
||||
{
|
||||
if (fluids == null) fluids = GetComponentInParent<CarFluids>();
|
||||
if (fluids == null) return "Сливная пробка картера";
|
||||
if (draining) return "Сливаем старое масло в таз...";
|
||||
|
||||
float liters = fluids.EngineOil.currentLiters;
|
||||
if (liters < 0.05f)
|
||||
return "Масло слито. Закрутите пробку и залейте свежее масло сверху через горловину";
|
||||
|
||||
if (!IsFrontLifted())
|
||||
return "Сливная пробка картера\n<color=#F2A93B>Поднимите переднюю часть авто домкратом, чтобы добраться до пробки</color>";
|
||||
|
||||
return $"[E] Открутить сливную пробку и слить масло ({liters:F1} л, состояние {Mathf.RoundToInt(fluids.EngineOil.quality * 100f)}%)";
|
||||
}
|
||||
|
||||
public void Interact(GameObject interactor)
|
||||
{
|
||||
if (draining || fluids == null || fluids.EngineOil.currentLiters < 0.05f || !IsFrontLifted()) return;
|
||||
StartCoroutine(DrainRoutine());
|
||||
}
|
||||
|
||||
private IEnumerator DrainRoutine()
|
||||
{
|
||||
draining = true;
|
||||
|
||||
// Таз под пробкой
|
||||
Vector3 ground = transform.position + Vector3.down * 0.6f;
|
||||
if (Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, 2f, ~0, QueryTriggerInteraction.Ignore))
|
||||
ground = hit.point;
|
||||
|
||||
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();
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.OilDrain, transform.position, 0.8f);
|
||||
|
||||
float total = fluids.EngineOil.currentLiters;
|
||||
float t = 0f;
|
||||
const float duration = 3f;
|
||||
while (t < duration)
|
||||
{
|
||||
t += Time.deltaTime;
|
||||
fluids.EngineOil.currentLiters = Mathf.Lerp(total, 0f, t / duration);
|
||||
oilSurface.transform.localPosition = new Vector3(0f, Mathf.Lerp(-0.3f, 0.6f, t / duration), 0f);
|
||||
yield return null;
|
||||
}
|
||||
|
||||
fluids.DrainEngineOil();
|
||||
if (stream != null) Destroy(stream.gameObject, 1f);
|
||||
Destroy(basin, 25f);
|
||||
draining = false;
|
||||
GameHUD.Notify("Старое масло слито. Залейте свежее моторное масло из желтой канистры", GameUI.Accent);
|
||||
}
|
||||
|
||||
private ParticleSystem CreateStream()
|
||||
{
|
||||
GameObject pObj = new GameObject("OilStream");
|
||||
pObj.transform.position = transform.position;
|
||||
pObj.transform.rotation = Quaternion.LookRotation(Vector3.down);
|
||||
ParticleSystem ps = pObj.AddComponent<ParticleSystem>();
|
||||
var main = ps.main;
|
||||
main.startLifetime = 0.35f;
|
||||
main.startSpeed = 1.6f;
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 357031328f39b3743b7231a2ee58dae4
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6f2b1b4674e74a4ebfa713844c5ed0dd
|
||||
timeCreated: 1789942925
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 37ba02caa32943f69ac40c67217aec57
|
||||
timeCreated: 1789943104
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Открытие дверей, капота и багажника.
|
||||
/// Режим 1 (как раньше): вращение вокруг собственного пивота детали на openRotation.
|
||||
/// Режим 2 (useHinge): вращение вокруг петли hingePoint/hingeAxis в координатах родителя —
|
||||
/// используется автонастройкой для моделей, у которых пивот детали стоит в центре машины.
|
||||
/// </summary>
|
||||
[RequireComponent(typeof(CarPart))]
|
||||
public class CarPartAnimator : MonoBehaviour
|
||||
{
|
||||
[Header("Настройки открытия")]
|
||||
[SerializeField] private Vector3 openRotation; // Например: (0, 0, 60) для капота
|
||||
[SerializeField] private float speed = 5f;
|
||||
|
||||
[Header("Петля (автонастройка)")]
|
||||
[SerializeField] private bool useHinge;
|
||||
[SerializeField] private Vector3 hingePoint;
|
||||
[SerializeField] private Vector3 hingeAxis = Vector3.right;
|
||||
[SerializeField] private float openAngle = -55f;
|
||||
|
||||
public bool IsOpen => isOpen;
|
||||
private Quaternion closedRot;
|
||||
private Quaternion openRot;
|
||||
private Vector3 closedPos;
|
||||
private bool isOpen = false;
|
||||
private float openAmount;
|
||||
private Coroutine animationCoroutine;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
closedRot = transform.localRotation;
|
||||
closedPos = transform.localPosition;
|
||||
// Конвертируем введенные углы Эйлера в Кватернион
|
||||
openRot = closedRot * Quaternion.Euler(openRotation);
|
||||
}
|
||||
|
||||
/// <summary>Настройка петли из Editor-автонастройки (координаты родителя детали).</summary>
|
||||
public void ConfigureHinge(Vector3 pointInParent, Vector3 axisInParent, float angle, float animSpeed = 4f)
|
||||
{
|
||||
useHinge = true;
|
||||
hingePoint = pointInParent;
|
||||
hingeAxis = axisInParent.sqrMagnitude > 0.0001f ? axisInParent.normalized : Vector3.right;
|
||||
openAngle = angle;
|
||||
speed = animSpeed;
|
||||
}
|
||||
|
||||
public void TogglePart()
|
||||
{
|
||||
isOpen = !isOpen;
|
||||
|
||||
// Если деталь уже двигалась, останавливаем старую корутину, чтобы не было конфликтов
|
||||
if (animationCoroutine != null)
|
||||
StopCoroutine(animationCoroutine);
|
||||
|
||||
animationCoroutine = useHinge
|
||||
? StartCoroutine(AnimateHinge(isOpen ? 1f : 0f))
|
||||
: StartCoroutine(AnimatePart(isOpen ? openRot : closedRot));
|
||||
}
|
||||
|
||||
public void ResetToClosed()
|
||||
{
|
||||
isOpen = false;
|
||||
openAmount = 0f;
|
||||
if (animationCoroutine != null) StopCoroutine(animationCoroutine);
|
||||
transform.localRotation = closedRot;
|
||||
if (useHinge) transform.localPosition = closedPos;
|
||||
}
|
||||
|
||||
private IEnumerator AnimatePart(Quaternion targetRot)
|
||||
{
|
||||
// Пока угол между текущим и целевым вращением больше 0.1 градуса
|
||||
while (Quaternion.Angle(transform.localRotation, targetRot) > 0.1f)
|
||||
{
|
||||
// Плавно вращаем деталь
|
||||
transform.localRotation = Quaternion.Lerp(transform.localRotation, targetRot, Time.deltaTime * speed);
|
||||
yield return null; // Ждем следующего кадра
|
||||
}
|
||||
|
||||
// Принудительно доводим до идеального угла в конце
|
||||
transform.localRotation = targetRot;
|
||||
}
|
||||
|
||||
private IEnumerator AnimateHinge(float target)
|
||||
{
|
||||
while (Mathf.Abs(openAmount - target) > 0.001f)
|
||||
{
|
||||
openAmount = Mathf.MoveTowards(openAmount, target, Time.deltaTime * speed * 0.35f);
|
||||
ApplyHinge(Mathf.SmoothStep(0f, 1f, openAmount));
|
||||
yield return null;
|
||||
}
|
||||
openAmount = target;
|
||||
ApplyHinge(target);
|
||||
}
|
||||
|
||||
private void ApplyHinge(float t)
|
||||
{
|
||||
Quaternion q = Quaternion.AngleAxis(openAngle * t, hingeAxis);
|
||||
transform.localRotation = q * closedRot;
|
||||
transform.localPosition = hingePoint + q * (closedPos - hingePoint);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9aac6d89a0a64dc6ba41ec26a0117e79
|
||||
timeCreated: 1789943180
|
||||
@@ -0,0 +1,149 @@
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Посадка/высадка игрока (клавиша F), управление машиной и внешняя камера CarOrbitCamera.
|
||||
/// Двигатель заводится при первом нажатии газа (если исправны АКБ и свечи).
|
||||
/// </summary>
|
||||
public class VehicleInteraction : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Header("Setup")]
|
||||
[SerializeField] private Transform exitPoint;
|
||||
[SerializeField] private UIManager uiManager;
|
||||
|
||||
/// <summary>Машина, в которой сейчас сидит игрок (null — игрок пешком).</summary>
|
||||
public static VehicleInteraction Current { get; private set; }
|
||||
|
||||
private CarOrbitCamera globalCarCamera;
|
||||
private CarController carController;
|
||||
private GameObject playerInstance;
|
||||
[HideInInspector] public bool isPlayerInside;
|
||||
private int enteredFrame = -1;
|
||||
|
||||
public CarController Controller => carController;
|
||||
public Transform ExitPoint => exitPoint;
|
||||
|
||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
|
||||
private static void ResetStatics() => Current = null;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
carController = GetComponent<CarController>();
|
||||
if (carController == null) carController = GetComponentInChildren<CarController>();
|
||||
if (carController == null) carController = GetComponentInParent<CarController>();
|
||||
if (uiManager == null) uiManager = FindAnyObjectByType<UIManager>();
|
||||
globalCarCamera = FindAnyObjectByType<CarOrbitCamera>(FindObjectsInactive.Include);
|
||||
|
||||
if (exitPoint == null)
|
||||
{
|
||||
foreach (Transform t in GetComponentsInChildren<Transform>(true))
|
||||
{
|
||||
string n = t.name.Replace(" ", "").ToLowerInvariant();
|
||||
if (n == "exitpoint") { exitPoint = t; break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Interact(GameObject interactor)
|
||||
{
|
||||
if (!isPlayerInside) EnterVehicle(interactor);
|
||||
}
|
||||
|
||||
public string GetPrompt() => "[F] Сесть в машину";
|
||||
|
||||
private void EnterVehicle(GameObject player)
|
||||
{
|
||||
if (player == null) return;
|
||||
|
||||
// Нельзя садиться за руль с деталью или канистрой в руках — кладем её на землю
|
||||
PlayerHands hands = player.GetComponentInChildren<PlayerHands>();
|
||||
if (hands != null) hands.DropEverything();
|
||||
|
||||
isPlayerInside = true;
|
||||
enteredFrame = Time.frameCount;
|
||||
Current = this;
|
||||
playerInstance = player;
|
||||
playerInstance.SetActive(false);
|
||||
|
||||
if (globalCarCamera == null) globalCarCamera = FindAnyObjectByType<CarOrbitCamera>(FindObjectsInactive.Include);
|
||||
if (globalCarCamera != null)
|
||||
{
|
||||
globalCarCamera.SetTarget(transform);
|
||||
globalCarCamera.gameObject.SetActive(true);
|
||||
}
|
||||
|
||||
if (carController != null) carController.SetDriver(true);
|
||||
|
||||
if (uiManager != null)
|
||||
{
|
||||
uiManager.HidePrompt();
|
||||
uiManager.ToggleDashboard(true);
|
||||
}
|
||||
|
||||
GameHUD.Notify("[W] — завести и ехать, [Space] — ручник, [L] — фары, [F] — выйти", GameUI.Muted);
|
||||
}
|
||||
|
||||
public void ExitVehicle()
|
||||
{
|
||||
if (!isPlayerInside) return;
|
||||
isPlayerInside = false;
|
||||
if (Current == this) Current = null;
|
||||
if (carController != null) carController.SetDriver(false);
|
||||
|
||||
if (globalCarCamera != null)
|
||||
{
|
||||
globalCarCamera.SetTarget(null);
|
||||
globalCarCamera.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
if (uiManager != null) uiManager.ToggleDashboard(false);
|
||||
|
||||
if (playerInstance == null) return;
|
||||
|
||||
CharacterController charController = playerInstance.GetComponent<CharacterController>();
|
||||
if (charController != null) charController.enabled = false;
|
||||
|
||||
Vector3 pos = exitPoint != null
|
||||
? exitPoint.position
|
||||
: transform.position - transform.right * 1.8f + Vector3.up * 0.5f;
|
||||
if (Physics.Raycast(pos + Vector3.up * 1.5f, Vector3.down, out RaycastHit hit, 4f, ~0, QueryTriggerInteraction.Ignore)
|
||||
&& !hit.collider.transform.IsChildOf(transform))
|
||||
pos.y = hit.point.y + 1.0f;
|
||||
|
||||
playerInstance.transform.position = pos;
|
||||
playerInstance.transform.rotation = Quaternion.Euler(0f, transform.eulerAngles.y, 0f);
|
||||
|
||||
if (charController != null) charController.enabled = true;
|
||||
|
||||
playerInstance.SetActive(true);
|
||||
playerInstance = null;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (!isPlayerInside) return;
|
||||
|
||||
if (GameInputLock.IsLocked)
|
||||
{
|
||||
if (carController != null) carController.ProcessInput(0f, 0f, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (carController != null)
|
||||
{
|
||||
float vertical = Input.GetAxis("Vertical");
|
||||
float horizontal = Input.GetAxis("Horizontal");
|
||||
bool isBraking = Input.GetKey(KeyCode.Space);
|
||||
|
||||
carController.ProcessInput(vertical, horizontal, isBraking);
|
||||
if (uiManager != null) uiManager.UpdateSpeed(carController.SpeedKmH);
|
||||
}
|
||||
|
||||
if (Time.frameCount != enteredFrame && (Input.GetKeyDown(KeyCode.F) || Input.GetKeyDown(KeyCode.E)))
|
||||
ExitVehicle();
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
if (isPlayerInside) ExitVehicle();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bf303cb78d154d429f7c0c90338cec80
|
||||
timeCreated: 1789819810
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5df59613a0b544e3b32d32cf1c4ea973
|
||||
timeCreated: 1792711737
|
||||
@@ -0,0 +1,192 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Осмотр автомобиля: список дефектов для торга с продавцом и чек-лист состояния для продажи.
|
||||
/// Скрытые дефекты (под капотом, ошибки ДВС, перекрас) видны только после проверки игроком.
|
||||
/// </summary>
|
||||
public static class CarInspection
|
||||
{
|
||||
public class Defect
|
||||
{
|
||||
public string text;
|
||||
public float discountPercent;
|
||||
public bool revealed;
|
||||
public string howToReveal;
|
||||
}
|
||||
|
||||
public static List<Defect> CollectDefects(CarOwnership car)
|
||||
{
|
||||
List<Defect> list = new List<Defect>();
|
||||
if (car == null) return list;
|
||||
Transform root = car.transform;
|
||||
|
||||
// --- Видно сразу ---
|
||||
float dirt = 0f;
|
||||
int dirtN = 0;
|
||||
int rusted = 0;
|
||||
foreach (CarPartVisuals v in root.GetComponentsInChildren<CarPartVisuals>())
|
||||
{
|
||||
if (!v.HasPaintSlots) continue;
|
||||
dirt += v.DirtAmount;
|
||||
dirtN++;
|
||||
if (v.Stage == RepairStage.Rusted) rusted++;
|
||||
}
|
||||
if (dirtN > 0 && dirt / dirtN > 0.3f)
|
||||
list.Add(new Defect { text = "Кузов сильно загрязнен — не видно реального состояния ЛКП", discountPercent = 2f, revealed = true });
|
||||
if (rusted > 0)
|
||||
list.Add(new Defect { text = $"Ржавчина на кузове: {rusted} очаг(а)", discountPercent = Mathf.Min(8f, 2f + rusted * 1.5f), revealed = true });
|
||||
|
||||
int missing = 0;
|
||||
foreach (CarPartMountZone z in root.GetComponentsInChildren<CarPartMountZone>(true))
|
||||
{
|
||||
if (z.TargetPart != null && z.TargetPart.GetComponent<EnginePart>() != null) continue;
|
||||
if (z.TargetPart != null && z.TargetPart.IsWheel) continue;
|
||||
missing++;
|
||||
}
|
||||
if (missing > 0)
|
||||
list.Add(new Defect { text = $"Некомплект: нет {missing} кузовн. детал(и)", discountPercent = Mathf.Min(9f, 3f * missing), revealed = true });
|
||||
|
||||
int flat = 0, wheelsMissing = 0;
|
||||
foreach (CarWheelCondition w in root.GetComponentsInChildren<CarWheelCondition>(true))
|
||||
{
|
||||
CarPart p = w.GetComponent<CarPart>();
|
||||
if (p != null && (!p.gameObject.activeInHierarchy || p.State != PartState.Installed)) wheelsMissing++;
|
||||
else if (w.IsFlat) flat++;
|
||||
}
|
||||
if (wheelsMissing > 0)
|
||||
list.Add(new Defect { text = "Стоит на кирпичах — нет колеса", discountPercent = 5f, revealed = true });
|
||||
if (flat > 0)
|
||||
list.Add(new Defect { text = $"Спущено колес: {flat}", discountPercent = 2f * flat, revealed = true });
|
||||
|
||||
// --- Под капотом (нужно открыть капот) ---
|
||||
CarFluids fluids = root.GetComponent<CarFluids>();
|
||||
if (fluids != null)
|
||||
{
|
||||
if (fluids.EngineOil.FillPercent < 0.5f || fluids.EngineOil.quality < 0.3f)
|
||||
list.Add(new Defect { text = "Старое черное масло / низкий уровень", discountPercent = 3f, revealed = car.hoodInspected, howToReveal = "откройте капот / проверьте щуп" });
|
||||
if (fluids.Coolant.FillPercent < 0.5f)
|
||||
list.Add(new Defect { text = "Низкий уровень антифриза", discountPercent = 2f, revealed = car.hoodInspected, howToReveal = "откройте капот" });
|
||||
if (fluids.BrakeFluid.FillPercent < 0.3f)
|
||||
list.Add(new Defect { text = "Тормозная жидкость ниже минимума", discountPercent = 2f, revealed = car.hoodInspected, howToReveal = "откройте капот" });
|
||||
}
|
||||
|
||||
EngineBayManager bay = root.GetComponent<EngineBayManager>();
|
||||
if (bay != null)
|
||||
{
|
||||
if (bay.GetPart(EnginePartType.Battery) == null)
|
||||
list.Add(new Defect { text = "Нет аккумулятора", discountPercent = 4f, revealed = car.hoodInspected, howToReveal = "откройте капот" });
|
||||
|
||||
// --- Ошибки двигателя (нужен OBD-сканер) ---
|
||||
foreach (string code in bay.GetObdCodes())
|
||||
{
|
||||
if (code.StartsWith("C1241")) continue;
|
||||
list.Add(new Defect { text = "OBD: " + code, discountPercent = 3f, revealed = car.obdScanned, howToReveal = "OBD-сканер" });
|
||||
}
|
||||
}
|
||||
|
||||
// --- Скрытый перекрас (нужен толщиномер) ---
|
||||
int repaint = 0;
|
||||
foreach (CarPartVisuals v in root.GetComponentsInChildren<CarPartVisuals>())
|
||||
if (v.HiddenRepaint && v.Stage == RepairStage.Healthy) repaint++;
|
||||
if (repaint > 0)
|
||||
list.Add(new Defect { text = $"Скрытый перекрас/шпаклёвка: {repaint} детал(и) (250–450 мкм)", discountPercent = 4f, revealed = car.hiddenRepaintFound, howToReveal = "толщиномер ЛКП" });
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public class SaleReport
|
||||
{
|
||||
public bool washed, rustFixed, bodyComplete, wheelsOk, engineOk, fluidsOk;
|
||||
public float score;
|
||||
public float salePrice;
|
||||
public float referencePrice;
|
||||
public readonly List<string> issues = new List<string>();
|
||||
}
|
||||
|
||||
/// <summary>Комплексная оценка автомобиля для перепродажи.</summary>
|
||||
public static SaleReport EvaluateForSale(CarOwnership car)
|
||||
{
|
||||
SaleReport r = new SaleReport();
|
||||
if (car == null) return r;
|
||||
Transform root = car.transform;
|
||||
bool diploma = GameEconomyManager.Instance == null || GameEconomyManager.Instance.DiplomaFeatures;
|
||||
|
||||
// 1. Мойка
|
||||
float dirt = 0f;
|
||||
int n = 0;
|
||||
bool rustOk = true;
|
||||
foreach (CarPartVisuals v in root.GetComponentsInChildren<CarPartVisuals>())
|
||||
{
|
||||
if (!v.HasPaintSlots) continue;
|
||||
dirt += v.DirtAmount;
|
||||
n++;
|
||||
RepairStage s = v.Stage;
|
||||
if (s != RepairStage.Healthy && s != RepairStage.Repaired) rustOk = false;
|
||||
}
|
||||
float avgDirt = n > 0 ? dirt / n : 0f;
|
||||
r.washed = avgDirt <= 0.03f;
|
||||
if (!r.washed) r.issues.Add($"Кузов не вымыт (грязь {Mathf.RoundToInt(avgDirt * 100f)}%)");
|
||||
r.rustFixed = rustOk;
|
||||
if (!rustOk) r.issues.Add("Ржавчина зачищена и покрашена не везде");
|
||||
|
||||
// 2. Комплектность кузова
|
||||
int missing = 0;
|
||||
foreach (CarPartMountZone z in root.GetComponentsInChildren<CarPartMountZone>(true))
|
||||
{
|
||||
if (z.TargetPart != null && (z.TargetPart.IsWheel || z.TargetPart.GetComponent<EnginePart>() != null)) continue;
|
||||
missing++;
|
||||
}
|
||||
r.bodyComplete = missing == 0;
|
||||
if (!r.bodyComplete) r.issues.Add($"Не установлено кузовных деталей: {missing}");
|
||||
|
||||
// 3. Колеса
|
||||
int wheelsOk = 0, wheelsTotal = 0;
|
||||
foreach (WheelCollider wc in root.GetComponentsInChildren<WheelCollider>(true))
|
||||
{
|
||||
wheelsTotal++;
|
||||
bool ok = false;
|
||||
foreach (CarPart p in root.GetComponentsInChildren<CarPart>(false))
|
||||
{
|
||||
if (p.LinkedWheelCollider != wc || p.State != PartState.Installed) continue;
|
||||
CarWheelCondition cond = p.GetComponent<CarWheelCondition>();
|
||||
bool flat = cond != null && cond.IsFlat;
|
||||
bool bolted = p.TotalBoltsCount == 0 || p.TightenedBoltsCount >= p.TotalBoltsCount;
|
||||
ok = !flat && bolted && wc.enabled;
|
||||
break;
|
||||
}
|
||||
if (ok) wheelsOk++;
|
||||
}
|
||||
bool bricks = false;
|
||||
foreach (WheelBrickSupport b in Object.FindObjectsByType<WheelBrickSupport>(FindObjectsSortMode.None))
|
||||
if (Vector3.Distance(b.transform.position, root.position) < 4f) bricks = true;
|
||||
r.wheelsOk = wheelsOk >= wheelsTotal && wheelsTotal > 0 && !bricks;
|
||||
if (!r.wheelsOk) r.issues.Add($"Целых затянутых колес: {wheelsOk}/{wheelsTotal}{(bricks ? ", машина на кирпичах" : "")}");
|
||||
|
||||
// 4–5. Подкапотное пространство
|
||||
EngineBayManager bay = root.GetComponent<EngineBayManager>();
|
||||
if (diploma && bay != null)
|
||||
{
|
||||
r.engineOk = bay.IsReadyForSale(r.issues);
|
||||
r.fluidsOk = bay.AreFluidsFresh(r.issues);
|
||||
}
|
||||
else
|
||||
{
|
||||
r.engineOk = true;
|
||||
r.fluidsOk = true;
|
||||
}
|
||||
|
||||
r.score = (r.washed ? 0.12f : 0f) + (r.rustFixed ? 0.25f : 0f) + (r.bodyComplete ? 0.18f : 0f)
|
||||
+ (r.wheelsOk ? 0.15f : 0f) + (r.engineOk ? 0.18f : 0f) + (r.fluidsOk ? 0.12f : 0f);
|
||||
|
||||
// Цена: при полном восстановлении +45..75% от цены покупки, мойка +8%
|
||||
float reference = car.purchasePrice > 1f ? car.purchasePrice : car.marketValue * 0.45f;
|
||||
r.referencePrice = reference;
|
||||
int seed = Mathf.Abs((car.carTitle + car.year + car.mileageKm).GetHashCode()) % 1000;
|
||||
float fullBonus = Mathf.Lerp(0.45f, 0.75f, seed / 999f);
|
||||
float mult = Mathf.Lerp(0.72f, 1f + fullBonus, r.score * r.score);
|
||||
if (r.washed) mult *= 1.08f;
|
||||
r.salePrice = Mathf.Round(reference * mult / 10f) * 10f;
|
||||
return r;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0c87153c12db56942aa79566636f15f8
|
||||
@@ -0,0 +1,358 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
[Serializable]
|
||||
public class CarCatalogItem
|
||||
{
|
||||
public string carTitle = "Ibishu Covet 1.5";
|
||||
public GameObject carPrefab;
|
||||
public float idealPrice = 4500f;
|
||||
public int minYear = 1992;
|
||||
public int maxYear = 2005;
|
||||
public string bodyType = "Хэтчбек";
|
||||
}
|
||||
|
||||
public class CarListing
|
||||
{
|
||||
public int id;
|
||||
public CarCatalogItem catalogItem;
|
||||
public int seed;
|
||||
public Color bodyColor;
|
||||
public string bodyColorName;
|
||||
public int year;
|
||||
public int mileageKm;
|
||||
public int price;
|
||||
public DriveType driveType;
|
||||
public string sellerName;
|
||||
public float sellerRating;
|
||||
public string sellerPhone;
|
||||
public string sellerDescription;
|
||||
public CarDefectsSummary defectsSummary;
|
||||
public Sprite photo;
|
||||
public bool isMeetingArranged;
|
||||
public GameObject spawnedInstance;
|
||||
public Vector3 spawnPosition;
|
||||
public bool isSold;
|
||||
}
|
||||
|
||||
public class CarMarketManager : MonoBehaviour
|
||||
{
|
||||
[Header("Каталог префабов машин для продажи")]
|
||||
[SerializeField] private CarCatalogItem[] carCatalog;
|
||||
|
||||
[Header("Точки спавна машин для встречи на карте")]
|
||||
[SerializeField] private Transform[] meetingSpawnPoints;
|
||||
|
||||
[Header("Настройки генерации объявлений")]
|
||||
[SerializeField] private int listingsCount = 6;
|
||||
[SerializeField] private Color[] possibleBodyColors = new Color[]
|
||||
{
|
||||
new Color(0.12f, 0.32f, 0.75f), // Синий
|
||||
new Color(0.75f, 0.15f, 0.15f), // Красный
|
||||
new Color(0.85f, 0.85f, 0.88f), // Белый / Серебро
|
||||
new Color(0.18f, 0.20f, 0.22f), // Темно-серый
|
||||
new Color(0.15f, 0.48f, 0.25f), // Темно-зеленый
|
||||
new Color(0.85f, 0.65f, 0.12f) // Желтый / Золотистый
|
||||
};
|
||||
|
||||
private readonly string[] colorNames = new string[]
|
||||
{
|
||||
"Синий металлик", "Красный рубин", "Серебристый металлик", "Мокрый асфальт", "Изумрудный перламутр", "Золотистый металлик"
|
||||
};
|
||||
|
||||
private readonly string[] sellerNames = new string[]
|
||||
{
|
||||
"Алексей Смирнов", "Сергей (Частник)", "Михаил Ремонт", "Дмитрий В.", "Виктор Авто", "Артем Романов", "Владимир", "Елена (муж попросил)"
|
||||
};
|
||||
|
||||
[Header("Настройки ракурса фотостудии")]
|
||||
[SerializeField] private Vector3 cameraOffset = new Vector3(-2.6f, 1.35f, 3.4f);
|
||||
[SerializeField] private Vector3 lookAtOffset = new Vector3(0f, 0.45f, 0f);
|
||||
[SerializeField] private int photoWidth = 640;
|
||||
[SerializeField] private int photoHeight = 360;
|
||||
|
||||
public readonly List<CarListing> Listings = new List<CarListing>();
|
||||
public CarListing ActiveMeetingListing { get; private set; }
|
||||
|
||||
public event Action<CarListing> OnMeetingArranged;
|
||||
public event Action OnMeetingCleared;
|
||||
public event Action OnListingsUpdated;
|
||||
|
||||
public CarCatalogItem[] Catalog => carCatalog;
|
||||
|
||||
/// <summary>Настройка рынка из Editor-автонастройки.</summary>
|
||||
public void Configure(CarCatalogItem[] catalog, Transform[] spawnPoints)
|
||||
{
|
||||
carCatalog = catalog;
|
||||
meetingSpawnPoints = spawnPoints;
|
||||
}
|
||||
|
||||
private GameObject photoStudioRoot;
|
||||
private Camera photoCamera;
|
||||
private RenderTexture photoRT;
|
||||
private int lastUsedSpawnPointIndex = -1;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
EnsureListingsGenerated();
|
||||
}
|
||||
|
||||
public void EnsureListingsGenerated()
|
||||
{
|
||||
if (Listings.Count == 0)
|
||||
{
|
||||
SetupPhotoStudio();
|
||||
GenerateListings();
|
||||
}
|
||||
}
|
||||
|
||||
private void SetupPhotoStudio()
|
||||
{
|
||||
if (photoStudioRoot != null) return;
|
||||
|
||||
// Создаем изолированную студию глубоко под картой
|
||||
photoStudioRoot = new GameObject("Offscreen_CarPhotoStudio");
|
||||
photoStudioRoot.transform.position = new Vector3(0f, -500f, 0f);
|
||||
|
||||
// Подиум/асфальт для приятного фона на фотографиях
|
||||
GameObject floor = GameObject.CreatePrimitive(PrimitiveType.Plane);
|
||||
Destroy(floor.GetComponent<Collider>());
|
||||
floor.transform.SetParent(photoStudioRoot.transform, false);
|
||||
floor.transform.localScale = new Vector3(3f, 1f, 3f);
|
||||
Renderer floorRend = floor.GetComponent<Renderer>();
|
||||
Material floorMat = new Material(Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard"));
|
||||
floorMat.color = new Color(0.22f, 0.24f, 0.27f);
|
||||
floorRend.sharedMaterial = floorMat;
|
||||
|
||||
// Освещение студии
|
||||
GameObject lightObj = new GameObject("StudioLight");
|
||||
lightObj.transform.SetParent(photoStudioRoot.transform, false);
|
||||
lightObj.transform.localPosition = new Vector3(-3f, 5f, 4f);
|
||||
lightObj.transform.localRotation = Quaternion.Euler(45f, 135f, 0f);
|
||||
Light studioLight = lightObj.AddComponent<Light>();
|
||||
studioLight.type = LightType.Directional;
|
||||
studioLight.intensity = 1.4f;
|
||||
|
||||
// Камера для рендера фото объявления
|
||||
GameObject camObj = new GameObject("StudioCamera");
|
||||
camObj.transform.SetParent(photoStudioRoot.transform, false);
|
||||
photoCamera = camObj.AddComponent<Camera>();
|
||||
photoCamera.clearFlags = CameraClearFlags.SolidColor;
|
||||
photoCamera.backgroundColor = new Color(0.48f, 0.60f, 0.74f);
|
||||
photoCamera.fieldOfView = 40f;
|
||||
photoCamera.enabled = false; // Выключена, рендерит только по команде Render()
|
||||
|
||||
photoRT = new RenderTexture(photoWidth, photoHeight, 24, RenderTextureFormat.ARGB32);
|
||||
photoCamera.targetTexture = photoRT;
|
||||
}
|
||||
|
||||
[ContextMenu("Обновить объявления")]
|
||||
public void GenerateListings()
|
||||
{
|
||||
if (carCatalog == null || carCatalog.Length == 0)
|
||||
{
|
||||
Debug.LogWarning("[CarMarketManager] Добавьте хотя бы один префаб машины в Car Catalog!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (photoStudioRoot == null) SetupPhotoStudio();
|
||||
|
||||
Listings.Clear();
|
||||
|
||||
for (int i = 0; i < listingsCount; i++)
|
||||
{
|
||||
CarCatalogItem item = carCatalog[UnityEngine.Random.Range(0, carCatalog.Length)];
|
||||
if (item.carPrefab == null) continue;
|
||||
|
||||
int seed = UnityEngine.Random.Range(10000, 999999);
|
||||
int colorIndex = (possibleBodyColors.Length > 0) ? UnityEngine.Random.Range(0, possibleBodyColors.Length) : 0;
|
||||
Color color = (possibleBodyColors.Length > 0) ? possibleBodyColors[colorIndex] : Color.blue;
|
||||
string colorName = (colorIndex < colorNames.Length) ? colorNames[colorIndex] : "Заводской окрас";
|
||||
|
||||
int year = UnityEngine.Random.Range(item.minYear, item.maxYear + 1);
|
||||
int mileage = (2026 - year) * UnityEngine.Random.Range(9500, 18000);
|
||||
|
||||
// 1. Временно спавним машину в фотостудии для точного снимка
|
||||
GameObject tempCar = Instantiate(item.carPrefab, photoStudioRoot.transform.position, Quaternion.identity);
|
||||
|
||||
// Отключаем гравитацию в фотобоксе, чтобы машина не падала во время кадра
|
||||
Rigidbody rb = tempCar.GetComponent<Rigidbody>();
|
||||
if (rb != null) rb.isKinematic = true;
|
||||
|
||||
CarController ctrl = tempCar.GetComponent<CarController>();
|
||||
DriveType drive = ctrl != null ? ctrl.driveType : DriveType.FWD;
|
||||
|
||||
CarConditionGenerator gen = tempCar.GetComponent<CarConditionGenerator>();
|
||||
if (gen == null) gen = tempCar.AddComponent<CarConditionGenerator>();
|
||||
|
||||
// Применяем состояние по Seed (точно такое же применится при выезде на встречу!)
|
||||
gen.ApplyConditionBySeed(seed, color, true, out CarDefectsSummary defects);
|
||||
|
||||
// 2. Выставляем камеру фотостудии в 3/4 спереди и делаем снимок
|
||||
photoCamera.transform.position = tempCar.transform.position + cameraOffset;
|
||||
photoCamera.transform.LookAt(tempCar.transform.position + lookAtOffset);
|
||||
Sprite capturedPhoto = CaptureStudioPhoto();
|
||||
|
||||
// 3. Сразу удаляем временную машину, чтобы не нагружать сцену!
|
||||
DestroyImmediate(tempCar);
|
||||
|
||||
// 4. Считаем итоговую цену и генерируем живое описание продавца
|
||||
float rawPrice = item.idealPrice - defects.totalPricePenalty - (mileage / 10000f) * 65f;
|
||||
int finalPrice = Mathf.RoundToInt(Mathf.Max(item.idealPrice * 0.25f, rawPrice) / 50f) * 50;
|
||||
|
||||
string sName = sellerNames[UnityEngine.Random.Range(0, sellerNames.Length)];
|
||||
float sRating = Mathf.Round(UnityEngine.Random.Range(4.5f, 5.0f) * 10f) / 10f;
|
||||
string sPhone = $"+375 ({(UnityEngine.Random.value < 0.5f ? 29 : 33)}) {UnityEngine.Random.Range(100, 999)}-{UnityEngine.Random.Range(10, 99)}-{UnityEngine.Random.Range(10, 99)}";
|
||||
|
||||
CarListing listing = new CarListing
|
||||
{
|
||||
id = i + 1,
|
||||
catalogItem = item,
|
||||
seed = seed,
|
||||
bodyColor = color,
|
||||
bodyColorName = colorName,
|
||||
year = year,
|
||||
mileageKm = mileage,
|
||||
price = finalPrice,
|
||||
driveType = drive,
|
||||
sellerName = sName,
|
||||
sellerRating = sRating,
|
||||
sellerPhone = sPhone,
|
||||
sellerDescription = BuildSellerDescription(defects, year, mileage),
|
||||
defectsSummary = defects,
|
||||
photo = capturedPhoto
|
||||
};
|
||||
|
||||
Listings.Add(listing);
|
||||
}
|
||||
|
||||
OnListingsUpdated?.Invoke();
|
||||
}
|
||||
|
||||
private Sprite CaptureStudioPhoto()
|
||||
{
|
||||
RenderTexture prev = RenderTexture.active;
|
||||
RenderTexture.active = photoRT;
|
||||
|
||||
photoCamera.Render();
|
||||
|
||||
Texture2D tex = new Texture2D(photoWidth, photoHeight, TextureFormat.RGB24, false);
|
||||
tex.ReadPixels(new Rect(0, 0, photoWidth, photoHeight), 0, 0);
|
||||
tex.Apply();
|
||||
|
||||
RenderTexture.active = prev;
|
||||
|
||||
return Sprite.Create(tex, new Rect(0, 0, photoWidth, photoHeight), new Vector2(0.5f, 0.5f));
|
||||
}
|
||||
|
||||
private string BuildSellerDescription(CarDefectsSummary d, int year, int mileage)
|
||||
{
|
||||
List<string> notes = new List<string>();
|
||||
|
||||
if (d.rustedPartsCount == 0 && d.missingBodyPartsCount == 0 && d.flatTiresCount == 0 && d.missingWheelsCount == 0 && d.lowFluidsCount == 0 && d.engineIssuesCount == 0)
|
||||
{
|
||||
return $"Отличное состояние для {year} года! Кузов без рыжиков, вся комплектная, родной пробег {mileage:N0} км. Сел и поехал, без вложений. Юридически чистая, торг минимальный.";
|
||||
}
|
||||
|
||||
if (d.rustedPartsCount > 0)
|
||||
notes.Add($"по кузову есть возрастные рыжики на кромках ({d.rustedPartsCount} эл.)");
|
||||
|
||||
if (d.missingBodyPartsCount > 0)
|
||||
{
|
||||
string missingList = string.Join(", ", d.missingPartNames);
|
||||
notes.Add($"сняты некоторые детали ({missingList})");
|
||||
}
|
||||
|
||||
if (d.lowFluidsCount > 0)
|
||||
notes.Add("нужно долить технические жидкости под капотом");
|
||||
|
||||
if (d.startProblems)
|
||||
notes.Add("иногда не заводится с первого раза (наверное, аккумулятор подсел)");
|
||||
if (d.oilProblems)
|
||||
notes.Add("масло давно не менял");
|
||||
if (d.overheatProblems)
|
||||
notes.Add("летом в пробках бывало грелся");
|
||||
if (d.brakeProblems)
|
||||
notes.Add("тормоза немного мягкие");
|
||||
if (d.dirtAmount > 0.7f)
|
||||
notes.Add("стояла под деревом, давно не мыта");
|
||||
|
||||
if (d.missingWheelsCount > 0)
|
||||
notes.Add("стоит на кирпичах (нет одного колеса, приезжайте со своей запаской)");
|
||||
else if (d.flatTiresCount > 0)
|
||||
notes.Add($"спущено колесо ({d.flatTiresCount} шт.)");
|
||||
|
||||
string details = string.Join(", ", notes);
|
||||
return $"Продаю как есть, под восстановление или перепродажу: {details}. Мотор и коробка живые, хороший торг у капота!";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вызывается при нажатии кнопки "Договориться о встрече" в приложении телефона.
|
||||
/// Спавнит машину на карте с её точным состоянием и активирует GPS навигацию.
|
||||
/// </summary>
|
||||
public void ArrangeMeeting(CarListing listing)
|
||||
{
|
||||
if (listing == null || listing.catalogItem == null || listing.catalogItem.carPrefab == null)
|
||||
return;
|
||||
|
||||
// Если машина из этого объявления уже заспавнена — просто активируем метку
|
||||
if (listing.isMeetingArranged && listing.spawnedInstance != null)
|
||||
{
|
||||
ActiveMeetingListing = listing;
|
||||
OnMeetingArranged?.Invoke(listing);
|
||||
return;
|
||||
}
|
||||
|
||||
Transform spawnPoint = GetNextMeetingSpawnPoint();
|
||||
Vector3 pos = spawnPoint != null ? spawnPoint.position : (transform.position + transform.forward * 15f);
|
||||
Quaternion rot = spawnPoint != null ? spawnPoint.rotation : Quaternion.identity;
|
||||
|
||||
GameObject carObj = Instantiate(listing.catalogItem.carPrefab, pos, rot);
|
||||
carObj.name = $"MarketCar_{listing.catalogItem.carTitle}_{listing.id}";
|
||||
|
||||
CarConditionGenerator gen = carObj.GetComponent<CarConditionGenerator>();
|
||||
if (gen == null) gen = carObj.AddComponent<CarConditionGenerator>();
|
||||
|
||||
// Применяем ТОТ ЖЕ САМЫЙ Seed, что был на фотографии в объявлении!
|
||||
gen.ApplyConditionBySeed(listing.seed, listing.bodyColor, false, out _);
|
||||
|
||||
CarOwnership own = carObj.GetComponent<CarOwnership>();
|
||||
if (own == null) own = carObj.AddComponent<CarOwnership>();
|
||||
own.SetupFromListing(listing);
|
||||
own.isOwned = false;
|
||||
|
||||
listing.isMeetingArranged = true;
|
||||
listing.spawnedInstance = carObj;
|
||||
listing.spawnPosition = pos;
|
||||
ActiveMeetingListing = listing;
|
||||
|
||||
OnMeetingArranged?.Invoke(listing);
|
||||
}
|
||||
|
||||
/// <summary>Машина куплена: объявление снимается с рынка.</summary>
|
||||
public void MarkListingSold(CarListing listing)
|
||||
{
|
||||
if (listing == null) return;
|
||||
listing.isSold = true;
|
||||
Listings.Remove(listing);
|
||||
if (ActiveMeetingListing == listing) ClearActiveMeeting();
|
||||
OnListingsUpdated?.Invoke();
|
||||
}
|
||||
|
||||
public void ClearActiveMeeting()
|
||||
{
|
||||
if (ActiveMeetingListing != null)
|
||||
{
|
||||
ActiveMeetingListing = null;
|
||||
OnMeetingCleared?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
private Transform GetNextMeetingSpawnPoint()
|
||||
{
|
||||
if (meetingSpawnPoints == null || meetingSpawnPoints.Length == 0) return null;
|
||||
lastUsedSpawnPointIndex = (lastUsedSpawnPointIndex + 1) % meetingSpawnPoints.Length;
|
||||
return meetingSpawnPoints[lastUsedSpawnPointIndex];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: dc01e717989741cca3b70672b43d4fe1
|
||||
timeCreated: 1792711755
|
||||
@@ -0,0 +1,104 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Сведения о сделке по конкретной машине: объявление, цена покупки, затраты на ремонт
|
||||
/// и что игрок уже проверил при осмотре (капот, OBD-сканер, толщиномер).
|
||||
/// </summary>
|
||||
[DisallowMultipleComponent]
|
||||
public class CarOwnership : MonoBehaviour
|
||||
{
|
||||
public static readonly List<CarOwnership> All = new List<CarOwnership>();
|
||||
|
||||
[Header("Объявление")]
|
||||
public string carTitle = "Автомобиль";
|
||||
public int year = 2001;
|
||||
public int mileageKm = 180000;
|
||||
public float askingPrice = 2500f;
|
||||
[Tooltip("Цена идеального экземпляра на рынке")]
|
||||
public float marketValue = 4500f;
|
||||
public string sellerName = "Продавец";
|
||||
|
||||
[Header("Сделка")]
|
||||
public bool isOwned;
|
||||
public bool isStarterCar;
|
||||
public float purchasePrice;
|
||||
public float expenses;
|
||||
public readonly List<string> expenseLog = new List<string>();
|
||||
|
||||
[Header("Осмотр перед покупкой")]
|
||||
public bool hoodInspected;
|
||||
public bool obdScanned;
|
||||
public bool thicknessChecked;
|
||||
public bool hiddenRepaintFound;
|
||||
|
||||
public CarListing Listing { get; set; }
|
||||
|
||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
|
||||
private static void ResetStatics() => All.Clear();
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
if (!All.Contains(this)) All.Add(this);
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
All.Remove(this);
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (hoodInspected || isOwned) return;
|
||||
foreach (CarPartAnimator anim in GetComponentsInChildren<CarPartAnimator>())
|
||||
{
|
||||
if (anim.IsOpen && anim.name.ToLowerInvariant().Contains("hood"))
|
||||
{
|
||||
hoodInspected = true;
|
||||
GameHUD.Notify("Вы осмотрели подкапотное пространство: уровни жидкостей и АКБ видны", GameUI.Blue);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void AddExpense(float usd, string reason)
|
||||
{
|
||||
expenses += usd;
|
||||
expenseLog.Add($"{reason}: ${usd:N0}");
|
||||
}
|
||||
|
||||
public void SetupFromListing(CarListing listing)
|
||||
{
|
||||
Listing = listing;
|
||||
if (listing == null) return;
|
||||
carTitle = listing.catalogItem != null ? listing.catalogItem.carTitle : carTitle;
|
||||
year = listing.year;
|
||||
mileageKm = listing.mileageKm;
|
||||
askingPrice = listing.price;
|
||||
marketValue = listing.catalogItem != null ? listing.catalogItem.idealPrice : askingPrice * 1.6f;
|
||||
sellerName = listing.sellerName;
|
||||
}
|
||||
|
||||
public static CarOwnership Get(GameObject anyChild)
|
||||
{
|
||||
if (anyChild == null) return null;
|
||||
return anyChild.GetComponentInParent<CarOwnership>();
|
||||
}
|
||||
|
||||
public static CarOwnership FindNearestNotOwned(Vector3 pos, float maxDist)
|
||||
{
|
||||
CarOwnership best = null;
|
||||
float bestD = maxDist;
|
||||
foreach (CarOwnership c in All)
|
||||
{
|
||||
if (c == null || c.isOwned) continue;
|
||||
float d = Vector3.Distance(pos, c.transform.position);
|
||||
if (d < bestD)
|
||||
{
|
||||
bestD = d;
|
||||
best = c;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 008312534ed74fa4db6a0bf29f621652
|
||||
@@ -0,0 +1,214 @@
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Площадка оценки и перепродажи восстановленного авто перед гаражом.
|
||||
/// Чек-лист: мойка, ржавчина, комплектность, 4 целых затянутых колеса, агрегаты > 80%, жидкости > 85%.
|
||||
/// После продажи выводится финансовый отчет сделки (покупка, затраты, продажа, чистая прибыль).
|
||||
/// </summary>
|
||||
[RequireComponent(typeof(BoxCollider))]
|
||||
public class CarSellZone : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private KeyCode sellKeyInCar = KeyCode.Return;
|
||||
[SerializeField] private KeyCode sellKeyOnFoot = KeyCode.B;
|
||||
|
||||
private enum View { None, Evaluation, Report }
|
||||
private View view = View.None;
|
||||
private CarOwnership car;
|
||||
private CarInspection.SaleReport report;
|
||||
private float soldPrice, soldPurchase, soldExpenses;
|
||||
private string soldTitle;
|
||||
private BoxCollider zone;
|
||||
private Transform player;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
zone = GetComponent<BoxCollider>();
|
||||
zone.isTrigger = true;
|
||||
gameObject.layer = 2; // Ignore Raycast — не мешает лучу игрока
|
||||
}
|
||||
|
||||
private bool Contains(Vector3 worldPos)
|
||||
{
|
||||
Vector3 local = transform.InverseTransformPoint(worldPos) - zone.center;
|
||||
Vector3 half = zone.size * 0.5f;
|
||||
return Mathf.Abs(local.x) <= half.x && Mathf.Abs(local.z) <= half.z && local.y > -2f && local.y < 4f;
|
||||
}
|
||||
|
||||
private CarOwnership FindOwnedCarInZone()
|
||||
{
|
||||
foreach (CarOwnership c in CarOwnership.All)
|
||||
if (c != null && c.isOwned && Contains(c.transform.position)) return c;
|
||||
return null;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (view != View.None)
|
||||
{
|
||||
if (Input.GetKeyDown(KeyCode.Escape)) Close();
|
||||
return;
|
||||
}
|
||||
|
||||
if (GameInputLock.IsLocked) return;
|
||||
MainMenuAndBootManager menu = MainMenuAndBootManager.Instance;
|
||||
if (menu != null && !menu.IsPlaying) return;
|
||||
|
||||
VehicleInteraction current = VehicleInteraction.Current;
|
||||
if (current != null)
|
||||
{
|
||||
CarOwnership own = current.GetComponent<CarOwnership>();
|
||||
if (own == null || !own.isOwned || !Contains(current.transform.position)) return;
|
||||
GameHUD.SetContextHint("Площадка продажи: остановитесь и нажмите [Enter] — выставить автомобиль на продажу");
|
||||
if (Input.GetKeyDown(sellKeyInCar) || Input.GetKeyDown(KeyCode.KeypadEnter))
|
||||
{
|
||||
if (current.Controller != null && current.Controller.SpeedKmH > 4f)
|
||||
GameHUD.Notify("Остановите машину на площадке", GameUI.Accent);
|
||||
else
|
||||
Open(own);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (player == null)
|
||||
{
|
||||
PlayerMovement pm = FindAnyObjectByType<PlayerMovement>();
|
||||
if (pm != null) player = pm.transform;
|
||||
}
|
||||
if (player == null || !player.gameObject.activeInHierarchy || !Contains(player.position)) return;
|
||||
|
||||
CarOwnership inZone = FindOwnedCarInZone();
|
||||
if (inZone == null) return;
|
||||
GameHUD.SetContextHint($"Площадка продажи: [B] Выставить {inZone.carTitle} на продажу");
|
||||
if (Input.GetKeyDown(sellKeyOnFoot)) Open(inZone);
|
||||
}
|
||||
|
||||
private void Open(CarOwnership c)
|
||||
{
|
||||
car = c;
|
||||
report = CarInspection.EvaluateForSale(c);
|
||||
view = View.Evaluation;
|
||||
GameInputLock.Lock(this);
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.Notification);
|
||||
}
|
||||
|
||||
private void Close()
|
||||
{
|
||||
view = View.None;
|
||||
car = null;
|
||||
GameInputLock.Unlock(this);
|
||||
}
|
||||
|
||||
private void Sell()
|
||||
{
|
||||
if (car == null || report == null) return;
|
||||
|
||||
soldTitle = car.carTitle;
|
||||
soldPrice = report.salePrice;
|
||||
soldPurchase = car.purchasePrice;
|
||||
soldExpenses = car.expenses;
|
||||
float profit = soldPrice - soldPurchase - soldExpenses;
|
||||
|
||||
GameEconomyManager eco = GameEconomyManager.Instance;
|
||||
if (eco != null)
|
||||
{
|
||||
eco.Earn(soldPrice, $"Продажа {soldTitle}");
|
||||
eco.RegisterDeal(profit);
|
||||
}
|
||||
|
||||
VehicleInteraction vi = car.GetComponent<VehicleInteraction>();
|
||||
if (vi != null && vi.isPlayerInside) vi.ExitVehicle();
|
||||
|
||||
foreach (WheelBrickSupport b in FindObjectsByType<WheelBrickSupport>(FindObjectsSortMode.None))
|
||||
if (Vector3.Distance(b.transform.position, car.transform.position) < 4f) Destroy(b.gameObject);
|
||||
|
||||
Destroy(car.gameObject);
|
||||
car = null;
|
||||
view = View.Report;
|
||||
}
|
||||
|
||||
private void OnGUI()
|
||||
{
|
||||
if (view == View.None) return;
|
||||
GameUI.Begin(-10);
|
||||
float w = GameUI.VirtualWidth;
|
||||
float h = GameUI.VirtualHeight;
|
||||
GameUI.DrawRect(new Rect(0, 0, w, h), GameUI.Bg.WithAlpha(0.55f));
|
||||
|
||||
if (view == View.Evaluation && car != null && report != null) DrawEvaluation(w, h);
|
||||
else if (view == View.Report) DrawReport(w, h);
|
||||
else Close();
|
||||
}
|
||||
|
||||
private void DrawEvaluation(float w, float h)
|
||||
{
|
||||
Rect r = new Rect(w * 0.5f - 560, h * 0.5f - 420, 1120, 840);
|
||||
GUI.Box(r, GUIContent.none, GameUI.PanelSolid);
|
||||
GUI.Label(new Rect(r.x + 30, r.y + 18, r.width - 60, 44), $"ОЦЕНКА АВТОМОБИЛЯ: {car.carTitle}", GameUI.Header);
|
||||
|
||||
float y = r.y + 80;
|
||||
Line(r, ref y, report.washed, "Кузов вымыт (бонус +8% к цене)");
|
||||
Line(r, ref y, report.rustFixed, "Ржавчина зачищена и покрашена");
|
||||
Line(r, ref y, report.bodyComplete, "Все кузовные детали установлены");
|
||||
Line(r, ref y, report.wheelsOk, "4 целых колеса установлены и прикручены");
|
||||
Line(r, ref y, report.engineOk, "Подкапотные агрегаты исправны (> 80%)");
|
||||
Line(r, ref y, report.fluidsOk, "Свежие технические жидкости (> 85%)");
|
||||
|
||||
y += 10;
|
||||
GUI.Label(new Rect(r.x + 40, y, r.width - 80, 30), $"Готовность к продаже: <b>{Mathf.RoundToInt(report.score * 100f)}%</b>", GameUI.Label);
|
||||
y += 36;
|
||||
GameUI.ProgressBar(new Rect(r.x + 40, y, r.width - 80, 22), report.score, report.score > 0.95f ? GameUI.Green : GameUI.Accent);
|
||||
y += 40;
|
||||
|
||||
if (report.issues.Count > 0)
|
||||
{
|
||||
string issues = string.Join("\n", report.issues.GetRange(0, Mathf.Min(7, report.issues.Count)));
|
||||
GUI.Label(new Rect(r.x + 40, y, r.width - 80, 200), "<color=#F2A93B>Замечания покупателя:</color>\n" + issues, GameUI.Small);
|
||||
}
|
||||
|
||||
float expenses = car.expenses;
|
||||
string purchase = car.isStarterCar ? "проектная машина (без затрат на покупку)" : GameUI.Money(car.purchasePrice);
|
||||
GUI.Label(new Rect(r.x + 40, r.yMax - 190, r.width - 80, 90),
|
||||
$"Цена покупки: {purchase}\nЗатраты на запчасти и жидкости: {GameUI.Money(expenses)}\n" +
|
||||
$"Предложение покупателя: <b><color=#4CD07D>{GameUI.Money(report.salePrice)}</color></b>", GameUI.Label);
|
||||
|
||||
if (GameUI.Btn(new Rect(r.x + 40, r.yMax - 86, 460, 62), $"ПРОДАТЬ ЗА {GameUI.Money(report.salePrice).Split(' ')[0]}", GameUI.ButtonAccent))
|
||||
Sell();
|
||||
if (GameUI.Btn(new Rect(r.xMax - 330, r.yMax - 86, 290, 62), "ДОРАБОТАТЬ МАШИНУ"))
|
||||
Close();
|
||||
}
|
||||
|
||||
private static void Line(Rect r, ref float y, bool ok, string text)
|
||||
{
|
||||
GUI.Label(new Rect(r.x + 40, y, r.width - 80, 34), $"{GameUI.Check(ok)} {text} {(ok ? "<color=#4CD07D>да</color>" : "<color=#E5534B>нет</color>")}", GameUI.Label);
|
||||
y += 40;
|
||||
}
|
||||
|
||||
private void DrawReport(float w, float h)
|
||||
{
|
||||
Rect r = new Rect(w * 0.5f - 460, h * 0.5f - 300, 920, 600);
|
||||
GUI.Box(r, GUIContent.none, GameUI.PanelSolid);
|
||||
GUI.Label(new Rect(r.x, r.y + 24, r.width, 56), "ФИНАНСОВЫЙ ОТЧЕТ СДЕЛКИ", GameUI.Title);
|
||||
GUI.Label(new Rect(r.x, r.y + 84, r.width, 30), soldTitle, GameUI.SmallCenter);
|
||||
|
||||
float profit = soldPrice - soldPurchase - soldExpenses;
|
||||
GUIStyle row = new GUIStyle(GameUI.Label) { fontSize = 24 };
|
||||
GUIStyle val = new GUIStyle(row) { alignment = TextAnchor.UpperRight };
|
||||
string[] labels = { "Цена покупки:", "Затраты на запчасти и жидкости:", "Цена продажи:" };
|
||||
float[] values = { soldPurchase, soldExpenses, soldPrice };
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
GUI.Label(new Rect(r.x + 80, r.y + 150 + i * 44, 460, 40), labels[i], row);
|
||||
GUI.Label(new Rect(r.x + 480, r.y + 150 + i * 44, r.width - 560, 40), GameUI.Money(values[i]), val);
|
||||
}
|
||||
GameUI.DrawRect(new Rect(r.x + 80, r.y + 290, r.width - 160, 2), GameUI.Hex("3A3F4A"));
|
||||
GUI.Label(new Rect(r.x + 80, r.y + 306, 460, 44), "<b>Чистая прибыль:</b>", row);
|
||||
GUI.Label(new Rect(r.x + 480, r.y + 306, r.width - 560, 44), $"<b><color={(profit >= 0 ? "#4CD07D" : "#E5534B")}>{GameUI.Money(profit)}</color></b>", val);
|
||||
|
||||
GameEconomyManager eco = GameEconomyManager.Instance;
|
||||
if (eco != null && !eco.Unlimited)
|
||||
GUI.Label(new Rect(r.x + 80, r.y + 420, r.width - 160, 40), $"На счету: {eco.FormatMoney(eco.Money)} • До Автосалона: {eco.FormatShort(Mathf.Max(0f, eco.AutosalonGoal - eco.Money))}", GameUI.Small);
|
||||
|
||||
if (GameUI.Btn(new Rect(r.x + r.width * 0.5f - 180, r.yMax - 90, 360, 60), "ОТЛИЧНО!", GameUI.ButtonAccent))
|
||||
Close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6c46266bf79245642b9ae030b4c68645
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6ff65ba155b645f2a1fe611307cc7eca
|
||||
timeCreated: 1790289676
|
||||
@@ -0,0 +1,539 @@
|
||||
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);
|
||||
|
||||
/// <summary>Назначение данных детали из кода (автонастройка и процедурные агрегаты).</summary>
|
||||
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<EnginePart>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Состояние детали 0–100% (для склада и продажи на Куфар).</summary>
|
||||
public float ConditionPercent
|
||||
{
|
||||
get
|
||||
{
|
||||
EnginePart ep = GetComponent<EnginePart>();
|
||||
if (ep != null) return ep.condition;
|
||||
CarWheelCondition wc = GetComponent<CarWheelCondition>();
|
||||
if (wc != null) return wc.IsFlat ? 35f : 90f;
|
||||
CarPartVisuals v = GetComponent<CarPartVisuals>();
|
||||
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<Collider>();
|
||||
if (partCollider != null) installAsTrigger = partCollider.isTrigger;
|
||||
partAnimator = GetComponent<CarPartAnimator>();
|
||||
wheelBolts = GetComponentsInChildren<WheelBolt>(true);
|
||||
|
||||
originalParent = transform.parent;
|
||||
originalLocalPos = transform.localPosition;
|
||||
originalLocalRot = transform.localRotation;
|
||||
originalLocalScale = transform.localScale;
|
||||
|
||||
// Определяем родную сторону модели колеса по его имени или позиции
|
||||
DetectNativeWheelSide();
|
||||
|
||||
VehicleInteraction car = GetComponentInParent<VehicleInteraction>();
|
||||
if (car != null)
|
||||
{
|
||||
foreach (WheelCollider wc in car.GetComponentsInChildren<WheelCollider>(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<Collider>();
|
||||
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<Rigidbody>();
|
||||
if (rb == null) rb = gameObject.AddComponent<Rigidbody>();
|
||||
|
||||
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<EnginePart>();
|
||||
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<EnginePart>();
|
||||
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<EnginePart>();
|
||||
ToolType required = (enginePart != null && enginePart.RequiresWrench) ? ToolType.Wrench : ToolType.Hands;
|
||||
PlayerToolManager toolMgr = interactor.GetComponentInChildren<PlayerToolManager>();
|
||||
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<PlayerHands>();
|
||||
if (hands == null) hands = interactor.GetComponentInParent<PlayerHands>();
|
||||
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<Collider>(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<Renderer>();
|
||||
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<Collider>(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<EnginePart>() != null || installAsTrigger)
|
||||
partCollider.isTrigger = true;
|
||||
}
|
||||
|
||||
// Сначала обновляем радиус WheelCollider (чтобы хорошее колесо вернуло полный радиус!), и только потом включаем его
|
||||
CarWheelCondition cond = GetComponent<CarWheelCondition>();
|
||||
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<CarPartMountZone>();
|
||||
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<CarController>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Возвращает снятую/проданную оригинальную деталь как новую запчасть из магазина
|
||||
/// (лежит на столе выдачи без ржавчины и грязи).
|
||||
/// </summary>
|
||||
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<CarPartVisuals>();
|
||||
if (v != null)
|
||||
{
|
||||
v.SetDamage(0f);
|
||||
v.SetDirt(0f);
|
||||
}
|
||||
|
||||
CarWheelCondition wc = GetComponent<CarWheelCondition>();
|
||||
if (wc != null) wc.ApplyState(CarWheelCondition.TireState.Normal);
|
||||
|
||||
EnginePart ep = GetComponent<EnginePart>();
|
||||
if (ep != null) ep.SetAsNew();
|
||||
|
||||
InitializeAsLoosePart();
|
||||
}
|
||||
|
||||
/// <summary>Убрать деталь со сцены после продажи (оригинал скрывается, чтобы его можно было купить заново).</summary>
|
||||
public void HideAsSold()
|
||||
{
|
||||
currentState = PartState.Dropped;
|
||||
if (rb != null) Destroy(rb);
|
||||
transform.SetParent(null);
|
||||
gameObject.SetActive(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 46199851c79547bc8c4f7ac4a0924fa5
|
||||
timeCreated: 1790289784
|
||||
@@ -0,0 +1,232 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class CarPartMountZone : MonoBehaviour, IInteractable
|
||||
{
|
||||
private CarPart targetPart;
|
||||
private Collider zoneCollider;
|
||||
private MeshRenderer ghostRenderer;
|
||||
private PlayerHands cachedHands;
|
||||
private Transform slotParent;
|
||||
private Vector3 slotLocalPos;
|
||||
private Quaternion slotLocalRot;
|
||||
private Vector3 slotLocalScale;
|
||||
private WheelCollider slotWheelCollider;
|
||||
|
||||
private string slotName;
|
||||
private float mountDuration = 1.2f;
|
||||
private float currentMountProgress = 0f;
|
||||
private bool hasSeparateBolts = false;
|
||||
private CarPartData targetData;
|
||||
private Mesh targetMesh;
|
||||
private bool acceptsByData;
|
||||
|
||||
public CarPartData TargetData => targetData;
|
||||
public CarPart TargetPart => targetPart;
|
||||
public string SlotName => slotName;
|
||||
public Vector3 SlotWorldPosition => slotParent != null ? slotParent.TransformPoint(slotLocalPos) : transform.position;
|
||||
|
||||
public string TargetTitle
|
||||
{
|
||||
get
|
||||
{
|
||||
if (targetPart != null) return targetPart.DisplayName;
|
||||
if (targetData != null) return targetData.partName;
|
||||
return slotName;
|
||||
}
|
||||
}
|
||||
|
||||
public void Initialize(CarPart part)
|
||||
{
|
||||
slotParent = part.transform.parent;
|
||||
slotLocalPos = part.transform.localPosition;
|
||||
slotLocalRot = part.transform.localRotation;
|
||||
slotLocalScale = part.transform.localScale;
|
||||
slotWheelCollider = part.LinkedWheelCollider;
|
||||
slotName = part.gameObject.name;
|
||||
|
||||
targetPart = part;
|
||||
targetData = part.Data;
|
||||
gameObject.layer = part.gameObject.layer;
|
||||
acceptsByData = part.GetComponent<EnginePart>() != null;
|
||||
MeshFilter tmf = part.GetComponentInChildren<MeshFilter>(true);
|
||||
targetMesh = tmf != null ? tmf.sharedMesh : null;
|
||||
|
||||
cachedHands = FindAnyObjectByType<PlayerHands>();
|
||||
hasSeparateBolts = part.GetComponentsInChildren<WheelBolt>(true).Length > 0;
|
||||
|
||||
if (part.Data != null && part.Data.boltDuration > 0f)
|
||||
mountDuration = part.Data.boltDuration;
|
||||
|
||||
MeshFilter sourceFilter = part.GetComponentInChildren<MeshFilter>();
|
||||
|
||||
// Для колеса создаем удобную широкую сферу вокруг ступицы, чтобы луч всегда попадал с первого раза
|
||||
if (hasSeparateBolts)
|
||||
{
|
||||
SphereCollider sphere = gameObject.AddComponent<SphereCollider>();
|
||||
if (sourceFilter != null && sourceFilter.sharedMesh != null)
|
||||
sphere.center = sourceFilter.sharedMesh.bounds.center;
|
||||
sphere.radius = 0.48f;
|
||||
sphere.isTrigger = true;
|
||||
zoneCollider = sphere;
|
||||
}
|
||||
else
|
||||
{
|
||||
Collider sourceCollider = part.GetComponent<Collider>();
|
||||
if (sourceCollider is BoxCollider sourceBox)
|
||||
{
|
||||
BoxCollider box = gameObject.AddComponent<BoxCollider>();
|
||||
box.center = sourceBox.center;
|
||||
box.size = sourceBox.size;
|
||||
box.isTrigger = true;
|
||||
zoneCollider = box;
|
||||
}
|
||||
else if (sourceCollider is MeshCollider sourceMesh)
|
||||
{
|
||||
MeshCollider meshCol = gameObject.AddComponent<MeshCollider>();
|
||||
meshCol.sharedMesh = sourceMesh.sharedMesh;
|
||||
meshCol.convex = true;
|
||||
meshCol.isTrigger = true;
|
||||
zoneCollider = meshCol;
|
||||
}
|
||||
else
|
||||
{
|
||||
SphereCollider sphere = gameObject.AddComponent<SphereCollider>();
|
||||
sphere.radius = 0.6f;
|
||||
sphere.isTrigger = true;
|
||||
zoneCollider = sphere;
|
||||
}
|
||||
}
|
||||
|
||||
if (sourceFilter != null && sourceFilter.sharedMesh != null)
|
||||
{
|
||||
MeshFilter mf = gameObject.AddComponent<MeshFilter>();
|
||||
mf.sharedMesh = sourceFilter.sharedMesh;
|
||||
|
||||
ghostRenderer = gameObject.AddComponent<MeshRenderer>();
|
||||
ghostRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
||||
|
||||
Material sharedGhostMat = part.Data != null ? part.Data.ghostMaterial : null;
|
||||
if (sharedGhostMat != null)
|
||||
{
|
||||
ghostRenderer.sharedMaterial = sharedGhostMat;
|
||||
}
|
||||
else
|
||||
{
|
||||
Material fallbackMat = new Material(Shader.Find("Universal Render Pipeline/Unlit"));
|
||||
fallbackMat.color = new Color(0.2f, 0.9f, 0.3f, 0.4f);
|
||||
ghostRenderer.material = fallbackMat;
|
||||
}
|
||||
}
|
||||
|
||||
UpdateZoneVisibility();
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
UpdateZoneVisibility();
|
||||
}
|
||||
|
||||
private void UpdateZoneVisibility()
|
||||
{
|
||||
if (cachedHands == null)
|
||||
cachedHands = FindAnyObjectByType<PlayerHands>();
|
||||
|
||||
bool isHoldingTarget = IsHoldingCompatiblePart();
|
||||
|
||||
if (zoneCollider != null && zoneCollider.enabled != isHoldingTarget)
|
||||
zoneCollider.enabled = isHoldingTarget;
|
||||
|
||||
if (ghostRenderer != null && ghostRenderer.enabled != isHoldingTarget)
|
||||
ghostRenderer.enabled = isHoldingTarget;
|
||||
|
||||
if (!isHoldingTarget)
|
||||
currentMountProgress = 0f;
|
||||
}
|
||||
|
||||
public string GetPrompt()
|
||||
{
|
||||
if (cachedHands == null || !IsHoldingCompatiblePart())
|
||||
return string.Empty;
|
||||
|
||||
string partTitle = TargetTitle;
|
||||
|
||||
// Колесо надевается на ступицу сразу при нажатии E или ЛКМ
|
||||
if (hasSeparateBolts)
|
||||
{
|
||||
if (Input.GetKeyDown(KeyCode.E) || Input.GetMouseButtonDown(0))
|
||||
{
|
||||
CompleteInstall();
|
||||
return string.Empty;
|
||||
}
|
||||
return $"[E / ЛКМ] Надеть {partTitle} на ступицу";
|
||||
}
|
||||
|
||||
if (Input.GetKey(KeyCode.E))
|
||||
{
|
||||
currentMountProgress += Time.deltaTime;
|
||||
if (currentMountProgress >= mountDuration)
|
||||
{
|
||||
CompleteInstall();
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
int percent = Mathf.RoundToInt(Mathf.Clamp01(currentMountProgress / mountDuration) * 100f);
|
||||
return $"Закручиваем болты: {partTitle}... {percent}%";
|
||||
}
|
||||
else
|
||||
{
|
||||
currentMountProgress = 0f;
|
||||
}
|
||||
|
||||
return $"[Удерживать E] Установить {partTitle}";
|
||||
}
|
||||
|
||||
public void Interact(GameObject interactor)
|
||||
{
|
||||
if (hasSeparateBolts && cachedHands != null && IsHoldingCompatiblePart())
|
||||
{
|
||||
CompleteInstall();
|
||||
}
|
||||
}
|
||||
|
||||
private void CompleteInstall()
|
||||
{
|
||||
if (cachedHands == null || !IsHoldingCompatiblePart()) return;
|
||||
|
||||
CarPart partToInstall = cachedHands.CurrentPart;
|
||||
cachedHands.ClearHandAfterInstall();
|
||||
|
||||
partToInstall.InstallIntoZone(
|
||||
slotParent,
|
||||
slotLocalPos,
|
||||
slotLocalRot,
|
||||
slotLocalScale,
|
||||
slotWheelCollider,
|
||||
slotName
|
||||
);
|
||||
|
||||
Destroy(gameObject);
|
||||
}
|
||||
|
||||
private bool IsHoldingCompatiblePart()
|
||||
{
|
||||
if (cachedHands == null || !cachedHands.IsHolding || cachedHands.CurrentPart == null)
|
||||
return false;
|
||||
|
||||
CarPart held = cachedHands.CurrentPart;
|
||||
if (held == targetPart) return true;
|
||||
|
||||
// Разрешаем установить любое колесо-дубликат или новый агрегат (АКБ, свечи, фильтры) с тем же CarPartData
|
||||
if ((hasSeparateBolts || acceptsByData) && held.Data != null && held.Data == targetData)
|
||||
return true;
|
||||
|
||||
// Кузовная деталь-дубликат той же модели (совпадает меш)
|
||||
if (targetMesh != null && held.Data != null && held.Data == targetData)
|
||||
{
|
||||
MeshFilter hmf = held.GetComponentInChildren<MeshFilter>(true);
|
||||
if (hmf != null && hmf.sharedMesh == targetMesh) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6974db776d91487fa81d470aa4b97359
|
||||
timeCreated: 1790290230
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d1396ff771764dc2bcb7e90faac08815
|
||||
timeCreated: 1791809673
|
||||
@@ -0,0 +1,19 @@
|
||||
using UnityEngine;
|
||||
|
||||
[CreateAssetMenu(fileName = "NewCarPart", menuName = "Car System/Part Data")]
|
||||
public class CarPartData : ScriptableObject
|
||||
{
|
||||
[Header("Данные детали")]
|
||||
public string partName = "Передний бампер";
|
||||
public float basePrice = 150f;
|
||||
[Range(0, 100)] public float condition = 100f;
|
||||
|
||||
[Header("Коррозия и материалы")]
|
||||
public bool canRust = true;
|
||||
|
||||
[Header("Монтаж и визуализация")]
|
||||
[Tooltip("Полупрозрачный материал для подсветки пустого места на кузове")]
|
||||
public Material ghostMaterial;
|
||||
[Tooltip("Время на откручивание/закручивание болтов (сек)")]
|
||||
public float boltDuration = 1.2f;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0cd31d9fac3d42f78a28531811779ce9
|
||||
timeCreated: 1790289694
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 631bb0dbce1e4eff852b0101516439ac
|
||||
timeCreated: 1789942959
|
||||
@@ -0,0 +1,377 @@
|
||||
using UnityEngine;
|
||||
|
||||
public enum DriveType { FWD, RWD, AWD }
|
||||
|
||||
[RequireComponent(typeof(Rigidbody))]
|
||||
public class CarController : MonoBehaviour
|
||||
{
|
||||
public float SpeedKmH => rb != null ? rb.linearVelocity.magnitude * 3.6f : 0f;
|
||||
|
||||
[Header("Аркадные настройки движения")]
|
||||
public DriveType driveType = DriveType.AWD;
|
||||
[SerializeField] private float motorForce = 2200f;
|
||||
[SerializeField] private float maxSpeedKmH = 160f;
|
||||
[SerializeField] private float brakeForce = 4500f;
|
||||
|
||||
[Header("Рулевое управление")]
|
||||
[SerializeField] private float maxSteerAngle = 32f;
|
||||
[SerializeField] private float steerSpeed = 8f;
|
||||
[Tooltip("Во сколько раз уменьшается выворот руля на максимальной скорости")]
|
||||
[SerializeField] private float highSpeedSteerFactor = 0.35f;
|
||||
|
||||
[Header("Устойчивость и Дрифт")]
|
||||
[SerializeField] private Vector3 centerOfMassOffset = new Vector3(0f, -0.45f, 0f);
|
||||
[SerializeField] private float antiRollForce = 8000f;
|
||||
[SerializeField] private float normalGrip = 2.2f;
|
||||
[SerializeField] private float handbrakeRearGrip = 0.65f;
|
||||
|
||||
[Header("Wheel Colliders")]
|
||||
[SerializeField] private WheelCollider frontLeftCollider;
|
||||
[SerializeField] private WheelCollider frontRightCollider;
|
||||
[SerializeField] private WheelCollider rearLeftCollider;
|
||||
[SerializeField] private WheelCollider rearRightCollider;
|
||||
|
||||
[Header("Wheel Meshes")]
|
||||
[SerializeField] private Transform frontLeftMesh;
|
||||
[SerializeField] private Transform frontRightMesh;
|
||||
[SerializeField] private Transform rearLeftMesh;
|
||||
[SerializeField] private Transform rearRightMesh;
|
||||
|
||||
private Rigidbody rb;
|
||||
private EngineBayManager engineBay;
|
||||
private AudioSource engineAudio;
|
||||
private bool hasDriver;
|
||||
private bool engineRunning;
|
||||
private float startCooldown;
|
||||
private float misfireTimer;
|
||||
|
||||
/// <summary>Двигатель заведен (без исправного АКБ и свечей не заводится).</summary>
|
||||
public bool EngineRunning => engineRunning;
|
||||
/// <summary>Сообщение на приборной панели (например, «Двигатель не заводится!»).</summary>
|
||||
public string DashboardMessage { get; private set; }
|
||||
public float DashboardMessageTimer { get; private set; }
|
||||
public EngineBayManager EngineBay => engineBay;
|
||||
public float MaxSpeedKmH => maxSpeedKmH;
|
||||
|
||||
private float inputVertical;
|
||||
private float inputHorizontal;
|
||||
private bool inputHandbrake = true; // Припаркованная машина стоит на ручнике
|
||||
private float currentSteerAngle;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
rb = GetComponent<Rigidbody>();
|
||||
rb.centerOfMass = centerOfMassOffset;
|
||||
rb.angularDamping = 1.5f;
|
||||
rb.interpolation = RigidbodyInterpolation.Interpolate;
|
||||
engineBay = GetComponent<EngineBayManager>();
|
||||
|
||||
SetupArcadeWheel(frontLeftCollider);
|
||||
SetupArcadeWheel(frontRightCollider);
|
||||
SetupArcadeWheel(rearLeftCollider);
|
||||
SetupArcadeWheel(rearRightCollider);
|
||||
}
|
||||
|
||||
private void SetupArcadeWheel(WheelCollider wc)
|
||||
{
|
||||
if (wc == null) return;
|
||||
|
||||
JointSpring spring = wc.suspensionSpring;
|
||||
spring.spring = 35000f;
|
||||
spring.damper = 4500f;
|
||||
spring.targetPosition = 0.5f;
|
||||
wc.suspensionSpring = spring;
|
||||
wc.suspensionDistance = 0.18f;
|
||||
|
||||
WheelFrictionCurve fwd = wc.forwardFriction;
|
||||
fwd.stiffness = 2.0f;
|
||||
wc.forwardFriction = fwd;
|
||||
|
||||
WheelFrictionCurve side = wc.sidewaysFriction;
|
||||
side.stiffness = normalGrip;
|
||||
wc.sidewaysFriction = side;
|
||||
}
|
||||
|
||||
public void ProcessInput(float vertical, float horizontal, bool handbrake)
|
||||
{
|
||||
inputVertical = vertical;
|
||||
inputHorizontal = horizontal;
|
||||
inputHandbrake = handbrake;
|
||||
|
||||
if (hasDriver && !engineRunning && Mathf.Abs(vertical) > 0.1f && startCooldown <= 0f)
|
||||
TryStartEngine();
|
||||
}
|
||||
|
||||
/// <summary>Водитель сел/вышел. При выходе двигатель глушится.</summary>
|
||||
public void SetDriver(bool present)
|
||||
{
|
||||
hasDriver = present;
|
||||
if (!present)
|
||||
{
|
||||
StopEngine();
|
||||
ProcessInput(0f, 0f, true);
|
||||
}
|
||||
}
|
||||
|
||||
public void TryStartEngine()
|
||||
{
|
||||
startCooldown = 1.6f;
|
||||
string reason = string.Empty;
|
||||
bool ok = engineBay == null || engineBay.TryStart(out reason);
|
||||
|
||||
if (ok)
|
||||
{
|
||||
engineRunning = true;
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.Starter, transform.position, 0.9f);
|
||||
ShowDashboardMessage("Двигатель запущен", 1.5f);
|
||||
}
|
||||
else
|
||||
{
|
||||
engineRunning = false;
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.RelayClick, transform.position, 1f);
|
||||
ShowDashboardMessage(reason, 4f);
|
||||
}
|
||||
}
|
||||
|
||||
public void StopEngine()
|
||||
{
|
||||
engineRunning = false;
|
||||
if (engineBay != null) engineBay.StopEngine();
|
||||
}
|
||||
|
||||
public void ShowDashboardMessage(string msg, float seconds)
|
||||
{
|
||||
DashboardMessage = msg;
|
||||
DashboardMessageTimer = seconds;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (startCooldown > 0f) startCooldown -= Time.deltaTime;
|
||||
if (DashboardMessageTimer > 0f) DashboardMessageTimer -= Time.deltaTime;
|
||||
|
||||
if (engineBay != null && engineRunning && !engineBay.EngineRunning)
|
||||
{
|
||||
engineRunning = false; // Двигатель заглох (например, сел аккумулятор)
|
||||
ShowDashboardMessage("Двигатель заглох!", 3f);
|
||||
}
|
||||
|
||||
UpdateEngineAudio();
|
||||
}
|
||||
|
||||
private void UpdateEngineAudio()
|
||||
{
|
||||
if (engineAudio == null)
|
||||
{
|
||||
ProceduralAudioManager pam = ProceduralAudioManager.Instance;
|
||||
if (pam == null) return;
|
||||
engineAudio = pam.CreateEngineSource(transform);
|
||||
}
|
||||
|
||||
float sfx = ProceduralAudioManager.Instance != null ? ProceduralAudioManager.Instance.sfxVolume : 0.8f;
|
||||
if (!engineRunning)
|
||||
{
|
||||
engineAudio.volume = Mathf.MoveTowards(engineAudio.volume, 0f, Time.deltaTime * 2f);
|
||||
if (engineAudio.volume <= 0.001f && engineAudio.isPlaying) engineAudio.Stop();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!engineAudio.isPlaying) engineAudio.Play();
|
||||
float load = Mathf.Clamp01(Mathf.Abs(inputVertical));
|
||||
float speed01 = Mathf.Clamp01(SpeedKmH / Mathf.Max(maxSpeedKmH, 1f));
|
||||
float pitch = 0.75f + speed01 * 1.5f + load * 0.15f;
|
||||
float vol = (0.35f + load * 0.35f) * sfx;
|
||||
|
||||
// Пропуски зажигания: мотор «троит» и проседает по громкости
|
||||
if (engineBay != null && (engineBay.IsMisfiring || engineBay.OilKnocking))
|
||||
{
|
||||
misfireTimer -= Time.deltaTime;
|
||||
if (misfireTimer <= 0f)
|
||||
{
|
||||
misfireTimer = Random.Range(0.08f, 0.35f);
|
||||
vol *= Random.Range(0.2f, 0.6f);
|
||||
}
|
||||
}
|
||||
|
||||
engineAudio.pitch = Mathf.Lerp(engineAudio.pitch, pitch, Time.deltaTime * 6f);
|
||||
engineAudio.volume = Mathf.Lerp(engineAudio.volume, vol, Time.deltaTime * 8f);
|
||||
}
|
||||
|
||||
private void FixedUpdate()
|
||||
{
|
||||
HandleSteering();
|
||||
HandleMotorAndBrakes();
|
||||
ApplyAntiRoll(frontLeftCollider, frontRightCollider);
|
||||
ApplyAntiRoll(rearLeftCollider, rearRightCollider);
|
||||
UpdateWheelPoses();
|
||||
}
|
||||
|
||||
private void HandleSteering()
|
||||
{
|
||||
float speedFactor = Mathf.Lerp(1f, highSpeedSteerFactor, SpeedKmH / maxSpeedKmH);
|
||||
float targetSteer = inputHorizontal * maxSteerAngle * speedFactor;
|
||||
currentSteerAngle = Mathf.Lerp(currentSteerAngle, targetSteer, Time.fixedDeltaTime * steerSpeed);
|
||||
|
||||
if (frontLeftCollider != null) frontLeftCollider.steerAngle = currentSteerAngle;
|
||||
if (frontRightCollider != null) frontRightCollider.steerAngle = currentSteerAngle;
|
||||
}
|
||||
|
||||
private void HandleMotorAndBrakes()
|
||||
{
|
||||
float localVelZ = transform.InverseTransformDirection(rb.linearVelocity).z;
|
||||
float motor = 0f;
|
||||
float brake = 0f;
|
||||
|
||||
// Связь физики с техсостоянием: мощность и тормоза зависят от агрегатов и жидкостей под капотом
|
||||
float powerMul = engineBay != null ? engineBay.PowerMultiplier : 1f;
|
||||
float brakeMul = engineBay != null ? engineBay.BrakeMultiplier : 1f;
|
||||
float speedLimit = engineBay != null ? Mathf.Min(maxSpeedKmH, engineBay.MaxSpeedLimit) : maxSpeedKmH;
|
||||
float effectiveMotor = engineRunning ? motorForce * powerMul : 0f;
|
||||
float effectiveBrake = brakeForce * brakeMul;
|
||||
|
||||
if (inputVertical > 0.01f)
|
||||
{
|
||||
if (localVelZ < -1.5f)
|
||||
brake = effectiveBrake;
|
||||
else if (SpeedKmH < speedLimit)
|
||||
motor = inputVertical * effectiveMotor;
|
||||
}
|
||||
else if (inputVertical < -0.01f)
|
||||
{
|
||||
if (localVelZ > 1.5f)
|
||||
brake = effectiveBrake;
|
||||
else if (SpeedKmH < 45f)
|
||||
motor = inputVertical * effectiveMotor * 0.7f;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Плавное торможение двигателем, когда газ отпущен
|
||||
brake = 150f;
|
||||
}
|
||||
|
||||
if (inputHandbrake)
|
||||
{
|
||||
motor = 0f;
|
||||
brake = effectiveBrake * 1.5f;
|
||||
}
|
||||
|
||||
ApplyDriveTorque(motor);
|
||||
ApplyBrakesAndDrift(brake, inputHandbrake);
|
||||
}
|
||||
|
||||
private void ApplyDriveTorque(float torque)
|
||||
{
|
||||
if (driveType == DriveType.FWD)
|
||||
{
|
||||
SetMotor(frontLeftCollider, torque);
|
||||
SetMotor(frontRightCollider, torque);
|
||||
SetMotor(rearLeftCollider, 0f);
|
||||
SetMotor(rearRightCollider, 0f);
|
||||
}
|
||||
else if (driveType == DriveType.RWD)
|
||||
{
|
||||
SetMotor(frontLeftCollider, 0f);
|
||||
SetMotor(frontRightCollider, 0f);
|
||||
SetMotor(rearLeftCollider, torque);
|
||||
SetMotor(rearRightCollider, torque);
|
||||
}
|
||||
else
|
||||
{
|
||||
float half = torque * 0.55f;
|
||||
SetMotor(frontLeftCollider, half);
|
||||
SetMotor(frontRightCollider, half);
|
||||
SetMotor(rearLeftCollider, half);
|
||||
SetMotor(rearRightCollider, half);
|
||||
}
|
||||
}
|
||||
|
||||
private void SetMotor(WheelCollider wc, float val)
|
||||
{
|
||||
if (wc != null && wc.enabled) wc.motorTorque = val;
|
||||
}
|
||||
|
||||
private void ApplyBrakesAndDrift(float brake, bool handbrake)
|
||||
{
|
||||
float targetRearStiffness = handbrake ? handbrakeRearGrip : normalGrip;
|
||||
|
||||
SetRearGrip(rearLeftCollider, targetRearStiffness);
|
||||
SetRearGrip(rearRightCollider, targetRearStiffness);
|
||||
|
||||
if (handbrake)
|
||||
{
|
||||
if (frontLeftCollider != null) frontLeftCollider.brakeTorque = 0f;
|
||||
if (frontRightCollider != null) frontRightCollider.brakeTorque = 0f;
|
||||
if (rearLeftCollider != null) rearLeftCollider.brakeTorque = brake;
|
||||
if (rearRightCollider != null) rearRightCollider.brakeTorque = brake;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (frontLeftCollider != null) frontLeftCollider.brakeTorque = brake;
|
||||
if (frontRightCollider != null) frontRightCollider.brakeTorque = brake;
|
||||
if (rearLeftCollider != null) rearLeftCollider.brakeTorque = brake * 0.6f;
|
||||
if (rearRightCollider != null) rearRightCollider.brakeTorque = brake * 0.6f;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetRearGrip(WheelCollider wc, float targetStiff)
|
||||
{
|
||||
if (wc == null) return;
|
||||
WheelFrictionCurve side = wc.sidewaysFriction;
|
||||
side.stiffness = Mathf.Lerp(side.stiffness, targetStiff, Time.fixedDeltaTime * 10f);
|
||||
wc.sidewaysFriction = side;
|
||||
}
|
||||
|
||||
private void ApplyAntiRoll(WheelCollider left, WheelCollider right)
|
||||
{
|
||||
if (left == null || right == null || !left.enabled || !right.enabled) return;
|
||||
|
||||
float travelL = 1f;
|
||||
float travelR = 1f;
|
||||
|
||||
bool groundedL = left.GetGroundHit(out WheelHit hitL);
|
||||
if (groundedL)
|
||||
travelL = (-left.transform.InverseTransformPoint(hitL.point).y - left.radius) / left.suspensionDistance;
|
||||
|
||||
bool groundedR = right.GetGroundHit(out WheelHit hitR);
|
||||
if (groundedR)
|
||||
travelR = (-right.transform.InverseTransformPoint(hitR.point).y - right.radius) / right.suspensionDistance;
|
||||
|
||||
float force = (travelL - travelR) * antiRollForce;
|
||||
|
||||
if (groundedL) rb.AddForceAtPosition(left.transform.up * -force, left.transform.position);
|
||||
if (groundedR) rb.AddForceAtPosition(right.transform.up * force, right.transform.position);
|
||||
}
|
||||
|
||||
private void UpdateWheelPoses()
|
||||
{
|
||||
UpdateWheelPose(frontLeftCollider, frontLeftMesh);
|
||||
UpdateWheelPose(frontRightCollider, frontRightMesh);
|
||||
UpdateWheelPose(rearLeftCollider, rearLeftMesh);
|
||||
UpdateWheelPose(rearRightCollider, rearRightMesh);
|
||||
}
|
||||
|
||||
private void UpdateWheelPose(WheelCollider collider, Transform mesh)
|
||||
{
|
||||
if (mesh == null || collider == null || !collider.enabled || !mesh.IsChildOf(transform))
|
||||
return;
|
||||
|
||||
collider.GetWorldPose(out Vector3 pos, out Quaternion rot);
|
||||
mesh.position = pos;
|
||||
|
||||
// Если на эту ступицу поставили запасное колесо с противоположной стороны машины (развернутое на 180°),
|
||||
// сохраняем его разворот при вращении колеса!
|
||||
float angleDiff = Quaternion.Angle(mesh.localRotation, Quaternion.Euler(0f, 180f, 0f));
|
||||
if (angleDiff < 60f)
|
||||
mesh.rotation = rot * Quaternion.Euler(0f, 180f, 0f);
|
||||
else
|
||||
mesh.rotation = rot;
|
||||
}
|
||||
|
||||
public void ReplaceWheelMesh(WheelCollider col, Transform newMesh)
|
||||
{
|
||||
if (col == frontLeftCollider) frontLeftMesh = newMesh;
|
||||
else if (col == frontRightCollider) frontRightMesh = newMesh;
|
||||
else if (col == rearLeftCollider) rearLeftMesh = newMesh;
|
||||
else if (col == rearRightCollider) rearRightMesh = newMesh;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 100e57e4683949049302153c3df8055c
|
||||
timeCreated: 1789819686
|
||||
@@ -0,0 +1,43 @@
|
||||
using UnityEngine;
|
||||
|
||||
[ExecuteInEditMode()]
|
||||
public class EasySuspension : MonoBehaviour
|
||||
{
|
||||
[Range(0, 20)] public float naturalFrequency = 10;
|
||||
[Range(0, 3)] public float dampingRatio = 0.8f;
|
||||
[Range(-1, 1)] public float forceShift = 0.03f;
|
||||
public bool setSuspensionDistance = true;
|
||||
|
||||
private float playModeTimer = 0f;
|
||||
|
||||
void Update()
|
||||
{
|
||||
// В режиме игры настраиваем подвеску только первые 0.25 сек при спавне авто.
|
||||
// Постоянный пересчет в каждом кадре вызывает вибрацию машины при спущенных шинах и на домкрате!
|
||||
if (Application.isPlaying)
|
||||
{
|
||||
if (playModeTimer > 0.25f) return;
|
||||
playModeTimer += Time.deltaTime;
|
||||
}
|
||||
|
||||
Rigidbody rb = GetComponent<Rigidbody>();
|
||||
if (rb == null) return;
|
||||
|
||||
foreach (WheelCollider wc in GetComponentsInChildren<WheelCollider>())
|
||||
{
|
||||
if (!wc.enabled || wc.sprungMass <= 0.001f) continue;
|
||||
|
||||
JointSpring spring = wc.suspensionSpring;
|
||||
spring.spring = Mathf.Pow(Mathf.Sqrt(wc.sprungMass) * naturalFrequency, 2);
|
||||
spring.damper = 2 * dampingRatio * Mathf.Sqrt(spring.spring * wc.sprungMass);
|
||||
wc.suspensionSpring = spring;
|
||||
|
||||
Vector3 wheelRelativeBody = transform.InverseTransformPoint(wc.transform.position);
|
||||
float distance = rb.centerOfMass.y - wheelRelativeBody.y + wc.radius;
|
||||
wc.forceAppPointDistance = distance - forceShift;
|
||||
|
||||
if (spring.targetPosition > 0 && spring.spring > 0.001f && setSuspensionDistance)
|
||||
wc.suspensionDistance = wc.sprungMass * Physics.gravity.magnitude / (spring.targetPosition * spring.spring);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7a530288782d44949a514cf418363121
|
||||
timeCreated: 1792619015
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 08c6a62f23462f0449bef85c16244a9d
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,68 @@
|
||||
using UnityEngine;
|
||||
|
||||
[DisallowMultipleComponent]
|
||||
public class CarFluidCap : MonoBehaviour, IInteractable
|
||||
{
|
||||
private CarFluids ownerFluids;
|
||||
private CarFluids.FluidReservoir reservoir;
|
||||
private bool isOpen = false;
|
||||
|
||||
private Vector3 closedLocalPos;
|
||||
private Quaternion closedLocalRot;
|
||||
private Vector3 openLocalPos;
|
||||
private Quaternion openLocalRot;
|
||||
|
||||
public bool IsOpen => isOpen;
|
||||
public CarFluids.FluidReservoir Reservoir => reservoir;
|
||||
public CarFluids Owner => ownerFluids;
|
||||
|
||||
public void Initialize(CarFluids owner, CarFluids.FluidReservoir res)
|
||||
{
|
||||
ownerFluids = owner;
|
||||
reservoir = res;
|
||||
|
||||
closedLocalPos = transform.localPosition;
|
||||
closedLocalRot = transform.localRotation;
|
||||
|
||||
// При открытии крышка приподнимается и сдвигается в сторону
|
||||
openLocalPos = closedLocalPos + new Vector3(0.08f, 0.09f, -0.04f);
|
||||
openLocalRot = closedLocalRot * Quaternion.Euler(0f, 180f, 35f);
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
Vector3 targetPos = isOpen ? openLocalPos : closedLocalPos;
|
||||
Quaternion targetRot = isOpen ? openLocalRot : closedLocalRot;
|
||||
|
||||
transform.localPosition = Vector3.Lerp(transform.localPosition, targetPos, Time.deltaTime * 12f);
|
||||
transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRot, Time.deltaTime * 12f);
|
||||
}
|
||||
|
||||
public string GetPrompt()
|
||||
{
|
||||
if (reservoir == null) return "Крышка бачка (E)";
|
||||
|
||||
int percent = Mathf.RoundToInt(reservoir.FillPercent * 100f);
|
||||
string status = reservoir.IsFull ? "Полный (100%)" : $"{reservoir.currentLiters:F1}/{reservoir.maxLiters:F1} л ({percent}%)";
|
||||
string quality = reservoir.fluidType == FluidType.WasherFluid
|
||||
? string.Empty
|
||||
: $" | Состояние: {Mathf.RoundToInt(reservoir.quality * 100f)}% ({reservoir.QualityText})";
|
||||
|
||||
if (isOpen)
|
||||
{
|
||||
return $"[E] Закрутить крышку ({reservoir.title})\nУровень: {status}{quality}";
|
||||
}
|
||||
|
||||
return $"[E] Открыть крышку ({reservoir.title})\nУровень: {status}{quality}";
|
||||
}
|
||||
|
||||
public void Interact(GameObject interactor)
|
||||
{
|
||||
isOpen = !isOpen;
|
||||
}
|
||||
|
||||
public void SetOpen(bool open)
|
||||
{
|
||||
isOpen = open;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e1f498fd0cb567b49947867db0b18489
|
||||
@@ -0,0 +1,209 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
public enum FluidType
|
||||
{
|
||||
EngineOil,
|
||||
Coolant,
|
||||
WasherFluid,
|
||||
BrakeFluid
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Технические жидкости автомобиля: уровень (литры) и состояние/чистота (0–1) для
|
||||
/// моторного масла, антифриза, тормозной жидкости и омывайки. Крышки бачков находятся автоматически по именам.
|
||||
/// </summary>
|
||||
[DisallowMultipleComponent]
|
||||
public class CarFluids : MonoBehaviour
|
||||
{
|
||||
[Serializable]
|
||||
public class FluidReservoir
|
||||
{
|
||||
public string title = "Моторное масло";
|
||||
public FluidType fluidType = FluidType.EngineOil;
|
||||
public float maxLiters = 4.0f;
|
||||
[Range(0f, 10f)] public float currentLiters = 3.8f;
|
||||
[Tooltip("Состояние жидкости: 1 = свежая, 0 = черная отработка")]
|
||||
[Range(0f, 1f)] public float quality = 1f;
|
||||
public Color fluidColor = new Color(0.85f, 0.65f, 0.15f, 0.9f);
|
||||
public CarFluidCap cap;
|
||||
|
||||
public float FillPercent => Mathf.Clamp01(currentLiters / Mathf.Max(maxLiters, 0.01f));
|
||||
public bool IsFull => currentLiters >= maxLiters - 0.05f;
|
||||
public bool IsGood => FillPercent >= 0.85f && quality >= 0.85f;
|
||||
|
||||
public string QualityText
|
||||
{
|
||||
get
|
||||
{
|
||||
if (fluidType == FluidType.WasherFluid) return "в норме";
|
||||
if (quality >= 0.85f) return "свежая";
|
||||
if (quality >= 0.5f) return "темная, скоро замена";
|
||||
if (quality >= 0.25f) return "грязная — требуется замена";
|
||||
return fluidType == FluidType.EngineOil ? "черная отработка — требуется замена" : "старая, требуется замена";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Header("Бачки и жидкости авто")]
|
||||
[SerializeField] private FluidReservoir engineOil = new FluidReservoir
|
||||
{
|
||||
title = "Моторное масло (5W-40)",
|
||||
fluidType = FluidType.EngineOil,
|
||||
maxLiters = 4.0f,
|
||||
currentLiters = 3.6f,
|
||||
fluidColor = new Color(0.85f, 0.62f, 0.12f, 0.95f)
|
||||
};
|
||||
|
||||
[SerializeField] private FluidReservoir coolant = new FluidReservoir
|
||||
{
|
||||
title = "Антифриз (G12+)",
|
||||
fluidType = FluidType.Coolant,
|
||||
maxLiters = 6.0f,
|
||||
currentLiters = 5.5f,
|
||||
fluidColor = new Color(0.95f, 0.20f, 0.35f, 0.95f)
|
||||
};
|
||||
|
||||
[SerializeField] private FluidReservoir washerFluid = new FluidReservoir
|
||||
{
|
||||
title = "Омывайка (-25°C)",
|
||||
fluidType = FluidType.WasherFluid,
|
||||
maxLiters = 3.5f,
|
||||
currentLiters = 3.2f,
|
||||
fluidColor = new Color(0.15f, 0.65f, 1.0f, 0.95f)
|
||||
};
|
||||
|
||||
[SerializeField] private FluidReservoir brakeFluid = new FluidReservoir
|
||||
{
|
||||
title = "Тормозная жидкость (DOT-4)",
|
||||
fluidType = FluidType.BrakeFluid,
|
||||
maxLiters = 1.0f,
|
||||
currentLiters = 0.9f,
|
||||
fluidColor = new Color(0.95f, 0.92f, 0.75f, 0.95f)
|
||||
};
|
||||
|
||||
public FluidReservoir EngineOil => engineOil;
|
||||
public FluidReservoir Coolant => coolant;
|
||||
public FluidReservoir WasherFluid => washerFluid;
|
||||
public FluidReservoir BrakeFluid => brakeFluid;
|
||||
|
||||
public FluidReservoir[] All => new[] { engineOil, coolant, brakeFluid, washerFluid };
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
EnsureBrakeFluidDefaults();
|
||||
InitializeCaps();
|
||||
}
|
||||
|
||||
private void EnsureBrakeFluidDefaults()
|
||||
{
|
||||
if (brakeFluid == null)
|
||||
brakeFluid = new FluidReservoir();
|
||||
if (string.IsNullOrEmpty(brakeFluid.title) || brakeFluid.fluidType != FluidType.BrakeFluid)
|
||||
{
|
||||
brakeFluid.title = "Тормозная жидкость (DOT-4)";
|
||||
brakeFluid.fluidType = FluidType.BrakeFluid;
|
||||
brakeFluid.maxLiters = 1.0f;
|
||||
brakeFluid.currentLiters = Mathf.Clamp(brakeFluid.currentLiters, 0f, 1f);
|
||||
brakeFluid.fluidColor = new Color(0.95f, 0.92f, 0.75f, 0.95f);
|
||||
}
|
||||
}
|
||||
|
||||
public void InitializeCaps()
|
||||
{
|
||||
// Автоматически находим крышки под капотом, если они еще не привязаны
|
||||
Transform[] allChildren = GetComponentsInChildren<Transform>(true);
|
||||
foreach (var t in allChildren)
|
||||
{
|
||||
string n = t.name.ToLowerInvariant().Replace(" ", "");
|
||||
if (n.Contains("oilcap") && engineOil.cap == null)
|
||||
engineOil.cap = SetupCap(t.gameObject, engineOil);
|
||||
else if ((n.Contains("coolantcap") || n.Contains("radcap") || n.Contains("radiatorcap")) && coolant.cap == null)
|
||||
coolant.cap = SetupCap(t.gameObject, coolant);
|
||||
else if ((n.Contains("washerfluidcap") || n.Contains("washercap")) && washerFluid.cap == null)
|
||||
washerFluid.cap = SetupCap(t.gameObject, washerFluid);
|
||||
else if ((n.Contains("brakefluidcap") || n.Contains("brakecap")) && brakeFluid.cap == null)
|
||||
brakeFluid.cap = SetupCap(t.gameObject, brakeFluid);
|
||||
}
|
||||
}
|
||||
|
||||
private CarFluidCap SetupCap(GameObject capObj, FluidReservoir res)
|
||||
{
|
||||
Collider col = capObj.GetComponent<Collider>();
|
||||
if (col == null)
|
||||
{
|
||||
BoxCollider bc = capObj.AddComponent<BoxCollider>();
|
||||
bc.size = new Vector3(0.12f, 0.08f, 0.12f);
|
||||
}
|
||||
|
||||
CarFluidCap capComp = capObj.GetComponent<CarFluidCap>();
|
||||
if (capComp == null) capComp = capObj.AddComponent<CarFluidCap>();
|
||||
|
||||
capComp.Initialize(this, res);
|
||||
return capComp;
|
||||
}
|
||||
|
||||
public FluidReservoir GetReservoir(FluidType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case FluidType.EngineOil: return engineOil;
|
||||
case FluidType.Coolant: return coolant;
|
||||
case FluidType.WasherFluid: return washerFluid;
|
||||
case FluidType.BrakeFluid: return brakeFluid;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Долив жидкости. Свежая жидкость смешивается со старой и улучшает её состояние.</summary>
|
||||
public bool Pour(FluidType type, float litersDelta, float addedQuality = 1f)
|
||||
{
|
||||
FluidReservoir r = GetReservoir(type);
|
||||
if (r == null || r.IsFull || litersDelta <= 0f) return false;
|
||||
|
||||
float before = r.currentLiters;
|
||||
r.currentLiters = Mathf.Min(r.maxLiters, r.currentLiters + litersDelta);
|
||||
float added = r.currentLiters - before;
|
||||
if (r.currentLiters > 0.001f)
|
||||
r.quality = Mathf.Clamp01((r.quality * before + addedQuality * added) / r.currentLiters);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Слив моторного масла через пробку поддона (старая отработка уходит в таз).</summary>
|
||||
public float DrainEngineOil()
|
||||
{
|
||||
float drained = engineOil.currentLiters;
|
||||
engineOil.currentLiters = 0f;
|
||||
engineOil.quality = 1f; // В пустой картер зальется только свежее масло
|
||||
return drained;
|
||||
}
|
||||
|
||||
public void Leak(FluidType type, float liters)
|
||||
{
|
||||
FluidReservoir r = GetReservoir(type);
|
||||
if (r == null) return;
|
||||
r.currentLiters = Mathf.Max(0f, r.currentLiters - liters);
|
||||
}
|
||||
|
||||
public void SetRandomLevels(float minPercent = 0.15f, float maxPercent = 0.55f)
|
||||
{
|
||||
engineOil.currentLiters = engineOil.maxLiters * UnityEngine.Random.Range(minPercent, maxPercent);
|
||||
coolant.currentLiters = coolant.maxLiters * UnityEngine.Random.Range(minPercent, maxPercent);
|
||||
washerFluid.currentLiters = washerFluid.maxLiters * UnityEngine.Random.Range(0f, 0.35f);
|
||||
brakeFluid.currentLiters = brakeFluid.maxLiters * UnityEngine.Random.Range(minPercent, Mathf.Min(1f, maxPercent + 0.2f));
|
||||
|
||||
engineOil.quality = UnityEngine.Random.Range(0.05f, 0.6f);
|
||||
coolant.quality = UnityEngine.Random.Range(0.3f, 0.9f);
|
||||
brakeFluid.quality = UnityEngine.Random.Range(0.3f, 0.9f);
|
||||
washerFluid.quality = 1f;
|
||||
}
|
||||
|
||||
public void FillAllFresh()
|
||||
{
|
||||
foreach (FluidReservoir r in All)
|
||||
{
|
||||
r.currentLiters = r.maxLiters;
|
||||
r.quality = 1f;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0cad3bea5e09c554cab3ba19a48f43e6
|
||||
@@ -0,0 +1,634 @@
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(BoxCollider))]
|
||||
public class CarJack : MonoBehaviour, IInteractable
|
||||
{
|
||||
public enum JackState { OnFloor, InHand, PlacedUnderCar }
|
||||
|
||||
[Header("Детали домкрата (из Blender)")]
|
||||
[SerializeField] private Transform bottomArmL;
|
||||
[SerializeField] private Transform bottomArmR;
|
||||
[SerializeField] private Transform topArmL;
|
||||
[SerializeField] private Transform topArmR;
|
||||
[SerializeField] private Transform screw;
|
||||
[SerializeField] private Transform topPlate;
|
||||
|
||||
[Header("Настройки подъема")]
|
||||
[SerializeField] private float liftDuration = 2.0f;
|
||||
[Tooltip("На сколько метров поднимается порог (0.28 = 28 см, чтобы колесо легко вставало на место)")]
|
||||
[SerializeField] private float carLiftHeight = 0.28f;
|
||||
|
||||
[Header("Позиционирование и материалы")]
|
||||
[SerializeField] private Material ghostMaterial;
|
||||
[SerializeField] private Vector3 inHandOffset = new Vector3(0.25f, -0.25f, 0.65f);
|
||||
[SerializeField] private Vector3 inHandRotation = new Vector3(0f, 90f, 0f);
|
||||
|
||||
[Header("Состояние подъема")]
|
||||
[Range(0f, 1f)] [SerializeField] private float liftProgress = 0f;
|
||||
|
||||
private JackState currentState = JackState.OnFloor;
|
||||
private BoxCollider mainCollider;
|
||||
private Rigidbody jackRb;
|
||||
private Transform holderCamera;
|
||||
private Transform playerRoot;
|
||||
private UIManager uiManager;
|
||||
private int stateChangeFrame = -1;
|
||||
|
||||
private Transform diamondPivot;
|
||||
private Vector3 topPlateInitLocalPos;
|
||||
private Vector3 screwInitLocalPos;
|
||||
private Quaternion screwInitLocalRot;
|
||||
private Vector3 originalRootScale;
|
||||
private float modelFullHeight = 0.32f;
|
||||
|
||||
private MeshRenderer[] renderers;
|
||||
private Material[] originalMaterials;
|
||||
private bool isShowingGhost = false;
|
||||
|
||||
// Физический подъемник на базе ConfigurableJoint (дает 100% плавный подъем без дрожи!)
|
||||
private Rigidbody targetCarRb;
|
||||
private CarPart targetWheelPart;
|
||||
private WheelCollider targetWheelCollider;
|
||||
private GameObject supportAnchorObj;
|
||||
private Rigidbody supportAnchorRb;
|
||||
private ConfigurableJoint liftJoint;
|
||||
private float initialSillWorldY;
|
||||
|
||||
private bool canPlaceUnderCar = false;
|
||||
private Vector3 previewWorldPos;
|
||||
private Quaternion previewWorldRot;
|
||||
private Rigidbody previewCarRb;
|
||||
private CarPart previewWheelPart;
|
||||
private WheelCollider previewWheelCol;
|
||||
|
||||
private bool isHoveredThisFrame = false;
|
||||
|
||||
public static CarJack ActiveJackInHand { get; private set; }
|
||||
public bool IsLifted => currentState == JackState.PlacedUnderCar && liftProgress >= 0.70f;
|
||||
|
||||
public static bool IsWheelLifted(Transform wheelTransform)
|
||||
{
|
||||
if (wheelTransform == null) return false;
|
||||
|
||||
// 1. Проверяем домкраты (дистанция строго < 0.95 м, чтобы левый домкрат не задевал правое колесо!)
|
||||
CarJack[] allJacks = FindObjectsByType<CarJack>(FindObjectsSortMode.None);
|
||||
foreach (CarJack jack in allJacks)
|
||||
{
|
||||
if (!jack.IsLifted) continue;
|
||||
if (jack.targetWheelPart != null && jack.targetWheelPart.transform == wheelTransform)
|
||||
return true;
|
||||
if (Vector3.Distance(jack.transform.position, wheelTransform.position) < 0.95f)
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2. Проверяем кирпичи (тоже строго < 0.95 м)
|
||||
WheelBrickSupport[] allBricks = FindObjectsByType<WheelBrickSupport>(FindObjectsSortMode.None);
|
||||
foreach (var b in allBricks)
|
||||
{
|
||||
if (Vector3.Distance(b.transform.position, wheelTransform.position) < 0.95f)
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
uiManager = FindAnyObjectByType<UIManager>();
|
||||
originalRootScale = transform.localScale;
|
||||
mainCollider = GetComponent<BoxCollider>();
|
||||
|
||||
foreach (var c in GetComponentsInChildren<Collider>(true))
|
||||
if (c != mainCollider) c.enabled = false;
|
||||
|
||||
renderers = GetComponentsInChildren<MeshRenderer>(true);
|
||||
originalMaterials = new Material[renderers.Length];
|
||||
for (int i = 0; i < renderers.Length; i++)
|
||||
originalMaterials[i] = renderers[i].sharedMaterial;
|
||||
|
||||
// Автоматически выравниваем BoxCollider по реальным габаритам модели,
|
||||
// чтобы его дно не торчало ниже подошвы домкрата
|
||||
FitColliderToRenderers();
|
||||
|
||||
SetupUnifiedDiamondRig();
|
||||
UpdateJackPose();
|
||||
}
|
||||
|
||||
private void FitColliderToRenderers()
|
||||
{
|
||||
if (mainCollider == null || renderers == null || renderers.Length == 0) return;
|
||||
|
||||
Quaternion savedRot = transform.rotation;
|
||||
transform.rotation = Quaternion.identity;
|
||||
|
||||
Bounds worldBounds = new Bounds(transform.position, Vector3.zero);
|
||||
bool hasBounds = false;
|
||||
foreach (var r in renderers)
|
||||
{
|
||||
if (r == null) continue;
|
||||
if (!hasBounds) { worldBounds = r.bounds; hasBounds = true; }
|
||||
else worldBounds.Encapsulate(r.bounds);
|
||||
}
|
||||
|
||||
if (hasBounds)
|
||||
{
|
||||
Vector3 localCenter = transform.InverseTransformPoint(worldBounds.center);
|
||||
Vector3 localSize = new Vector3(
|
||||
worldBounds.size.x / Mathf.Max(0.001f, transform.lossyScale.x),
|
||||
worldBounds.size.y / Mathf.Max(0.001f, transform.lossyScale.y),
|
||||
worldBounds.size.z / Mathf.Max(0.001f, transform.lossyScale.z)
|
||||
);
|
||||
|
||||
// Задаем минимальную толщину, чтобы физика надежно держала домкрат на асфальте
|
||||
localSize.x = Mathf.Max(localSize.x, 0.25f);
|
||||
localSize.y = Mathf.Max(localSize.y, 0.20f);
|
||||
localSize.z = Mathf.Max(localSize.z, 0.35f);
|
||||
|
||||
// Дно коллайдера никогда не опускается ниже 0 (подошвы домкрата)
|
||||
localCenter.y = Mathf.Max(localCenter.y, localSize.y * 0.5f);
|
||||
|
||||
mainCollider.center = localCenter;
|
||||
mainCollider.size = localSize;
|
||||
}
|
||||
|
||||
transform.rotation = savedRot;
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
DestroyLiftJoint();
|
||||
}
|
||||
|
||||
private void SetupUnifiedDiamondRig()
|
||||
{
|
||||
Bounds b = new Bounds(transform.position, Vector3.zero);
|
||||
bool hasBounds = false;
|
||||
foreach (var r in renderers)
|
||||
{
|
||||
if (r == null) continue;
|
||||
if (!hasBounds) { b = r.bounds; hasBounds = true; }
|
||||
else b.Encapsulate(r.bounds);
|
||||
}
|
||||
|
||||
modelFullHeight = hasBounds ? Mathf.Max(0.15f, b.size.y / transform.lossyScale.y) : 0.32f;
|
||||
|
||||
GameObject pivotObj = new GameObject("DiamondRigPivot");
|
||||
diamondPivot = pivotObj.transform;
|
||||
diamondPivot.SetParent(transform, false);
|
||||
diamondPivot.localPosition = Vector3.zero;
|
||||
diamondPivot.localRotation = Quaternion.identity;
|
||||
diamondPivot.localScale = Vector3.one;
|
||||
|
||||
if (bottomArmL != null) bottomArmL.SetParent(diamondPivot, true);
|
||||
if (bottomArmR != null) bottomArmR.SetParent(diamondPivot, true);
|
||||
if (topArmL != null) topArmL.SetParent(diamondPivot, true);
|
||||
if (topArmR != null) topArmR.SetParent(diamondPivot, true);
|
||||
|
||||
if (topPlate != null)
|
||||
{
|
||||
topPlate.SetParent(transform, true);
|
||||
topPlateInitLocalPos = topPlate.localPosition;
|
||||
}
|
||||
|
||||
if (screw != null)
|
||||
{
|
||||
screw.SetParent(transform, true);
|
||||
screwInitLocalPos = screw.localPosition;
|
||||
screwInitLocalRot = screw.localRotation;
|
||||
}
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (currentState != JackState.InHand) return;
|
||||
|
||||
UpdateInHandPreview();
|
||||
if (Time.frameCount <= stateChangeFrame) return;
|
||||
|
||||
if (canPlaceUnderCar && (Input.GetKeyDown(KeyCode.E) || Input.GetMouseButtonDown(0)))
|
||||
PlaceUnderCar();
|
||||
else if (Input.GetKeyDown(KeyCode.G))
|
||||
DropToFloor();
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
if (currentState == JackState.InHand)
|
||||
{
|
||||
if (uiManager != null) uiManager.ShowPrompt(GetPlacementPrompt());
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentState == JackState.PlacedUnderCar && isHoveredThisFrame && Time.frameCount > stateChangeFrame)
|
||||
{
|
||||
if (Input.GetKey(KeyCode.E))
|
||||
ChangeLift(Time.deltaTime / liftDuration);
|
||||
else if (Input.GetKey(KeyCode.R) && CanLowerSafely())
|
||||
ChangeLift(-Time.deltaTime / liftDuration);
|
||||
else if (liftProgress <= 0.01f && Input.GetKeyDown(KeyCode.G))
|
||||
PickUpToHand(holderCamera, playerRoot);
|
||||
}
|
||||
|
||||
isHoveredThisFrame = false;
|
||||
}
|
||||
|
||||
private void FixedUpdate()
|
||||
{
|
||||
if (currentState != JackState.PlacedUnderCar || targetCarRb == null || supportAnchorRb == null) return;
|
||||
|
||||
// Плавно перемещаем кинематическую точку опоры вверх-вниз вместе с верхушкой домкрата
|
||||
float targetY = initialSillWorldY + liftProgress * carLiftHeight;
|
||||
Vector3 targetAnchorPos = new Vector3(transform.position.x, targetY, transform.position.z);
|
||||
supportAnchorRb.MovePosition(targetAnchorPos);
|
||||
|
||||
if (liftProgress > 0.01f)
|
||||
targetCarRb.WakeUp();
|
||||
}
|
||||
|
||||
private void CreateLiftJoint(Vector3 contactWorld)
|
||||
{
|
||||
DestroyLiftJoint();
|
||||
if (targetCarRb == null) return;
|
||||
|
||||
supportAnchorObj = new GameObject("JackPhysicsSupport");
|
||||
supportAnchorObj.transform.position = contactWorld;
|
||||
|
||||
supportAnchorRb = supportAnchorObj.AddComponent<Rigidbody>();
|
||||
supportAnchorRb.isKinematic = true;
|
||||
supportAnchorRb.interpolation = RigidbodyInterpolation.Interpolate;
|
||||
|
||||
liftJoint = supportAnchorObj.AddComponent<ConfigurableJoint>();
|
||||
liftJoint.connectedBody = targetCarRb;
|
||||
liftJoint.autoConfigureConnectedAnchor = false;
|
||||
liftJoint.anchor = Vector3.zero;
|
||||
liftJoint.connectedAnchor = targetCarRb.transform.InverseTransformPoint(contactWorld);
|
||||
|
||||
// Разрешаем свободный наклон кузова, но плавно и жестко держим высоту точки опоры
|
||||
liftJoint.xMotion = ConfigurableJointMotion.Free;
|
||||
liftJoint.yMotion = ConfigurableJointMotion.Free;
|
||||
liftJoint.zMotion = ConfigurableJointMotion.Free;
|
||||
liftJoint.angularXMotion = ConfigurableJointMotion.Free;
|
||||
liftJoint.angularYMotion = ConfigurableJointMotion.Free;
|
||||
liftJoint.angularZMotion = ConfigurableJointMotion.Free;
|
||||
|
||||
JointDrive verticalDrive = new JointDrive
|
||||
{
|
||||
positionSpring = targetCarRb.mass * 180f,
|
||||
positionDamper = targetCarRb.mass * 28f,
|
||||
maximumForce = targetCarRb.mass * 60f
|
||||
};
|
||||
|
||||
JointDrive horizontalDrive = new JointDrive
|
||||
{
|
||||
positionSpring = targetCarRb.mass * 25f,
|
||||
positionDamper = targetCarRb.mass * 8f,
|
||||
maximumForce = targetCarRb.mass * 20f
|
||||
};
|
||||
|
||||
liftJoint.yDrive = verticalDrive;
|
||||
liftJoint.xDrive = horizontalDrive;
|
||||
liftJoint.zDrive = horizontalDrive;
|
||||
}
|
||||
|
||||
private void DestroyLiftJoint()
|
||||
{
|
||||
if (supportAnchorObj != null)
|
||||
Destroy(supportAnchorObj);
|
||||
supportAnchorObj = null;
|
||||
supportAnchorRb = null;
|
||||
liftJoint = null;
|
||||
}
|
||||
|
||||
private bool CanLowerSafely()
|
||||
{
|
||||
if (targetWheelPart == null) return true;
|
||||
if (targetWheelPart.State != PartState.Installed) return false;
|
||||
if (targetWheelPart.TotalBoltsCount > 0 && targetWheelPart.TightenedBoltsCount < targetWheelPart.TotalBoltsCount)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public string GetPrompt()
|
||||
{
|
||||
isHoveredThisFrame = true;
|
||||
|
||||
if (currentState == JackState.OnFloor)
|
||||
return "[E] Взять домкрат";
|
||||
|
||||
if (currentState == JackState.PlacedUnderCar)
|
||||
{
|
||||
int percent = Mathf.RoundToInt(liftProgress * 100f);
|
||||
if (!CanLowerSafely())
|
||||
return $"Домкрат поднят ({percent}%)\n<color=yellow>Наденьте колесо и закрутите болты перед спуском!</color>";
|
||||
|
||||
if (liftProgress <= 0.01f)
|
||||
return "[Удерж. E] Поднимать авто | [G] Забрать домкрат";
|
||||
|
||||
return $"Домкрат ({percent}%)\n[Удерж. E] Поднять | [Удерж. R] Опустить";
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
public string GetPlacementPrompt()
|
||||
{
|
||||
if (canPlaceUnderCar)
|
||||
return "[E / ЛКМ] Поставить домкрат под порог | [G] Выбросить";
|
||||
return "Наведите на колесо или порог авто | [G] Выбросить домкрат";
|
||||
}
|
||||
|
||||
public void Interact(GameObject interactor)
|
||||
{
|
||||
if (currentState == JackState.OnFloor)
|
||||
{
|
||||
PlayerHands hands = interactor.GetComponentInChildren<PlayerHands>() ?? interactor.GetComponentInParent<PlayerHands>();
|
||||
if (hands != null && hands.IsHolding) return;
|
||||
|
||||
Camera cam = interactor.GetComponentInChildren<Camera>();
|
||||
Transform camTr = cam != null ? cam.transform : FindAnyObjectByType<PlayerInteractor>()?.transform;
|
||||
if (camTr != null)
|
||||
PickUpToHand(camTr, interactor.transform.root);
|
||||
}
|
||||
}
|
||||
|
||||
private void PickUpToHand(Transform camTransform, Transform rootTransform)
|
||||
{
|
||||
if (camTransform == null) return;
|
||||
if (ActiveJackInHand != null && ActiveJackInHand != this) return;
|
||||
|
||||
DestroyLiftJoint();
|
||||
|
||||
holderCamera = camTransform;
|
||||
playerRoot = rootTransform;
|
||||
ActiveJackInHand = this;
|
||||
currentState = JackState.InHand;
|
||||
stateChangeFrame = Time.frameCount;
|
||||
|
||||
targetCarRb = null;
|
||||
targetWheelPart = null;
|
||||
targetWheelCollider = null;
|
||||
liftProgress = 0f;
|
||||
|
||||
if (jackRb != null) Destroy(jackRb);
|
||||
mainCollider.enabled = false;
|
||||
|
||||
transform.SetParent(holderCamera);
|
||||
transform.localScale = originalRootScale;
|
||||
transform.localPosition = inHandOffset;
|
||||
transform.localRotation = Quaternion.Euler(inHandRotation);
|
||||
UpdateJackPose();
|
||||
SetGhostVisual(false);
|
||||
}
|
||||
|
||||
private void UpdateInHandPreview()
|
||||
{
|
||||
canPlaceUnderCar = false;
|
||||
if (holderCamera == null) return;
|
||||
|
||||
Ray ray = new Ray(holderCamera.position, holderCamera.forward);
|
||||
RaycastHit[] hits = Physics.RaycastAll(ray, 4.0f, ~0, QueryTriggerInteraction.Collide);
|
||||
|
||||
bool foundSurface = false;
|
||||
RaycastHit validHit = default;
|
||||
float closestHitDist = float.MaxValue;
|
||||
|
||||
foreach (var h in hits)
|
||||
{
|
||||
if (h.collider.transform.IsChildOf(transform)) continue;
|
||||
if (playerRoot != null && h.collider.transform.IsChildOf(playerRoot)) continue;
|
||||
|
||||
if (h.distance < closestHitDist)
|
||||
{
|
||||
closestHitDist = h.distance;
|
||||
validHit = h;
|
||||
foundSurface = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (foundSurface)
|
||||
{
|
||||
WheelCollider[] allWheels = FindObjectsByType<WheelCollider>(FindObjectsSortMode.None);
|
||||
WheelCollider closestWheel = null;
|
||||
float minWheelDist = 1.8f;
|
||||
|
||||
foreach (var w in allWheels)
|
||||
{
|
||||
float d = Vector3.Distance(validHit.point, w.transform.position);
|
||||
if (d < minWheelDist)
|
||||
{
|
||||
minWheelDist = d;
|
||||
closestWheel = w;
|
||||
}
|
||||
}
|
||||
|
||||
if (closestWheel != null)
|
||||
{
|
||||
Rigidbody carRb = closestWheel.GetComponentInParent<Rigidbody>();
|
||||
if (carRb != null)
|
||||
{
|
||||
Transform carTr = carRb.transform;
|
||||
Vector3 localWheel = carTr.InverseTransformPoint(closestWheel.transform.position);
|
||||
float zOffset = -Mathf.Sign(localWheel.z) * 0.48f;
|
||||
float sideSign = Mathf.Sign(localWheel.x);
|
||||
if (sideSign == 0f) sideSign = 1f;
|
||||
|
||||
Vector3 localSill = new Vector3(localWheel.x * 0.94f, localWheel.y, localWheel.z + zOffset);
|
||||
Vector3 worldSill = carTr.TransformPoint(localSill);
|
||||
|
||||
Vector3 groundPoint = worldSill;
|
||||
groundPoint.y = closestWheel.transform.position.y - closestWheel.radius;
|
||||
|
||||
RaycastHit[] groundHits = Physics.RaycastAll(worldSill + Vector3.up * 0.4f, Vector3.down, 2.0f, ~0, QueryTriggerInteraction.Ignore);
|
||||
foreach (var gh in groundHits)
|
||||
{
|
||||
if (gh.collider.transform.IsChildOf(carTr)) continue;
|
||||
if (gh.collider.transform.IsChildOf(transform)) continue;
|
||||
if (playerRoot != null && gh.collider.transform.IsChildOf(playerRoot)) continue;
|
||||
|
||||
groundPoint = gh.point;
|
||||
break;
|
||||
}
|
||||
|
||||
previewWorldPos = groundPoint;
|
||||
Vector3 outward = carTr.right * sideSign;
|
||||
previewWorldRot = Quaternion.LookRotation(Vector3.Cross(outward, Vector3.up), Vector3.up);
|
||||
|
||||
previewCarRb = carRb;
|
||||
previewWheelCol = closestWheel;
|
||||
previewWheelPart = FindMatchingWheelPart(carTr, closestWheel.name);
|
||||
canPlaceUnderCar = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (canPlaceUnderCar)
|
||||
{
|
||||
transform.position = previewWorldPos;
|
||||
transform.rotation = previewWorldRot;
|
||||
SetGhostVisual(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
transform.localPosition = inHandOffset;
|
||||
transform.localRotation = Quaternion.Euler(inHandRotation);
|
||||
SetGhostVisual(false);
|
||||
}
|
||||
}
|
||||
|
||||
private CarPart FindMatchingWheelPart(Transform carRoot, string wheelName)
|
||||
{
|
||||
foreach (CarPart p in carRoot.GetComponentsInChildren<CarPart>(true))
|
||||
if (p.name == wheelName) return p;
|
||||
return null;
|
||||
}
|
||||
|
||||
private void PlaceUnderCar()
|
||||
{
|
||||
ActiveJackInHand = null;
|
||||
currentState = JackState.PlacedUnderCar;
|
||||
stateChangeFrame = Time.frameCount;
|
||||
SetGhostVisual(false);
|
||||
|
||||
transform.SetParent(null);
|
||||
transform.position = previewWorldPos;
|
||||
transform.rotation = previewWorldRot;
|
||||
|
||||
mainCollider.enabled = true;
|
||||
mainCollider.isTrigger = true;
|
||||
|
||||
targetCarRb = previewCarRb;
|
||||
targetWheelPart = previewWheelPart;
|
||||
targetWheelCollider = previewWheelCol;
|
||||
|
||||
float sillClearance = 0.16f;
|
||||
if (targetWheelCollider != null)
|
||||
{
|
||||
float wheelBottomY = previewWorldPos.y;
|
||||
float hubY = targetWheelCollider.transform.position.y;
|
||||
sillClearance = Mathf.Clamp((hubY - wheelBottomY) * 0.58f, 0.12f, 0.22f);
|
||||
}
|
||||
|
||||
initialSillWorldY = transform.position.y + sillClearance;
|
||||
|
||||
float maxTargetJackHeight = sillClearance + carLiftHeight;
|
||||
float requiredScaleY = maxTargetJackHeight / Mathf.Max(0.1f, modelFullHeight);
|
||||
transform.localScale = new Vector3(originalRootScale.x, requiredScaleY, originalRootScale.z);
|
||||
|
||||
Vector3 contactWorld = new Vector3(transform.position.x, initialSillWorldY, transform.position.z);
|
||||
CreateLiftJoint(contactWorld);
|
||||
|
||||
liftProgress = 0f;
|
||||
UpdateJackPose();
|
||||
}
|
||||
|
||||
private void DropToFloor()
|
||||
{
|
||||
DestroyLiftJoint();
|
||||
ActiveJackInHand = null;
|
||||
currentState = JackState.OnFloor;
|
||||
stateChangeFrame = Time.frameCount;
|
||||
SetGhostVisual(false);
|
||||
|
||||
transform.SetParent(null);
|
||||
transform.localScale = originalRootScale;
|
||||
|
||||
if (holderCamera != null)
|
||||
{
|
||||
// 1. Вычисляем горизонтальную точку перед игроком (независимо от наклона камеры вниз)
|
||||
Vector3 flatForward = Vector3.ProjectOnPlane(holderCamera.forward, Vector3.up).normalized;
|
||||
if (flatForward.sqrMagnitude < 0.01f) flatForward = holderCamera.up;
|
||||
|
||||
Vector3 dropPos = holderCamera.position + flatForward * 1.1f;
|
||||
|
||||
// 2. Ищем уровень пола лучом сверху вниз, чтобы НИКОГДА не заспавнить домкрат под асфальтом
|
||||
Vector3 rayStart = new Vector3(dropPos.x, holderCamera.position.y + 0.5f, dropPos.z);
|
||||
RaycastHit[] hits = Physics.RaycastAll(rayStart, Vector3.down, 5.0f, ~0, QueryTriggerInteraction.Ignore);
|
||||
|
||||
float highestGroundY = float.MinValue;
|
||||
foreach (var h in hits)
|
||||
{
|
||||
if (h.collider.transform.IsChildOf(transform)) continue;
|
||||
if (playerRoot != null && h.collider.transform.IsChildOf(playerRoot)) continue;
|
||||
|
||||
if (h.point.y > highestGroundY)
|
||||
highestGroundY = h.point.y;
|
||||
}
|
||||
|
||||
if (highestGroundY > float.MinValue)
|
||||
{
|
||||
// Ставим на 8 см выше найденного асфальта, чтобы домкрат мягко упал на него сверху
|
||||
dropPos.y = highestGroundY + 0.08f;
|
||||
}
|
||||
else
|
||||
{
|
||||
dropPos.y = holderCamera.position.y - 0.3f;
|
||||
}
|
||||
|
||||
transform.position = dropPos;
|
||||
transform.rotation = Quaternion.Euler(0f, holderCamera.eulerAngles.y, 0f);
|
||||
}
|
||||
|
||||
mainCollider.enabled = true;
|
||||
mainCollider.isTrigger = false;
|
||||
|
||||
if (jackRb == null) jackRb = gameObject.GetComponent<Rigidbody>();
|
||||
if (jackRb == null) jackRb = gameObject.AddComponent<Rigidbody>();
|
||||
|
||||
jackRb.mass = 8f;
|
||||
jackRb.interpolation = RigidbodyInterpolation.Interpolate;
|
||||
// Continuous защищает от пролета сквозь тонкий MeshCollider дороги
|
||||
jackRb.collisionDetectionMode = CollisionDetectionMode.Continuous;
|
||||
jackRb.linearVelocity = Vector3.zero;
|
||||
jackRb.angularVelocity = Vector3.zero;
|
||||
}
|
||||
|
||||
private void SetGhostVisual(bool isGhost)
|
||||
{
|
||||
if (isShowingGhost == isGhost) return;
|
||||
isShowingGhost = isGhost;
|
||||
|
||||
for (int i = 0; i < renderers.Length; i++)
|
||||
{
|
||||
if (renderers[i] == null) continue;
|
||||
renderers[i].sharedMaterial = (isGhost && ghostMaterial != null) ? ghostMaterial : originalMaterials[i];
|
||||
}
|
||||
}
|
||||
|
||||
private void ChangeLift(float delta)
|
||||
{
|
||||
float prev = liftProgress;
|
||||
liftProgress = Mathf.Clamp01(liftProgress + delta);
|
||||
if (Mathf.FloorToInt(prev * 14f) != Mathf.FloorToInt(liftProgress * 14f))
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.JackClick, transform.position, 0.6f, Random.Range(0.95f, 1.08f));
|
||||
|
||||
if (Mathf.Abs(liftProgress - prev) > 0.0001f)
|
||||
UpdateJackPose();
|
||||
}
|
||||
|
||||
private void UpdateJackPose()
|
||||
{
|
||||
float heightRatio = Mathf.Lerp(0.45f, 1.0f, liftProgress);
|
||||
float widthRatio = Mathf.Lerp(1.14f, 1.0f, liftProgress);
|
||||
|
||||
if (diamondPivot != null)
|
||||
diamondPivot.localScale = new Vector3(widthRatio, heightRatio, widthRatio);
|
||||
|
||||
if (topPlate != null)
|
||||
{
|
||||
topPlate.localPosition = new Vector3(
|
||||
topPlateInitLocalPos.x,
|
||||
topPlateInitLocalPos.y * heightRatio,
|
||||
topPlateInitLocalPos.z
|
||||
);
|
||||
}
|
||||
|
||||
if (screw != null)
|
||||
{
|
||||
screw.localPosition = new Vector3(
|
||||
screwInitLocalPos.x,
|
||||
screwInitLocalPos.y * heightRatio,
|
||||
screwInitLocalPos.z
|
||||
);
|
||||
screw.localRotation = screwInitLocalRot;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9f288deec95645989a289923e0cd38ca
|
||||
timeCreated: 1792105469
|
||||
@@ -0,0 +1,240 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class CarWheelCondition : MonoBehaviour
|
||||
{
|
||||
public enum TireState
|
||||
{
|
||||
Normal, // Целое накачанное колесо
|
||||
Flat, // Спущено (нужно заменить)
|
||||
Missing // Колеса изначально нет на ступице
|
||||
}
|
||||
|
||||
// Хранит истинный начальный радиус каждого WheelCollider, чтобы новое колесо никогда не проваливалось
|
||||
private static readonly Dictionary<WheelCollider, float> trueOriginalRadii = new Dictionary<WheelCollider, float>();
|
||||
|
||||
[Header("Состояние колеса")]
|
||||
public TireState currentState = TireState.Normal;
|
||||
|
||||
[Header("Настройки деформации покрышки (Диск не затрагивается)")]
|
||||
[Range(0.4f, 0.8f)] [SerializeField] private float rimRadiusRatio = 0.62f;
|
||||
[Range(0.02f, 0.12f)] [SerializeField] private float flatSquashAmount = 0.055f;
|
||||
[Range(0f, 0.06f)] [SerializeField] private float sidewallBulge = 0.025f;
|
||||
|
||||
private CarPart carPart;
|
||||
private MeshFilter meshFilter;
|
||||
private Mesh runtimeMesh;
|
||||
private Vector3[] originalVertices;
|
||||
private Vector3[] deformedVertices;
|
||||
private float maxMeshRadius = 0.32f;
|
||||
private Vector3 meshCenter;
|
||||
private Quaternion lastDeformedRot;
|
||||
private Mesh sourceMesh;
|
||||
private Transform meshTransform;
|
||||
|
||||
/// <summary>Исходный (недеформированный) меш колеса — для создания запасных колес в магазине.</summary>
|
||||
public Mesh SourceMesh => sourceMesh;
|
||||
|
||||
public bool IsFlat => currentState == TireState.Flat;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
carPart = GetComponent<CarPart>();
|
||||
meshFilter = GetComponent<MeshFilter>();
|
||||
if (meshFilter == null || meshFilter.sharedMesh == null)
|
||||
{
|
||||
// Колесо из нескольких мешей (диск + шина): деформируем самый крупный (покрышку)
|
||||
float best = 0f;
|
||||
foreach (MeshFilter mf in GetComponentsInChildren<MeshFilter>(true))
|
||||
{
|
||||
if (mf.sharedMesh == null || mf.GetComponent<WheelBolt>() != null) continue;
|
||||
float size = mf.sharedMesh.bounds.size.sqrMagnitude;
|
||||
if (size > best) { best = size; meshFilter = mf; }
|
||||
}
|
||||
}
|
||||
meshTransform = meshFilter != null ? meshFilter.transform : transform;
|
||||
|
||||
// Кэшируем истинный радиус всех WheelCollider машины до любых изменений
|
||||
VehicleInteraction car = GetComponentInParent<VehicleInteraction>();
|
||||
if (car != null)
|
||||
{
|
||||
foreach (WheelCollider wc in car.GetComponentsInChildren<WheelCollider>(true))
|
||||
{
|
||||
if (!trueOriginalRadii.ContainsKey(wc))
|
||||
trueOriginalRadii[wc] = wc.radius;
|
||||
}
|
||||
}
|
||||
|
||||
if (meshFilter != null) sourceMesh = meshFilter.sharedMesh;
|
||||
|
||||
if (meshFilter != null && meshFilter.sharedMesh != null && meshFilter.sharedMesh.isReadable)
|
||||
{
|
||||
runtimeMesh = Instantiate(meshFilter.sharedMesh);
|
||||
meshFilter.mesh = runtimeMesh;
|
||||
originalVertices = runtimeMesh.vertices;
|
||||
deformedVertices = new Vector3[originalVertices.Length];
|
||||
|
||||
Bounds b = runtimeMesh.bounds;
|
||||
meshCenter = b.center;
|
||||
maxMeshRadius = Mathf.Max(b.extents.y, b.extents.z);
|
||||
}
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
ApplyState(currentState);
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
// Обновляем вмятину покрышки только когда машина реально катится (чтобы не вызывать дрожь на месте)
|
||||
if (currentState == TireState.Flat && runtimeMesh != null && carPart != null && carPart.State == PartState.Installed)
|
||||
{
|
||||
if (Quaternion.Angle(meshTransform.rotation, lastDeformedRot) > 8f)
|
||||
{
|
||||
DeformTireMesh();
|
||||
lastDeformedRot = meshTransform.rotation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void ApplyState(TireState newState)
|
||||
{
|
||||
currentState = newState;
|
||||
if (carPart == null) carPart = GetComponent<CarPart>();
|
||||
|
||||
if (currentState == TireState.Missing)
|
||||
{
|
||||
if (carPart != null && carPart.State == PartState.Installed)
|
||||
carPart.MakeMissingAtStart();
|
||||
return;
|
||||
}
|
||||
|
||||
UpdateWheelColliderPhysics();
|
||||
|
||||
if (runtimeMesh != null)
|
||||
{
|
||||
if (currentState == TireState.Flat)
|
||||
{
|
||||
DeformTireMesh();
|
||||
lastDeformedRot = meshTransform.rotation;
|
||||
}
|
||||
else
|
||||
{
|
||||
runtimeMesh.vertices = originalVertices;
|
||||
runtimeMesh.RecalculateBounds();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdateWheelColliderPhysics()
|
||||
{
|
||||
if (carPart == null) carPart = GetComponent<CarPart>();
|
||||
if (carPart == null) return;
|
||||
|
||||
WheelCollider wc = carPart.LinkedWheelCollider;
|
||||
if (wc == null) return;
|
||||
|
||||
if (!trueOriginalRadii.TryGetValue(wc, out float baseRadius))
|
||||
{
|
||||
baseRadius = wc.radius;
|
||||
trueOriginalRadii[wc] = baseRadius;
|
||||
}
|
||||
|
||||
if (currentState == TireState.Flat)
|
||||
{
|
||||
// Мягко занижаем радиус на 10% (без ударов днищем и без раскачки подвески)
|
||||
wc.radius = baseRadius * 0.90f;
|
||||
WheelFrictionCurve side = wc.sidewaysFriction;
|
||||
side.stiffness = 1.0f;
|
||||
wc.sidewaysFriction = side;
|
||||
}
|
||||
else
|
||||
{
|
||||
// ГАРАНТИРОВАННО возвращаем 100% заводской радиус при установке целого колеса!
|
||||
wc.radius = baseRadius;
|
||||
WheelFrictionCurve side = wc.sidewaysFriction;
|
||||
side.stiffness = 2.0f;
|
||||
wc.sidewaysFriction = side;
|
||||
}
|
||||
}
|
||||
|
||||
private void DeformTireMesh()
|
||||
{
|
||||
if (originalVertices == null) return;
|
||||
|
||||
float rimRadius = maxMeshRadius * rimRadiusRatio;
|
||||
Vector3 localDown = (carPart != null && carPart.State == PartState.Installed)
|
||||
? meshTransform.InverseTransformDirection(Vector3.down).normalized
|
||||
: Vector3.down;
|
||||
|
||||
for (int i = 0; i < originalVertices.Length; i++)
|
||||
{
|
||||
Vector3 v = originalVertices[i];
|
||||
Vector3 fromCenter = v - meshCenter;
|
||||
float radialDist = Mathf.Sqrt(fromCenter.y * fromCenter.y + fromCenter.z * fromCenter.z);
|
||||
|
||||
if (radialDist <= rimRadius)
|
||||
{
|
||||
deformedVertices[i] = v;
|
||||
continue;
|
||||
}
|
||||
|
||||
float rubberFactor = Mathf.InverseLerp(rimRadius, maxMeshRadius, radialDist);
|
||||
Vector3 radialDir = new Vector3(0f, fromCenter.y, fromCenter.z).normalized;
|
||||
float bottomDot = Vector3.Dot(radialDir, localDown);
|
||||
|
||||
if (bottomDot > 0.30f)
|
||||
{
|
||||
float bottomFactor = Mathf.InverseLerp(0.30f, 1.0f, bottomDot);
|
||||
float squash = bottomFactor * rubberFactor * flatSquashAmount;
|
||||
|
||||
v -= localDown * squash;
|
||||
float sideSign = Mathf.Sign(fromCenter.x);
|
||||
v.x += sideSign * (bottomFactor * Mathf.Sin(rubberFactor * Mathf.PI) * sidewallBulge);
|
||||
}
|
||||
|
||||
deformedVertices[i] = v;
|
||||
}
|
||||
|
||||
runtimeMesh.vertices = deformedVertices;
|
||||
}
|
||||
|
||||
/// <summary>Создает новое целое колесо-дубликат (без болтов на ступице) для магазина.</summary>
|
||||
public static CarPart CreateSpareFrom(CarPart wheelTemplate, Vector3 worldPos)
|
||||
{
|
||||
if (wheelTemplate == null) return null;
|
||||
|
||||
// Создаем копию в неактивном контейнере, чтобы Awake отработал уже после восстановления меша
|
||||
GameObject holder = new GameObject("SpareWheelHolder");
|
||||
holder.SetActive(false);
|
||||
GameObject copy = Instantiate(wheelTemplate.gameObject, holder.transform);
|
||||
copy.name = wheelTemplate.gameObject.name;
|
||||
copy.SetActive(true);
|
||||
|
||||
CarWheelCondition src = wheelTemplate.GetComponent<CarWheelCondition>();
|
||||
CarWheelCondition dst = copy.GetComponent<CarWheelCondition>();
|
||||
if (src != null && dst != null && src.SourceMesh != null)
|
||||
{
|
||||
MeshFilter target = null;
|
||||
foreach (MeshFilter mf in copy.GetComponentsInChildren<MeshFilter>(true))
|
||||
{
|
||||
if (src.meshFilter != null && mf.name == src.meshFilter.name) { target = mf; break; }
|
||||
}
|
||||
if (target != null) target.sharedMesh = src.SourceMesh;
|
||||
dst.currentState = TireState.Normal;
|
||||
}
|
||||
|
||||
Rigidbody rb = copy.GetComponent<Rigidbody>();
|
||||
if (rb != null) DestroyImmediate(rb);
|
||||
|
||||
copy.transform.SetParent(null);
|
||||
copy.transform.position = worldPos;
|
||||
copy.transform.rotation = Quaternion.Euler(0f, 0f, 90f);
|
||||
Destroy(holder);
|
||||
|
||||
CarPart part = copy.GetComponent<CarPart>();
|
||||
if (part != null) part.InitializeAsLoosePart();
|
||||
return part;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9f5711453a0b43ad8d142a54264c4981
|
||||
timeCreated: 1792508527
|
||||
@@ -0,0 +1,420 @@
|
||||
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;
|
||||
|
||||
/// <summary>Настройка канистры из кода (магазин автохимии, автонастройка).</summary>
|
||||
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<Collider>();
|
||||
rb = GetComponent<Rigidbody>();
|
||||
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<ParticleSystem>();
|
||||
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<ParticleSystemRenderer>();
|
||||
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<PlayerHands>();
|
||||
if (hands == null) hands = interactor.GetComponentInParent<PlayerHands>();
|
||||
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<Rigidbody>();
|
||||
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<Camera>() : 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<CarFluidCap>();
|
||||
}
|
||||
|
||||
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<VehicleInteraction>();
|
||||
if (car != null)
|
||||
{
|
||||
foreach (CarPartAnimator a in car.GetComponentsInChildren<CarPartAnimator>())
|
||||
{
|
||||
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<CarFluidCap>(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<Collider>());
|
||||
Renderer r = capMarker.GetComponent<Renderer>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ea11abd87b90ed046961814227fc398c
|
||||
@@ -0,0 +1,266 @@
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(SphereCollider))]
|
||||
public class WheelBolt : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Header("Настройки вылета и скорости")]
|
||||
[SerializeField] private float pullOutDistance = 0.05f;
|
||||
[SerializeField] private float workDuration = 0.5f;
|
||||
|
||||
private CarPart parentWheel;
|
||||
private MeshRenderer meshRenderer;
|
||||
private SphereCollider boltCollider;
|
||||
private Material originalMaterial;
|
||||
private Material ghostMaterial;
|
||||
private PlayerToolManager toolManager;
|
||||
|
||||
private Vector3 tightenedLocalPos;
|
||||
private Quaternion tightenedLocalRot;
|
||||
private Vector3 baseLocalScale;
|
||||
|
||||
private Vector3 localMeshCenter;
|
||||
private Vector3 boltCenterInParent;
|
||||
private Vector3 parentOutwardDir = Vector3.right;
|
||||
|
||||
private float tightness = 1f;
|
||||
private bool isTightened = true;
|
||||
private bool isHoveredThisFrame = false;
|
||||
|
||||
// Глобальная блокировка до отпускания кнопки, чтобы болт НИКОГДА не крутился туда-сюда по кругу
|
||||
private static bool waitForKeyRelease = false;
|
||||
|
||||
public bool IsTightened => isTightened;
|
||||
public bool IsAvailableForAim => parentWheel == null || parentWheel.State == PartState.Installed;
|
||||
|
||||
// ВАЖНО: Координата для прицела берется от неподвижного гнезда на ступице,
|
||||
// чтобы во время выдвижения болта он не выскакивал из-под прицела!
|
||||
public Vector3 WorldBoltCenter => transform.parent != null
|
||||
? transform.parent.TransformPoint(boltCenterInParent)
|
||||
: transform.TransformPoint(localMeshCenter);
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
parentWheel = GetComponentInParent<CarPart>();
|
||||
meshRenderer = GetComponent<MeshRenderer>();
|
||||
boltCollider = GetComponent<SphereCollider>();
|
||||
toolManager = FindAnyObjectByType<PlayerToolManager>();
|
||||
|
||||
tightenedLocalPos = transform.localPosition;
|
||||
tightenedLocalRot = transform.localRotation;
|
||||
baseLocalScale = transform.localScale;
|
||||
|
||||
MeshFilter mf = GetComponent<MeshFilter>();
|
||||
if (mf != null && mf.sharedMesh != null)
|
||||
localMeshCenter = mf.sharedMesh.bounds.center;
|
||||
|
||||
boltCollider.isTrigger = true;
|
||||
boltCollider.center = localMeshCenter;
|
||||
boltCollider.radius = 0.055f;
|
||||
|
||||
boltCenterInParent = tightenedLocalPos + tightenedLocalRot * Vector3.Scale(localMeshCenter, baseLocalScale);
|
||||
|
||||
if (meshRenderer != null)
|
||||
originalMaterial = meshRenderer.sharedMaterial;
|
||||
|
||||
if (parentWheel != null && parentWheel.Data != null)
|
||||
ghostMaterial = parentWheel.Data.ghostMaterial;
|
||||
|
||||
// Если в CarPartData забыли назначить Ghost Material — создаем запасной полупрозрачный материал
|
||||
if (ghostMaterial == null)
|
||||
{
|
||||
Shader sh = Shader.Find("Universal Render Pipeline/Unlit") ?? Shader.Find("Sprites/Default");
|
||||
if (sh != null)
|
||||
{
|
||||
ghostMaterial = new Material(sh);
|
||||
ghostMaterial.color = new Color(0.2f, 0.95f, 0.35f, 0.5f);
|
||||
}
|
||||
}
|
||||
|
||||
RecalculateOutwardDirection();
|
||||
}
|
||||
|
||||
public void RecalculateOutwardDirection()
|
||||
{
|
||||
Vector3 worldBoltPos = WorldBoltCenter;
|
||||
VehicleInteraction car = GetComponentInParent<VehicleInteraction>();
|
||||
Transform carRoot = car != null ? car.transform : transform.root;
|
||||
|
||||
Vector3 fromCarToBolt = worldBoltPos - carRoot.position;
|
||||
float sideSign = Mathf.Sign(Vector3.Dot(fromCarToBolt, carRoot.right));
|
||||
if (sideSign == 0f) sideSign = 1f;
|
||||
|
||||
Vector3 worldOutDir = carRoot.right * sideSign;
|
||||
parentOutwardDir = transform.parent != null
|
||||
? transform.parent.InverseTransformDirection(worldOutDir).normalized
|
||||
: Vector3.right * sideSign;
|
||||
|
||||
UpdateBoltTransform(1f);
|
||||
}
|
||||
|
||||
public void SetTightenedImmediate(bool state)
|
||||
{
|
||||
isTightened = state;
|
||||
tightness = state ? 1f : 0f;
|
||||
UpdateBoltTransform(1f);
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
// Снимаем блокировку сразу, как только игрок отпустил ЛКМ и клавишу E
|
||||
if (waitForKeyRelease && !Input.GetMouseButton(0) && !Input.GetKey(KeyCode.E))
|
||||
{
|
||||
waitForKeyRelease = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
if (parentWheel == null)
|
||||
parentWheel = GetComponentInParent<CarPart>();
|
||||
|
||||
// Пока колесо в руках или лежит на земле — болты полностью скрыты
|
||||
if (parentWheel != null && parentWheel.State != PartState.Installed)
|
||||
{
|
||||
if (meshRenderer != null && meshRenderer.enabled) meshRenderer.enabled = false;
|
||||
if (boltCollider != null && boltCollider.enabled) boltCollider.enabled = false;
|
||||
isHoveredThisFrame = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (boltCollider != null && !boltCollider.enabled)
|
||||
boltCollider.enabled = true;
|
||||
|
||||
if (toolManager == null)
|
||||
toolManager = FindAnyObjectByType<PlayerToolManager>();
|
||||
|
||||
bool hasWrench = toolManager != null && toolManager.currentTool == ToolType.Wrench;
|
||||
bool isAnimating = tightness > 0.01f && tightness < 0.99f;
|
||||
|
||||
// Если игрок отпустил кнопку на полпути или увел взгляд — возвращаем болт в крайнее положение
|
||||
if (!isHoveredThisFrame || (!Input.GetMouseButton(0) && !Input.GetKey(KeyCode.E)))
|
||||
{
|
||||
tightness = isTightened ? 1f : 0f;
|
||||
isAnimating = false;
|
||||
}
|
||||
|
||||
// Болт под прицелом заметно увеличивается (1.35x), чтобы игрок четко видел выбранный болт
|
||||
float scaleMult = (isHoveredThisFrame && hasWrench) ? 1.35f : 1.0f;
|
||||
UpdateBoltTransform(scaleMult);
|
||||
|
||||
if (meshRenderer != null)
|
||||
{
|
||||
if (isTightened || isAnimating)
|
||||
{
|
||||
// Закрученный болт всегда виден; под прицелом с ключом — подсвечивается
|
||||
meshRenderer.enabled = true;
|
||||
if (isHoveredThisFrame && hasWrench && ghostMaterial != null)
|
||||
meshRenderer.sharedMaterial = ghostMaterial;
|
||||
else if (originalMaterial != null)
|
||||
meshRenderer.sharedMaterial = originalMaterial;
|
||||
}
|
||||
else
|
||||
{
|
||||
// КЛЮЧЕВОЕ ИСПРАВЛЕНИЕ: когда болты выкручены и игрок взял КЛЮЧ (hasWrench),
|
||||
// ВСЕ 4 места под болты сразу подсвечиваются силуэтом, чтобы игрок видел, куда наводиться!
|
||||
meshRenderer.enabled = hasWrench;
|
||||
if (hasWrench && ghostMaterial != null)
|
||||
meshRenderer.sharedMaterial = ghostMaterial;
|
||||
}
|
||||
}
|
||||
|
||||
isHoveredThisFrame = false;
|
||||
}
|
||||
|
||||
public string GetPrompt()
|
||||
{
|
||||
isHoveredThisFrame = true;
|
||||
|
||||
if (isTightened && parentWheel != null && !CarJack.IsWheelLifted(parentWheel.transform))
|
||||
{
|
||||
return "Колесо под нагрузкой! Сначала поднимите эту сторону домкратом";
|
||||
}
|
||||
|
||||
bool hasWrench = toolManager != null && toolManager.currentTool == ToolType.Wrench;
|
||||
if (!hasWrench)
|
||||
{
|
||||
return isTightened
|
||||
? "Колесный болт (Возьмите баллонный ключ [Tab])"
|
||||
: "Место под болт (Возьмите баллонный ключ [Tab])";
|
||||
}
|
||||
|
||||
bool isHoldingKey = Input.GetMouseButton(0) || Input.GetKey(KeyCode.E);
|
||||
|
||||
if (isHoldingKey && !waitForKeyRelease)
|
||||
{
|
||||
ProcessWrench(Time.deltaTime);
|
||||
}
|
||||
|
||||
int percent = Mathf.RoundToInt((isTightened ? (1f - tightness) : tightness) * 100f);
|
||||
|
||||
if (isTightened)
|
||||
{
|
||||
if (waitForKeyRelease) return "Болт закручен! Отпустите кнопку";
|
||||
return percent > 0 ? $"Откручиваем болт... {percent}%" : "[Удерж. ЛКМ / E] Открутить болт";
|
||||
}
|
||||
else
|
||||
{
|
||||
if (waitForKeyRelease) return "Болт выкручен! Отпустите кнопку";
|
||||
return percent > 0 ? $"Закручиваем болт... {percent}%" : "[Удерж. ЛКМ / E] Закрутить болт";
|
||||
}
|
||||
}
|
||||
|
||||
private static float lastRatchetTime;
|
||||
|
||||
private void ProcessWrench(float dt)
|
||||
{
|
||||
float step = dt / workDuration;
|
||||
if (Time.time - lastRatchetTime > 0.16f)
|
||||
{
|
||||
lastRatchetTime = Time.time;
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.Ratchet, transform.position, 0.7f, Random.Range(0.9f, 1.1f));
|
||||
}
|
||||
|
||||
if (isTightened)
|
||||
{
|
||||
tightness -= step;
|
||||
if (tightness <= 0f)
|
||||
{
|
||||
tightness = 0f;
|
||||
isTightened = false;
|
||||
waitForKeyRelease = true; // Блокируем до отпускания кнопки!
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
tightness += step;
|
||||
if (tightness >= 1f)
|
||||
{
|
||||
tightness = 1f;
|
||||
isTightened = true;
|
||||
waitForKeyRelease = true; // Блокируем до отпускания кнопки!
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateBoltTransform(float scaleMultiplier = 1f)
|
||||
{
|
||||
// Выкрученный неанимируемый силуэт стоит ровно в гнезде ступицы (outFactor = 0),
|
||||
// чтобы силуэты отверстий не висели в воздухе в 5 см от диска
|
||||
bool isAnimating = tightness > 0.001f && tightness < 0.999f;
|
||||
float outFactor = isAnimating ? (1f - Mathf.Clamp01(tightness)) : 0f;
|
||||
|
||||
Vector3 currentScale = baseLocalScale * scaleMultiplier;
|
||||
|
||||
Quaternion spinRotation = Quaternion.AngleAxis(outFactor * 720f, parentOutwardDir);
|
||||
Quaternion newLocalRot = spinRotation * tightenedLocalRot;
|
||||
|
||||
Vector3 rotatedCenterOffset = newLocalRot * Vector3.Scale(localMeshCenter, currentScale);
|
||||
Vector3 pullOutOffset = parentOutwardDir * (pullOutDistance * outFactor);
|
||||
|
||||
transform.localScale = currentScale;
|
||||
transform.localRotation = newLocalRot;
|
||||
transform.localPosition = boltCenterInParent - rotatedCenterOffset + pullOutOffset;
|
||||
}
|
||||
|
||||
public void Interact(GameObject interactor) { }
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d6608191adf74f8ab4b691b58c60a3f5
|
||||
timeCreated: 1792096376
|
||||
@@ -0,0 +1,217 @@
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(BoxCollider))]
|
||||
public class WheelBrickSupport : MonoBehaviour, IInteractable
|
||||
{
|
||||
private Rigidbody carRb;
|
||||
private Transform carRoot;
|
||||
private WheelCollider targetWheelCollider;
|
||||
private string targetWheelName;
|
||||
|
||||
private GameObject physicsAnchorObj;
|
||||
private ConfigurableJoint supportJoint;
|
||||
|
||||
public static WheelBrickSupport CreateUnderWheel(CarPart missingWheelPart, GameObject customBricksPrefab = null)
|
||||
{
|
||||
if (missingWheelPart == null) return null;
|
||||
|
||||
Rigidbody rb = missingWheelPart.GetComponentInParent<Rigidbody>();
|
||||
if (rb == null) return null;
|
||||
|
||||
Transform carTr = rb.transform;
|
||||
WheelCollider wc = missingWheelPart.LinkedWheelCollider;
|
||||
Vector3 wheelWorldPos = wc != null ? wc.transform.position : missingWheelPart.transform.position;
|
||||
|
||||
// Находим точку под порогом рядом с колесной аркой (чтобы новое колесо не проходило сквозь кирпичи)
|
||||
Vector3 localWheel = carTr.InverseTransformPoint(wheelWorldPos);
|
||||
float zOffset = -Mathf.Sign(localWheel.z) * 0.42f;
|
||||
float sideSign = Mathf.Sign(localWheel.x);
|
||||
if (sideSign == 0f) sideSign = 1f;
|
||||
|
||||
Vector3 localSupportPoint = new Vector3(localWheel.x * 0.92f, localWheel.y, localWheel.z + zOffset);
|
||||
Vector3 worldSupportPoint = carTr.TransformPoint(localSupportPoint);
|
||||
|
||||
// Ищем высоту асфальта строго под точкой опоры
|
||||
float groundY = wheelWorldPos.y - (wc != null ? wc.radius : 0.32f);
|
||||
RaycastHit[] hits = Physics.RaycastAll(worldSupportPoint + Vector3.up * 0.5f, Vector3.down, 2.0f, ~0, QueryTriggerInteraction.Ignore);
|
||||
foreach (var h in hits)
|
||||
{
|
||||
if (h.collider.transform.IsChildOf(carTr)) continue;
|
||||
groundY = h.point.y;
|
||||
break;
|
||||
}
|
||||
|
||||
// Высота от земли до днища/порога
|
||||
float sillClearance = wc != null ? Mathf.Clamp((wheelWorldPos.y - groundY) * 0.62f, 0.14f, 0.26f) : 0.18f;
|
||||
Vector3 spawnPos = new Vector3(worldSupportPoint.x, groundY, worldSupportPoint.z);
|
||||
|
||||
GameObject supportObj = new GameObject($"BrickSupport_{missingWheelPart.name}");
|
||||
supportObj.layer = missingWheelPart.gameObject.layer;
|
||||
supportObj.transform.position = spawnPos;
|
||||
supportObj.transform.rotation = carTr.rotation;
|
||||
|
||||
WheelBrickSupport support = supportObj.AddComponent<WheelBrickSupport>();
|
||||
support.Initialize(rb, wc, missingWheelPart.name, sillClearance, customBricksPrefab);
|
||||
return support;
|
||||
}
|
||||
|
||||
private void Initialize(Rigidbody rb, WheelCollider wc, string wheelName, float height, GameObject customPrefab)
|
||||
{
|
||||
carRb = rb;
|
||||
carRoot = rb.transform;
|
||||
targetWheelCollider = wc;
|
||||
targetWheelName = wheelName;
|
||||
|
||||
// Настраиваем триггер-коллайдер для луча игрока
|
||||
BoxCollider col = GetComponent<BoxCollider>();
|
||||
col.isTrigger = true;
|
||||
col.size = new Vector3(0.32f, height + 0.06f, 0.38f);
|
||||
col.center = new Vector3(0f, (height + 0.06f) * 0.5f, 0f);
|
||||
|
||||
// Создаем визуал кирпичей (префаб или процедурную кладку)
|
||||
if (customPrefab != null)
|
||||
{
|
||||
GameObject visual = Instantiate(customPrefab, transform);
|
||||
visual.transform.localPosition = Vector3.zero;
|
||||
visual.transform.localRotation = Quaternion.identity;
|
||||
foreach (var c in visual.GetComponentsInChildren<Collider>(true)) c.enabled = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
BuildProceduralBricks(height);
|
||||
}
|
||||
|
||||
// Фиксируем этот угол машины на текущей высоте, чтобы она не кренилась без колеса
|
||||
Vector3 contactWorld = transform.position + Vector3.up * height;
|
||||
CreateSupportJoint(contactWorld);
|
||||
}
|
||||
|
||||
private void BuildProceduralBricks(float totalHeight)
|
||||
{
|
||||
Material brickMat = new Material(Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard"));
|
||||
brickMat.color = new Color(0.68f, 0.28f, 0.18f); // Кирпичный цвет
|
||||
|
||||
int layers = 3;
|
||||
float brickH = totalHeight / layers;
|
||||
float brickW = 0.12f;
|
||||
float brickL = 0.25f;
|
||||
|
||||
for (int row = 0; row < layers; row++)
|
||||
{
|
||||
float yPos = (row + 0.5f) * brickH;
|
||||
bool rotated = (row % 2 == 1);
|
||||
|
||||
for (int i = -1; i <= 1; i += 2)
|
||||
{
|
||||
GameObject brick = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
Destroy(brick.GetComponent<Collider>());
|
||||
brick.transform.SetParent(transform, false);
|
||||
|
||||
float offset = i * (brickW * 0.54f);
|
||||
brick.transform.localPosition = rotated
|
||||
? new Vector3(0f, yPos, offset)
|
||||
: new Vector3(offset, yPos, 0f);
|
||||
|
||||
brick.transform.localRotation = rotated
|
||||
? Quaternion.Euler(0f, 90f, 0f)
|
||||
: Quaternion.identity;
|
||||
|
||||
brick.transform.localScale = new Vector3(brickW, brickH * 0.92f, brickL);
|
||||
brick.GetComponent<Renderer>().sharedMaterial = brickMat;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void CreateSupportJoint(Vector3 contactWorld)
|
||||
{
|
||||
if (carRb == null) return;
|
||||
|
||||
physicsAnchorObj = new GameObject("BricksPhysicsAnchor");
|
||||
physicsAnchorObj.transform.position = contactWorld;
|
||||
|
||||
Rigidbody anchorRb = physicsAnchorObj.AddComponent<Rigidbody>();
|
||||
anchorRb.isKinematic = true;
|
||||
|
||||
supportJoint = physicsAnchorObj.AddComponent<ConfigurableJoint>();
|
||||
supportJoint.connectedBody = carRb;
|
||||
supportJoint.autoConfigureConnectedAnchor = false;
|
||||
supportJoint.anchor = Vector3.zero;
|
||||
supportJoint.connectedAnchor = carRb.transform.InverseTransformPoint(contactWorld);
|
||||
|
||||
JointDrive verticalDrive = new JointDrive
|
||||
{
|
||||
positionSpring = carRb.mass * 220f,
|
||||
positionDamper = carRb.mass * 30f,
|
||||
maximumForce = carRb.mass * 80f
|
||||
};
|
||||
|
||||
JointDrive horizontalDrive = new JointDrive
|
||||
{
|
||||
positionSpring = carRb.mass * 40f,
|
||||
positionDamper = carRb.mass * 10f,
|
||||
maximumForce = carRb.mass * 30f
|
||||
};
|
||||
|
||||
supportJoint.xDrive = horizontalDrive;
|
||||
supportJoint.yDrive = verticalDrive;
|
||||
supportJoint.zDrive = horizontalDrive;
|
||||
}
|
||||
|
||||
private bool IsWheelReadyToHoldCar()
|
||||
{
|
||||
if (carRoot == null) return true;
|
||||
|
||||
// Если эту сторону уже подняли домкратом — кирпичи тоже можно свободно вытащить
|
||||
if (CarJack.IsWheelLifted(transform)) return true;
|
||||
|
||||
// Ищем установленное на эту ступицу колесо и проверяем его болты
|
||||
foreach (CarPart part in carRoot.GetComponentsInChildren<CarPart>(false))
|
||||
{
|
||||
if (part.State != PartState.Installed) continue;
|
||||
|
||||
bool isMatchingHub = (targetWheelCollider != null && part.LinkedWheelCollider == targetWheelCollider)
|
||||
|| part.name == targetWheelName;
|
||||
|
||||
if (isMatchingHub)
|
||||
{
|
||||
return part.TotalBoltsCount == 0 || part.TightenedBoltsCount >= part.TotalBoltsCount;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public string GetPrompt()
|
||||
{
|
||||
if (!IsWheelReadyToHoldCar())
|
||||
{
|
||||
return "Машина стоит на кирпичах\n<color=yellow>Сначала установите колесо и закрутите все болты!</color>";
|
||||
}
|
||||
|
||||
return "[E] Убрать кирпичи";
|
||||
}
|
||||
|
||||
public void Interact(GameObject interactor)
|
||||
{
|
||||
if (!IsWheelReadyToHoldCar()) return;
|
||||
|
||||
RemoveBricks();
|
||||
}
|
||||
|
||||
public void RemoveBricks()
|
||||
{
|
||||
if (physicsAnchorObj != null)
|
||||
Destroy(physicsAnchorObj);
|
||||
|
||||
if (carRb != null)
|
||||
carRb.WakeUp();
|
||||
|
||||
Destroy(gameObject);
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (physicsAnchorObj != null)
|
||||
Destroy(physicsAnchorObj);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f60f5fc826264d8781da1587ba1ec484
|
||||
timeCreated: 1792535337
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0de206522eb940258e88b78fd9cd8e0c
|
||||
timeCreated: 1791330354
|
||||
@@ -0,0 +1,342 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public struct CarDefectsSummary
|
||||
{
|
||||
public int rustedPartsCount;
|
||||
public int missingBodyPartsCount;
|
||||
public int flatTiresCount;
|
||||
public int missingWheelsCount;
|
||||
public int lowFluidsCount;
|
||||
public int engineIssuesCount;
|
||||
public int hiddenRepaintCount;
|
||||
public float dirtAmount;
|
||||
public bool startProblems;
|
||||
public bool oilProblems;
|
||||
public bool overheatProblems;
|
||||
public bool brakeProblems;
|
||||
public List<string> missingPartNames;
|
||||
public float totalPricePenalty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Детерминированная генерация состояния подержанного авто по Seed: грязь, ржавчина, скрытый перекрас,
|
||||
/// отсутствующие навесные детали, спущенные/отсутствующие колеса, износ подкапотных агрегатов и жидкостей.
|
||||
/// Один и тот же seed дает 100% одинаковую машину и на фото объявления, и на месте встречи.
|
||||
/// </summary>
|
||||
public class CarConditionGenerator : MonoBehaviour
|
||||
{
|
||||
[Header("Настройки ржавчины")]
|
||||
[Range(0f, 1f)] [SerializeField] private float rustProbability = 0.65f;
|
||||
[SerializeField] private float minRustAmount = 0.25f;
|
||||
[SerializeField] private float maxRustAmount = 0.80f;
|
||||
|
||||
[Header("Шанс отсутствия навесных деталей (бамперы, фары, крылья)")]
|
||||
[Range(0f, 0.5f)] [SerializeField] private float missingBodyPartChance = 0.15f;
|
||||
[SerializeField] private int maxMissingBodyParts = 3;
|
||||
|
||||
[Header("Проблемы с колесами")]
|
||||
[Range(0f, 1f)] [SerializeField] private float flatTireChance = 0.25f;
|
||||
[Range(0f, 1f)] [SerializeField] private float missingWheelChance = 0.12f;
|
||||
|
||||
[Header("Грязь и скрытый перекрас")]
|
||||
[SerializeField] private Vector2 dirtRange = new Vector2(0.35f, 0.95f);
|
||||
[Range(0f, 1f)] [SerializeField] private float hiddenRepaintChance = 0.18f;
|
||||
|
||||
[Header("Цвет кузова")]
|
||||
[SerializeField] private bool overrideMaterialColor = false;
|
||||
[SerializeField] private Color baseCarColor = Color.blue;
|
||||
|
||||
private bool configuredExternally = false;
|
||||
|
||||
public CarDefectsSummary LastSummary { get; private set; }
|
||||
|
||||
private void Start()
|
||||
{
|
||||
// Если машина уже настроена через CarMarketManager (по Seed) — не перезаписываем её!
|
||||
if (!configuredExternally)
|
||||
{
|
||||
GenerateCondition();
|
||||
}
|
||||
}
|
||||
|
||||
public void MarkConfigured() => configuredExternally = true;
|
||||
|
||||
[ContextMenu("Сгенерировать случайное состояние")]
|
||||
public void GenerateCondition()
|
||||
{
|
||||
int randomSeed = Random.Range(1, 999999);
|
||||
Color col = overrideMaterialColor ? baseCarColor : GetCurrentBodyColor();
|
||||
ApplyConditionBySeed(randomSeed, col, false, out _);
|
||||
}
|
||||
|
||||
public Color GetCurrentBodyColor()
|
||||
{
|
||||
int rustProp = Shader.PropertyToID("_RustAmount");
|
||||
int colorProp = Shader.PropertyToID("_BaseColor");
|
||||
foreach (Renderer r in GetComponentsInChildren<Renderer>(true))
|
||||
{
|
||||
foreach (Material m in r.sharedMaterials)
|
||||
{
|
||||
if (m != null && m.HasProperty(rustProp) && m.HasProperty(colorProp))
|
||||
return m.GetColor(colorProp);
|
||||
}
|
||||
}
|
||||
return baseCarColor;
|
||||
}
|
||||
|
||||
private static bool IsWheel(CarPart part) => part.GetComponent<CarWheelCondition>() != null || part.TotalBoltsCount > 0 || part.LinkedWheelCollider != null;
|
||||
|
||||
/// <summary>
|
||||
/// Генерирует 100% одинаковое состояние машины для одного и того же seed (и в фотобоксе, и на карте).
|
||||
/// </summary>
|
||||
public void ApplyConditionBySeed(int seed, Color carColor, bool isPhotoStudio, out CarDefectsSummary summary)
|
||||
{
|
||||
configuredExternally = true;
|
||||
|
||||
EngineBayManager bay = GetComponent<EngineBayManager>();
|
||||
if (bay != null) bay.EnsureBuilt();
|
||||
|
||||
Random.State oldState = Random.state;
|
||||
Random.InitState(seed);
|
||||
|
||||
summary = new CarDefectsSummary
|
||||
{
|
||||
missingPartNames = new List<string>()
|
||||
};
|
||||
|
||||
float carDirt = Random.Range(dirtRange.x, dirtRange.y);
|
||||
summary.dirtAmount = carDirt;
|
||||
summary.totalPricePenalty += carDirt * 40f;
|
||||
|
||||
CarPart[] allParts = GetComponentsInChildren<CarPart>(true);
|
||||
|
||||
// 1. Кузовные и навесные детали (кроме колес и подкапотных агрегатов)
|
||||
foreach (CarPart part in allParts)
|
||||
{
|
||||
if (IsWheel(part) || part.GetComponent<EnginePart>() != null)
|
||||
continue;
|
||||
|
||||
CarPartVisuals visuals = part.GetComponent<CarPartVisuals>();
|
||||
if (visuals == null) visuals = part.gameObject.AddComponent<CarPartVisuals>();
|
||||
|
||||
visuals.SetPaintColor(carColor);
|
||||
float partDirt = Mathf.Clamp01(carDirt + Random.Range(-0.1f, 0.1f));
|
||||
|
||||
float partPrice = part.Data != null ? part.Data.basePrice : 150f;
|
||||
string partTitle = part.Data != null ? part.Data.partName : part.name;
|
||||
|
||||
// Проверяем, отсутствует ли эта навесная деталь (бампер, фара, крыло, дверь, зеркало)
|
||||
if (summary.missingBodyPartsCount < maxMissingBodyParts && Random.value < missingBodyPartChance)
|
||||
{
|
||||
summary.missingBodyPartsCount++;
|
||||
summary.missingPartNames.Add(partTitle.ToLower());
|
||||
summary.totalPricePenalty += partPrice * 1.4f;
|
||||
visuals.SetDamage(0f);
|
||||
visuals.SetDirt(0f);
|
||||
part.MakeMissingAtStart(null, false);
|
||||
continue;
|
||||
}
|
||||
|
||||
visuals.SetDirt(partDirt);
|
||||
|
||||
// Пластик не ржавеет
|
||||
if (part.Data != null && !part.Data.canRust)
|
||||
{
|
||||
visuals.SetDamage(0f);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Random.value < rustProbability)
|
||||
{
|
||||
float dmg = Random.Range(minRustAmount, maxRustAmount);
|
||||
visuals.SetDamage(dmg);
|
||||
visuals.SetHiddenRepaint(false);
|
||||
summary.rustedPartsCount++;
|
||||
summary.totalPricePenalty += partPrice * dmg;
|
||||
}
|
||||
else
|
||||
{
|
||||
visuals.SetDamage(0f);
|
||||
bool repainted = Random.value < hiddenRepaintChance;
|
||||
visuals.SetHiddenRepaint(repainted);
|
||||
if (repainted)
|
||||
{
|
||||
summary.hiddenRepaintCount++;
|
||||
summary.totalPricePenalty += partPrice * 0.35f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Основной несъемный кузов (body): ржавеют только крупные панели, не больше 3 очагов на машину
|
||||
int rustProp = Shader.PropertyToID("_RustAmount");
|
||||
List<Renderer> bodyRenderers = new List<Renderer>();
|
||||
foreach (Renderer r in GetComponentsInChildren<Renderer>(true))
|
||||
{
|
||||
if (r.GetComponentInParent<CarPart>(true) != null) continue;
|
||||
foreach (Material m in r.sharedMaterials)
|
||||
{
|
||||
if (m != null && m.HasProperty(rustProp))
|
||||
{
|
||||
bodyRenderers.Add(r);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int bodyRust = 0;
|
||||
foreach (Renderer r in bodyRenderers)
|
||||
{
|
||||
CarPartVisuals bodyVis = r.GetComponent<CarPartVisuals>();
|
||||
if (bodyVis == null) bodyVis = r.gameObject.AddComponent<CarPartVisuals>();
|
||||
bodyVis.SetPaintColor(carColor);
|
||||
bodyVis.SetDirt(Mathf.Clamp01(carDirt + Random.Range(-0.05f, 0.08f)));
|
||||
|
||||
bool large = r.bounds.size.magnitude > 1.2f;
|
||||
float roll = Random.value;
|
||||
float dmgRoll = Random.Range(minRustAmount, maxRustAmount);
|
||||
float bodyDmg = (large && bodyRust < 3 && roll < rustProbability * 0.6f) ? dmgRoll : 0f;
|
||||
bodyVis.SetDamage(bodyDmg);
|
||||
if (bodyDmg > 0.05f)
|
||||
{
|
||||
bodyRust++;
|
||||
summary.rustedPartsCount++;
|
||||
summary.totalPricePenalty += 140f * bodyDmg;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Колеса (Нормальное / Спущенное / Отсутствует)
|
||||
CarWheelCondition[] wheels = GetComponentsInChildren<CarWheelCondition>(true);
|
||||
foreach (CarWheelCondition wheel in wheels)
|
||||
{
|
||||
float roll = Random.value;
|
||||
// В одном объявлении убираем максимум 1 колесо, чтобы машина не висела вся на кирпичах
|
||||
if (roll < missingWheelChance && summary.missingWheelsCount < 1)
|
||||
{
|
||||
summary.missingWheelsCount++;
|
||||
summary.totalPricePenalty += 220f;
|
||||
CarPart wp = wheel.GetComponent<CarPart>();
|
||||
if (wp != null) wp.MakeMissingAtStart(null, !isPhotoStudio);
|
||||
}
|
||||
else if (roll < missingWheelChance + flatTireChance)
|
||||
{
|
||||
summary.flatTiresCount++;
|
||||
summary.totalPricePenalty += 100f;
|
||||
wheel.ApplyState(CarWheelCondition.TireState.Flat);
|
||||
}
|
||||
else
|
||||
{
|
||||
wheel.ApplyState(CarWheelCondition.TireState.Normal);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Подкапотные агрегаты (АКБ, свечи, фильтры, радиатор, генератор)
|
||||
foreach (EnginePart ep in GetComponentsInChildren<EnginePart>(true))
|
||||
{
|
||||
float r1 = Random.value;
|
||||
float r2 = Random.value;
|
||||
float r3 = Random.value;
|
||||
ep.charge = 100f;
|
||||
|
||||
switch (ep.partType)
|
||||
{
|
||||
case EnginePartType.Battery:
|
||||
ep.condition = Mathf.Lerp(40f, 100f, r2);
|
||||
if (r1 < 0.30f)
|
||||
{
|
||||
ep.charge = Mathf.Lerp(4f, 18f, r3);
|
||||
summary.startProblems = true;
|
||||
summary.engineIssuesCount++;
|
||||
summary.totalPricePenalty += 60f;
|
||||
}
|
||||
else ep.charge = Mathf.Lerp(45f, 100f, r3);
|
||||
|
||||
if (r1 > 0.94f && ep.Part != null && ep.Part.State == PartState.Installed)
|
||||
{
|
||||
summary.startProblems = true;
|
||||
summary.engineIssuesCount++;
|
||||
summary.missingPartNames.Add("аккумулятор");
|
||||
summary.totalPricePenalty += 110f;
|
||||
ep.Part.MakeMissingAtStart(null, false);
|
||||
}
|
||||
break;
|
||||
|
||||
case EnginePartType.SparkPlugs:
|
||||
ep.condition = r1 < 0.35f ? Mathf.Lerp(5f, 28f, r2) : Mathf.Lerp(50f, 100f, r2);
|
||||
if (ep.condition < 30f) { summary.startProblems = true; summary.engineIssuesCount++; summary.totalPricePenalty += 45f; }
|
||||
break;
|
||||
|
||||
case EnginePartType.AirFilter:
|
||||
ep.condition = r1 < 0.40f ? Mathf.Lerp(5f, 28f, r2) : Mathf.Lerp(40f, 100f, r2);
|
||||
if (ep.condition < 30f) { summary.engineIssuesCount++; summary.totalPricePenalty += 20f; }
|
||||
break;
|
||||
|
||||
case EnginePartType.Radiator:
|
||||
ep.condition = r1 < 0.20f ? Mathf.Lerp(10f, 28f, r2) : Mathf.Lerp(50f, 100f, r2);
|
||||
if (ep.condition < 30f) { summary.overheatProblems = true; summary.engineIssuesCount++; summary.totalPricePenalty += 120f; }
|
||||
break;
|
||||
|
||||
case EnginePartType.Alternator:
|
||||
ep.condition = r1 < 0.15f ? Mathf.Lerp(5f, 25f, r2) : Mathf.Lerp(50f, 100f, r2);
|
||||
if (ep.condition < 30f) { summary.startProblems = true; summary.engineIssuesCount++; summary.totalPricePenalty += 130f; }
|
||||
break;
|
||||
|
||||
default:
|
||||
ep.condition = Mathf.Lerp(10f, 100f, r2);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Технические жидкости под капотом (масло, антифриз, тормозная, омывайка)
|
||||
CarFluids fluids = GetComponent<CarFluids>();
|
||||
if (fluids != null)
|
||||
{
|
||||
fluids.SetRandomLevels(0.20f, 0.70f);
|
||||
if (fluids.EngineOil.FillPercent < 0.50f || fluids.EngineOil.quality < 0.3f)
|
||||
{
|
||||
summary.lowFluidsCount++;
|
||||
summary.oilProblems = true;
|
||||
summary.totalPricePenalty += 60f;
|
||||
}
|
||||
if (fluids.Coolant.FillPercent < 0.50f)
|
||||
{
|
||||
summary.lowFluidsCount++;
|
||||
summary.overheatProblems |= fluids.Coolant.FillPercent < 0.25f;
|
||||
summary.totalPricePenalty += 50f;
|
||||
}
|
||||
if (fluids.BrakeFluid.FillPercent < 0.30f)
|
||||
{
|
||||
summary.lowFluidsCount++;
|
||||
summary.brakeProblems = true;
|
||||
summary.totalPricePenalty += 30f;
|
||||
}
|
||||
if (fluids.WasherFluid.FillPercent < 0.25f)
|
||||
{
|
||||
summary.lowFluidsCount++;
|
||||
summary.totalPricePenalty += 10f;
|
||||
}
|
||||
}
|
||||
|
||||
Random.state = oldState;
|
||||
LastSummary = summary;
|
||||
}
|
||||
|
||||
/// <summary>Идеальное состояние (используется для отладки и демонстрации).</summary>
|
||||
[ContextMenu("Сделать машину новой")]
|
||||
public void MakePristine()
|
||||
{
|
||||
configuredExternally = true;
|
||||
foreach (CarPartVisuals v in GetComponentsInChildren<CarPartVisuals>(true))
|
||||
{
|
||||
v.SetDamage(0f);
|
||||
v.SetDirt(0f);
|
||||
v.SetHiddenRepaint(false);
|
||||
}
|
||||
foreach (CarWheelCondition w in GetComponentsInChildren<CarWheelCondition>(true))
|
||||
w.ApplyState(CarWheelCondition.TireState.Normal);
|
||||
foreach (EnginePart ep in GetComponentsInChildren<EnginePart>(true))
|
||||
ep.SetAsNew();
|
||||
CarFluids f = GetComponent<CarFluids>();
|
||||
if (f != null) f.FillAllFresh();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 598fbcd97cc34477934893a1802ce999
|
||||
timeCreated: 1791330530
|
||||
@@ -0,0 +1,180 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Анализирует геометрию кузовных деталей (двери, капот, багажник, крылья)
|
||||
/// и запекает веса торцов и кромок в цвета вершин (Mesh.colors),
|
||||
/// чтобы ржавчина реалистично зарождалась на торцах и швах.
|
||||
/// </summary>
|
||||
public static class CarPartMeshEdgeAnalyzer
|
||||
{
|
||||
private static readonly Dictionary<string, Color[]> vertexColorCache = new Dictionary<string, Color[]>();
|
||||
|
||||
public static void ApplyEdgeColorsToMesh(MeshFilter filter, string partNameHint = "")
|
||||
{
|
||||
if (filter == null || filter.sharedMesh == null) return;
|
||||
|
||||
Mesh shared = filter.sharedMesh;
|
||||
int vertexCount = shared.vertexCount;
|
||||
if (vertexCount == 0) return;
|
||||
|
||||
string cacheKey = $"{shared.name}_{vertexCount}";
|
||||
|
||||
Color[] colors;
|
||||
if (!vertexColorCache.TryGetValue(cacheKey, out colors) || colors == null || colors.Length != vertexCount)
|
||||
{
|
||||
colors = CalculateEdgeColors(shared, partNameHint);
|
||||
vertexColorCache[cacheKey] = colors;
|
||||
}
|
||||
|
||||
// Если в sharedMesh еще нет цветов, или если мы в рантайме создаем экземпляр
|
||||
if (shared.colors == null || shared.colors.Length != vertexCount)
|
||||
{
|
||||
// Клонируем меш для инстанса, чтобы не портить исходный asset на диске
|
||||
Mesh instanceMesh = Object.Instantiate(shared);
|
||||
instanceMesh.name = shared.name + "_EdgeColored";
|
||||
instanceMesh.colors = colors;
|
||||
filter.sharedMesh = instanceMesh;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Если уже инстанс — просто присваиваем
|
||||
filter.sharedMesh.colors = colors;
|
||||
}
|
||||
}
|
||||
|
||||
private static Color[] CalculateEdgeColors(Mesh mesh, string partName)
|
||||
{
|
||||
Vector3[] vertices = mesh.vertices;
|
||||
Vector3[] normals = mesh.normals;
|
||||
int[] triangles = mesh.triangles;
|
||||
int vCount = vertices.Length;
|
||||
|
||||
Color[] colors = new Color[vCount];
|
||||
if (triangles == null || triangles.Length < 3)
|
||||
{
|
||||
for (int i = 0; i < vCount; i++) colors[i] = Color.black;
|
||||
return colors;
|
||||
}
|
||||
|
||||
Bounds bounds = mesh.bounds;
|
||||
Vector3 bMin = bounds.min;
|
||||
Vector3 bMax = bounds.max;
|
||||
Vector3 bSize = bounds.size;
|
||||
|
||||
// 1. Поиск граничных ребер (Boundary Edges) — ребра, принадлежащие только 1 треугольнику
|
||||
Dictionary<long, int> edgeUsage = new Dictionary<long, int>(triangles.Length);
|
||||
for (int i = 0; i < triangles.Length; i += 3)
|
||||
{
|
||||
int i0 = triangles[i];
|
||||
int i1 = triangles[i + 1];
|
||||
int i2 = triangles[i + 2];
|
||||
|
||||
AddEdge(edgeUsage, i0, i1);
|
||||
AddEdge(edgeUsage, i1, i2);
|
||||
AddEdge(edgeUsage, i2, i0);
|
||||
}
|
||||
|
||||
HashSet<int> boundaryVertices = new HashSet<int>();
|
||||
foreach (var kvp in edgeUsage)
|
||||
{
|
||||
if (kvp.Value == 1) // Ребро лежит на открытом торце / кромке металла
|
||||
{
|
||||
int v0 = (int)(kvp.Key >> 32);
|
||||
int v1 = (int)(kvp.Key & 0xFFFFFFFF);
|
||||
boundaryVertices.Add(v0);
|
||||
boundaryVertices.Add(v1);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Оптимизированный расчет расстояния от каждой вершины до ближайшего торца
|
||||
// Для деталей авто ширина зоны распространения ржавчины от торца: 8-12 см
|
||||
float maxEdgeDist = Mathf.Max(0.08f, Mathf.Min(bSize.x, Mathf.Min(bSize.y, bSize.z)) * 0.45f);
|
||||
|
||||
List<Vector3> boundaryPoints = new List<Vector3>(boundaryVertices.Count);
|
||||
foreach (int idx in boundaryVertices)
|
||||
{
|
||||
boundaryPoints.Add(vertices[idx]);
|
||||
}
|
||||
|
||||
bool hasBoundary = boundaryPoints.Count > 0;
|
||||
|
||||
string lowerName = partName.ToLowerInvariant();
|
||||
bool isDoor = lowerName.Contains("door");
|
||||
bool isFender = lowerName.Contains("fender") || lowerName.Contains("wing");
|
||||
bool isHood = lowerName.Contains("hood");
|
||||
bool isTrunk = lowerName.Contains("trunk") || lowerName.Contains("tailgate");
|
||||
|
||||
for (int i = 0; i < vCount; i++)
|
||||
{
|
||||
Vector3 p = vertices[i];
|
||||
|
||||
// Фактор расстояния до геометрического торца меша
|
||||
float edgeDist = float.MaxValue;
|
||||
if (hasBoundary)
|
||||
{
|
||||
// Ищем ближайшую точку торца
|
||||
for (int b = 0; b < boundaryPoints.Count; b++)
|
||||
{
|
||||
float sqr = (p - boundaryPoints[b]).sqrMagnitude;
|
||||
if (sqr < edgeDist) edgeDist = sqr;
|
||||
if (sqr < 0.0004f) break; // Ближе 2 см — точно торец
|
||||
}
|
||||
edgeDist = Mathf.Sqrt(edgeDist);
|
||||
}
|
||||
|
||||
float boundaryWeight = hasBoundary ? Mathf.Clamp01(1f - (edgeDist / maxEdgeDist)) : 0f;
|
||||
|
||||
// Фактор нижней кромки (пороги, низ дверей, нижние углы крыльев)
|
||||
// Вода и дорожная соль стекают вниз: нижние 10-15% высоты детали ржавеют сильнее всего
|
||||
float relY = (bSize.y > 0.001f) ? Mathf.Clamp01((p.y - bMin.y) / bSize.y) : 0f;
|
||||
float bottomWeight = Mathf.Clamp01(1f - (relY / 0.18f));
|
||||
|
||||
// Фактор периметра габаритов (для капота — передняя кромка, для багажника — задний торец)
|
||||
float perimeterWeight = 0f;
|
||||
if (isDoor)
|
||||
{
|
||||
// На дверях ржавчина сильнее всего на нижней кромке (hem flange) и переднем/заднем торцах
|
||||
perimeterWeight = bottomWeight * 0.85f + boundaryWeight * 0.75f;
|
||||
}
|
||||
else if (isFender)
|
||||
{
|
||||
// На крыльях ржавчина по кромке колесной арки и внизу у брызговика
|
||||
perimeterWeight = boundaryWeight * 0.85f + bottomWeight * 0.65f;
|
||||
}
|
||||
else if (isHood)
|
||||
{
|
||||
// На капоте сильнее всего передний торец от сколов камней
|
||||
float relZ = (bSize.z > 0.001f) ? Mathf.Clamp01((p.z - bMin.z) / bSize.z) : 0f;
|
||||
float frontLip = Mathf.Clamp01(1f - (relZ / 0.20f));
|
||||
perimeterWeight = frontLip * 0.85f + boundaryWeight * 0.65f;
|
||||
}
|
||||
else if (isTrunk)
|
||||
{
|
||||
// На багажнике — нижний и задний край
|
||||
float rearLip = bottomWeight;
|
||||
perimeterWeight = rearLip * 0.85f + boundaryWeight * 0.65f;
|
||||
}
|
||||
else
|
||||
{
|
||||
perimeterWeight = Mathf.Max(boundaryWeight, bottomWeight * 0.7f);
|
||||
}
|
||||
|
||||
// Итоговый вес: 1.0 на торцах, плавно спадает к 0 в центре детали
|
||||
float finalEdgeFactor = Mathf.Clamp01(perimeterWeight);
|
||||
|
||||
colors[i] = new Color(finalEdgeFactor, bottomWeight, boundaryWeight, 1f);
|
||||
}
|
||||
|
||||
return colors;
|
||||
}
|
||||
|
||||
private static void AddEdge(Dictionary<long, int> dict, int a, int b)
|
||||
{
|
||||
int min = Mathf.Min(a, b);
|
||||
int max = Mathf.Max(a, b);
|
||||
long key = ((long)min << 32) | (long)(uint)max;
|
||||
if (!dict.ContainsKey(key)) dict[key] = 0;
|
||||
dict[key]++;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bc9438d09442eea48993b97d16b13579
|
||||
@@ -0,0 +1,331 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public enum RepairStage
|
||||
{
|
||||
Healthy, Rusted, Cleaned, Puttied, Sanded, Repaired
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Визуальное состояние кузовной детали через MaterialPropertyBlock (без дублирования материалов):
|
||||
/// родной цвет, ржавчина, шпаклевка, шлифовка, покраска и слой дорожной грязи (dirtAmount).
|
||||
/// </summary>
|
||||
[DisallowMultipleComponent]
|
||||
public class CarPartVisuals : MonoBehaviour
|
||||
{
|
||||
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 SmoothnessProp = Shader.PropertyToID("_PaintSmoothness");
|
||||
|
||||
private const float DoneThreshold = 0.98f;
|
||||
private const float RustCleanThreshold = 0.02f;
|
||||
public const float DirtyThreshold = 0.1f;
|
||||
|
||||
private static readonly Color DirtColor = new Color(0.36f, 0.31f, 0.24f);
|
||||
|
||||
[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;
|
||||
[SerializeField] private Color paintColor = Color.white;
|
||||
|
||||
[Header("Грязь и ЛКП")]
|
||||
[Range(0f, 1f)] [SerializeField] private float dirtAmount;
|
||||
[Tooltip("Деталь была перекрашена прошлым владельцем (толщиномер покажет 250–450 мкм)")]
|
||||
[SerializeField] private bool hiddenRepaint;
|
||||
|
||||
private struct Slot
|
||||
{
|
||||
public Renderer renderer;
|
||||
public int materialIndex;
|
||||
}
|
||||
|
||||
private readonly List<Slot> slots = new List<Slot>();
|
||||
private readonly List<Slot> dirtSlots = new List<Slot>();
|
||||
private MaterialPropertyBlock dirtBlock;
|
||||
private MaterialPropertyBlock block;
|
||||
private bool initialized;
|
||||
private bool colorInitialized;
|
||||
private float baseSmoothness = 0.8f;
|
||||
|
||||
public float CurrentRust => rustCurrent;
|
||||
public float InitialRust => rustInitial;
|
||||
public Color CurrentColor => paintColor;
|
||||
public float DirtAmount => dirtAmount;
|
||||
public bool IsDirty => dirtAmount > DirtyThreshold;
|
||||
public bool HiddenRepaint => hiddenRepaint;
|
||||
public bool HasPaintSlots { get { EnsureInit(); return slots.Count > 0; } }
|
||||
public bool IsMainBody => GetComponent<CarPart>() == null;
|
||||
|
||||
public RepairStage Stage
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Толщина ЛКП в микронах для толщиномера (стабильная для конкретной детали).</summary>
|
||||
public int PaintThicknessMicrons
|
||||
{
|
||||
get
|
||||
{
|
||||
int h = Mathf.Abs(gameObject.name.GetHashCode());
|
||||
float jitter = (h % 100) / 100f;
|
||||
switch (Stage)
|
||||
{
|
||||
case RepairStage.Rusted: return Mathf.RoundToInt(Mathf.Lerp(40f, 80f, jitter));
|
||||
case RepairStage.Cleaned: return 0;
|
||||
case RepairStage.Puttied:
|
||||
case RepairStage.Sanded: return Mathf.RoundToInt(Mathf.Lerp(600f, 900f, jitter));
|
||||
case RepairStage.Repaired: return Mathf.RoundToInt(Mathf.Lerp(250f, 450f, jitter));
|
||||
default:
|
||||
return hiddenRepaint ? Mathf.RoundToInt(Mathf.Lerp(250f, 450f, jitter)) : Mathf.RoundToInt(Mathf.Lerp(95f, 120f, jitter));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
// Основной кузов (без CarPart) не забирает рендеры съемных деталей
|
||||
if (owner == null && r.GetComponentInParent<CarPart>(true) != null) continue;
|
||||
if (owner == null && r.GetComponent<CarPartVisuals>() != null && r.gameObject != gameObject) 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;
|
||||
}
|
||||
if (mats[i].HasProperty(SmoothnessProp))
|
||||
baseSmoothness = mats[i].GetFloat(SmoothnessProp);
|
||||
|
||||
slots.Add(new Slot { renderer = r, materialIndex = i });
|
||||
AddDirtOverlay(r);
|
||||
|
||||
MeshFilter mf = r.GetComponent<MeshFilter>();
|
||||
if (mf != null)
|
||||
{
|
||||
CarPartMeshEdgeAnalyzer.ApplyEdgeColorsToMesh(mf, gameObject.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Слой дорожной грязи: полупрозрачная текстура поверх краски на том же меше.
|
||||
/// Её непрозрачность (= dirtAmount) задается через MaterialPropertyBlock, мойка смывает её до 0.
|
||||
/// </summary>
|
||||
private void AddDirtOverlay(Renderer r)
|
||||
{
|
||||
if (!Application.isPlaying) return;
|
||||
foreach (Slot d in dirtSlots) if (d.renderer == r) return;
|
||||
Material overlay = PartCatalog.DirtOverlayMaterial;
|
||||
if (overlay == null) return;
|
||||
|
||||
Material[] mats = r.sharedMaterials;
|
||||
foreach (Material m in mats) if (m == overlay) return;
|
||||
Material[] extended = new Material[mats.Length + 1];
|
||||
mats.CopyTo(extended, 0);
|
||||
extended[mats.Length] = overlay;
|
||||
r.sharedMaterials = extended;
|
||||
dirtSlots.Add(new Slot { renderer = r, materialIndex = mats.Length });
|
||||
}
|
||||
|
||||
private void OnValidate()
|
||||
{
|
||||
if (Application.isPlaying && initialized) Apply();
|
||||
}
|
||||
|
||||
public void SetDamage(float amount)
|
||||
{
|
||||
EnsureInit();
|
||||
amount = Mathf.Clamp01(amount);
|
||||
if (amount <= 0.001f) amount = 0f;
|
||||
|
||||
rustInitial = amount;
|
||||
rustCurrent = amount;
|
||||
putty = 0f;
|
||||
sanding = 0f;
|
||||
paint = 0f;
|
||||
Apply();
|
||||
}
|
||||
|
||||
public void SetDirt(float amount)
|
||||
{
|
||||
EnsureInit();
|
||||
dirtAmount = Mathf.Clamp01(amount);
|
||||
Apply();
|
||||
}
|
||||
|
||||
public void SetHiddenRepaint(bool value) => hiddenRepaint = value;
|
||||
|
||||
/// <summary>Мойка высокого давления: снижает слой грязи.</summary>
|
||||
public bool Wash(float amount01)
|
||||
{
|
||||
if (dirtAmount <= 0f) return false;
|
||||
dirtAmount = Mathf.Max(0f, dirtAmount - amount01);
|
||||
if (dirtAmount < 0.01f) dirtAmount = 0f;
|
||||
Apply();
|
||||
return true;
|
||||
}
|
||||
|
||||
public void SetPaintColor(Color newColor)
|
||||
{
|
||||
EnsureInit();
|
||||
paintColor = newColor;
|
||||
colorInitialized = true;
|
||||
Apply();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public bool Recolor(Color newColor)
|
||||
{
|
||||
RepairStage s = Stage;
|
||||
if (s != RepairStage.Healthy && s != RepairStage.Repaired) return false;
|
||||
SetPaintColor(newColor);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Apply()
|
||||
{
|
||||
EnsureInit();
|
||||
// Грязь приглушает родной цвет землисто-серым матовым налетом и снижает гладкость
|
||||
Color shown = Color.Lerp(paintColor, DirtColor, dirtAmount * (dirtSlots.Count > 0 ? 0.35f : 0.82f));
|
||||
float smooth = Mathf.Lerp(baseSmoothness, 0.05f, dirtAmount);
|
||||
|
||||
foreach (Slot s in slots)
|
||||
{
|
||||
if (s.renderer == null) continue;
|
||||
s.renderer.GetPropertyBlock(block, s.materialIndex);
|
||||
block.SetColor(BaseColorProp, shown);
|
||||
block.SetFloat(RustInitialProp, rustInitial);
|
||||
block.SetFloat(RustAmountProp, rustCurrent);
|
||||
block.SetFloat(PuttyProp, putty);
|
||||
block.SetFloat(SandProp, sanding);
|
||||
block.SetFloat(PaintProp, paint);
|
||||
block.SetFloat(SmoothnessProp, smooth);
|
||||
s.renderer.SetPropertyBlock(block, s.materialIndex);
|
||||
}
|
||||
|
||||
if (dirtSlots.Count > 0)
|
||||
{
|
||||
if (dirtBlock == null) dirtBlock = new MaterialPropertyBlock();
|
||||
foreach (Slot d in dirtSlots)
|
||||
{
|
||||
if (d.renderer == null) continue;
|
||||
d.renderer.GetPropertyBlock(dirtBlock, d.materialIndex);
|
||||
dirtBlock.SetColor(BaseColorProp, new Color(1f, 1f, 1f, Mathf.Clamp01(dirtAmount * 1.05f)));
|
||||
d.renderer.SetPropertyBlock(dirtBlock, d.materialIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Находит обрабатываемую поверхность по точке попадания луча: сначала деталь под лучом,
|
||||
/// иначе ближайший к точке рендер основного несъемного кузова этой машины.
|
||||
/// </summary>
|
||||
public static CarPartVisuals FindAt(Collider hitCollider, Vector3 hitPoint)
|
||||
{
|
||||
if (hitCollider == null) return null;
|
||||
CarPartVisuals direct = hitCollider.GetComponentInParent<CarPartVisuals>();
|
||||
CarPart directPart = hitCollider.GetComponentInParent<CarPart>();
|
||||
if (direct != null && (directPart == null || direct.GetComponent<CarPart>() == directPart))
|
||||
return direct;
|
||||
if (directPart != null) return directPart.GetComponent<CarPartVisuals>();
|
||||
|
||||
VehicleInteraction car = hitCollider.GetComponentInParent<VehicleInteraction>();
|
||||
if (car == null) return direct;
|
||||
|
||||
CarPartVisuals best = null;
|
||||
float bestDist = float.MaxValue;
|
||||
foreach (CarPartVisuals v in car.GetComponentsInChildren<CarPartVisuals>())
|
||||
{
|
||||
if (!v.IsMainBody || !v.HasPaintSlots) continue;
|
||||
Renderer r = v.GetComponent<Renderer>();
|
||||
float d = r != null ? r.bounds.SqrDistance(hitPoint) : (v.transform.position - hitPoint).sqrMagnitude;
|
||||
if (d < bestDist)
|
||||
{
|
||||
bestDist = d;
|
||||
best = v;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: de28a2301d654322a1a3aa450e964901
|
||||
timeCreated: 1791330380
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1856babf52f5f4943bc3427cdc59f158
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,180 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public enum GameMode { None, Career, Free }
|
||||
|
||||
/// <summary>
|
||||
/// Главный менеджер игры и экономики перекупа.
|
||||
/// isDiplomaVersion = true — «Дипломный проект»: бюджет, ДВС и жидкости, диагностика, торг, магазин, склад «Куфар», продажа с прибылью.
|
||||
/// isDiplomaVersion = false — «Курсовая работа»: авторынок, GPS, мойка, колеса с домкратом, кузовной ремонт и тест-драйв.
|
||||
/// </summary>
|
||||
public class GameEconomyManager : MonoBehaviour
|
||||
{
|
||||
public static GameEconomyManager Instance { get; private set; }
|
||||
|
||||
[Header("Версия проекта")]
|
||||
[Tooltip("true — полный Дипломный проект, false — базовая Курсовая работа")]
|
||||
public bool isDiplomaVersion = true;
|
||||
|
||||
[Header("Экономика")]
|
||||
[SerializeField] private float startCapitalUsd = 5000f;
|
||||
[SerializeField] private float bynPerUsd = 3.27f;
|
||||
[SerializeField] private float autosalonGoalUsd = 25000f;
|
||||
|
||||
[Header("Гараж игрока")]
|
||||
public Transform garageCenter;
|
||||
public float garageRadius = 24f;
|
||||
public Transform garageCarSpot;
|
||||
public Transform deliveryPoint;
|
||||
public Transform playerSpawnPoint;
|
||||
|
||||
public GameMode Mode { get; private set; } = GameMode.None;
|
||||
public float Money { get; private set; }
|
||||
public int DealsCompleted { get; private set; }
|
||||
public float TotalProfit { get; private set; }
|
||||
public bool AutosalonOpened { get; private set; }
|
||||
public float AutosalonGoal => autosalonGoalUsd;
|
||||
public float StartCapital => startCapitalUsd;
|
||||
|
||||
/// <summary>Свободный режим: деньги не ограничены.</summary>
|
||||
public bool Unlimited => Mode != GameMode.Career;
|
||||
public bool DiplomaFeatures => isDiplomaVersion;
|
||||
|
||||
public event Action<float> OnMoneyChanged;
|
||||
public event Action OnAutosalonOpened;
|
||||
|
||||
private readonly List<string> history = new List<string>();
|
||||
public IReadOnlyList<string> History => history;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (Instance != null && Instance != this)
|
||||
{
|
||||
Destroy(this);
|
||||
return;
|
||||
}
|
||||
Instance = this;
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (Instance == this) Instance = null;
|
||||
}
|
||||
|
||||
public void StartGame(GameMode mode)
|
||||
{
|
||||
Mode = mode;
|
||||
Money = mode == GameMode.Career ? startCapitalUsd : 0f;
|
||||
DealsCompleted = 0;
|
||||
TotalProfit = 0f;
|
||||
AutosalonOpened = false;
|
||||
history.Clear();
|
||||
OnMoneyChanged?.Invoke(Money);
|
||||
}
|
||||
|
||||
public string FormatMoney(float usd)
|
||||
{
|
||||
string sign = usd < 0 ? "-" : "";
|
||||
float a = Mathf.Abs(usd);
|
||||
return $"{sign}${a:N0} ({sign}{a * bynPerUsd:N0} BYN)";
|
||||
}
|
||||
|
||||
public string FormatShort(float usd) => (usd < 0 ? "-$" : "$") + Mathf.Abs(usd).ToString("N0");
|
||||
|
||||
public bool CanAfford(float usd) => Unlimited || Money + 0.01f >= usd;
|
||||
|
||||
/// <summary>Списать деньги. Затраты автоматически записываются на машину (для отчета о прибыли).</summary>
|
||||
public bool TrySpend(float usd, string reason, CarOwnership forCar = null, bool attributeToCar = true)
|
||||
{
|
||||
if (usd <= 0f) return true;
|
||||
if (!CanAfford(usd))
|
||||
{
|
||||
GameHUD.Notify($"Недостаточно средств! Нужно {FormatShort(usd)}, на счету {FormatShort(Money)}", GameUI.Red);
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!Unlimited)
|
||||
{
|
||||
Money -= usd;
|
||||
OnMoneyChanged?.Invoke(Money);
|
||||
}
|
||||
|
||||
if (attributeToCar)
|
||||
{
|
||||
if (forCar == null) forCar = FindCarForExpense();
|
||||
if (forCar != null) forCar.AddExpense(usd, reason);
|
||||
}
|
||||
|
||||
history.Add($"−{FormatShort(usd)} {reason}");
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.Cash);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Earn(float usd, string reason)
|
||||
{
|
||||
if (usd <= 0f) return;
|
||||
if (!Unlimited)
|
||||
{
|
||||
Money += usd;
|
||||
OnMoneyChanged?.Invoke(Money);
|
||||
}
|
||||
history.Add($"+{FormatShort(usd)} {reason}");
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.Cash);
|
||||
CheckAutosalonGoal();
|
||||
}
|
||||
|
||||
public void RegisterDeal(float profit)
|
||||
{
|
||||
DealsCompleted++;
|
||||
TotalProfit += profit;
|
||||
CheckAutosalonGoal();
|
||||
}
|
||||
|
||||
private void CheckAutosalonGoal()
|
||||
{
|
||||
if (AutosalonOpened || Mode != GameMode.Career) return;
|
||||
if (Money >= autosalonGoalUsd)
|
||||
{
|
||||
AutosalonOpened = true;
|
||||
OnAutosalonOpened?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsInGarage(Vector3 worldPos)
|
||||
{
|
||||
if (garageCenter == null) return true;
|
||||
Vector3 d = worldPos - garageCenter.position;
|
||||
d.y = 0f;
|
||||
return d.magnitude <= garageRadius;
|
||||
}
|
||||
|
||||
/// <summary>Машина игрока, на которую списываются расходы (ближайшая к гаражу купленная).</summary>
|
||||
public CarOwnership FindCarForExpense()
|
||||
{
|
||||
CarOwnership best = null;
|
||||
float bestDist = float.MaxValue;
|
||||
Vector3 center = garageCenter != null ? garageCenter.position : Vector3.zero;
|
||||
|
||||
foreach (CarOwnership c in CarOwnership.All)
|
||||
{
|
||||
if (c == null || !c.isOwned) continue;
|
||||
float d = Vector3.Distance(c.transform.position, center);
|
||||
if (d < bestDist)
|
||||
{
|
||||
bestDist = d;
|
||||
best = c;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
public Vector3 GetDeliveryPosition(int index = 0)
|
||||
{
|
||||
Vector3 basePos = deliveryPoint != null ? deliveryPoint.position : (garageCenter != null ? garageCenter.position + Vector3.up : Vector3.up);
|
||||
Vector3 right = deliveryPoint != null ? deliveryPoint.right : Vector3.right;
|
||||
int slot = index % 5;
|
||||
return basePos + right * ((slot - 2) * 0.45f) + Vector3.up * (0.25f + (index / 5) * 0.35f);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8f574617d139dfa43963e53d3955d024
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Единая блокировка управления игроком при открытых окнах (меню, планшет, торг, склад, радиальное меню).
|
||||
/// Пока хотя бы одно окно держит блокировку — курсор свободен, а ходьба, обзор, луч и инструменты отключены.
|
||||
/// </summary>
|
||||
public static class GameInputLock
|
||||
{
|
||||
private static readonly HashSet<object> owners = new HashSet<object>();
|
||||
|
||||
public static bool IsLocked => owners.Count > 0;
|
||||
|
||||
/// <summary>Кадр, в котором было закрыто последнее окно (чтобы Esc не открывал паузу в том же кадре).</summary>
|
||||
public static int LastUnlockFrame { get; private set; } = -1;
|
||||
public static bool WasJustUnlocked => LastUnlockFrame == Time.frameCount || LastUnlockFrame == Time.frameCount - 1;
|
||||
|
||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
|
||||
private static void ResetStatics()
|
||||
{
|
||||
owners.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Сброс при загрузке сцены (окна прошлой сцены уничтожены).</summary>
|
||||
public static void ClearAll()
|
||||
{
|
||||
owners.Clear();
|
||||
ApplyCursor();
|
||||
}
|
||||
|
||||
public static bool IsLockedBy(object owner) => owner != null && owners.Contains(owner);
|
||||
|
||||
/// <summary>Заблокирован ли ввод кем-то кроме указанного владельца.</summary>
|
||||
public static bool IsLockedByOther(object owner)
|
||||
{
|
||||
if (owners.Count == 0) return false;
|
||||
if (owners.Count == 1 && owner != null && owners.Contains(owner)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void Set(object owner, bool locked)
|
||||
{
|
||||
if (owner == null) return;
|
||||
bool changed = locked ? owners.Add(owner) : owners.Remove(owner);
|
||||
if (changed && !locked) LastUnlockFrame = Time.frameCount;
|
||||
if (changed) ApplyCursor();
|
||||
}
|
||||
|
||||
public static void Lock(object owner) => Set(owner, true);
|
||||
public static void Unlock(object owner) => Set(owner, false);
|
||||
|
||||
public static void ApplyCursor()
|
||||
{
|
||||
Cursor.lockState = IsLocked ? CursorLockMode.None : CursorLockMode.Locked;
|
||||
Cursor.visible = IsLocked;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3f9215cff0aeb7d4b954a9f41519c9a0
|
||||
@@ -0,0 +1,206 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Общий стиль резервного интерфейса OnGUI (асфальтово-индустриальная палитра #16181D).
|
||||
/// Все окна рисуются в виртуальном разрешении высотой 1080 px и масштабируются под любой экран,
|
||||
/// поэтому интерфейс гарантированно отображается даже при пустых ссылках в Инспекторе.
|
||||
/// </summary>
|
||||
public static class GameUI
|
||||
{
|
||||
public const float RefHeight = 1080f;
|
||||
|
||||
public static readonly Color Bg = Hex("16181D");
|
||||
public static readonly Color PanelColor = Hex("1E2128");
|
||||
public static readonly Color PanelLight = Hex("2A2E37");
|
||||
public static readonly Color Accent = Hex("F2A93B");
|
||||
public static readonly Color Green = Hex("4CD07D");
|
||||
public static readonly Color Red = Hex("E5534B");
|
||||
public static readonly Color Blue = Hex("4FA3F7");
|
||||
public static readonly Color TextColor = Hex("E8E9EB");
|
||||
public static readonly Color Muted = Hex("9AA0A6");
|
||||
|
||||
private static bool initialized;
|
||||
private static readonly Dictionary<string, Texture2D> texCache = new Dictionary<string, Texture2D>();
|
||||
|
||||
public static GUIStyle Panel, PanelSolid, Title, Header, Label, LabelCenter, Small, SmallCenter, Button, ButtonAccent, ButtonDanger, ButtonTab, ButtonTabActive, Badge;
|
||||
|
||||
public static float Scale => Screen.height / RefHeight;
|
||||
public static float VirtualWidth => Screen.width / Mathf.Max(Scale, 0.01f);
|
||||
public static float VirtualHeight => RefHeight;
|
||||
|
||||
public static Color Hex(string hex)
|
||||
{
|
||||
ColorUtility.TryParseHtmlString("#" + hex, out Color c);
|
||||
return c;
|
||||
}
|
||||
|
||||
/// <summary>Вызывать в начале каждого OnGUI: включает масштабирование и стили.</summary>
|
||||
public static void Begin(int depth = 0)
|
||||
{
|
||||
EnsureStyles();
|
||||
GUI.depth = depth;
|
||||
float s = Scale;
|
||||
GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(s, s, 1f));
|
||||
}
|
||||
|
||||
public static Vector2 MouseVirtual()
|
||||
{
|
||||
Vector2 m = Event.current != null ? Event.current.mousePosition : Vector2.zero;
|
||||
return m;
|
||||
}
|
||||
|
||||
private static void EnsureStyles()
|
||||
{
|
||||
if (initialized && Panel != null && Panel.normal.background != null) return;
|
||||
initialized = true;
|
||||
|
||||
Panel = new GUIStyle(GUI.skin.box)
|
||||
{
|
||||
normal = { background = Rounded(PanelColor.WithAlpha(0.96f), Hex("3A3F4A"), 12, 2) },
|
||||
border = new RectOffset(14, 14, 14, 14),
|
||||
padding = new RectOffset(20, 20, 18, 18)
|
||||
};
|
||||
|
||||
PanelSolid = new GUIStyle(Panel)
|
||||
{
|
||||
normal = { background = Rounded(Bg, Hex("2F333C"), 12, 2) }
|
||||
};
|
||||
|
||||
Badge = new GUIStyle(GUI.skin.box)
|
||||
{
|
||||
normal = { background = Rounded(Hex("101216").WithAlpha(0.82f), Hex("2F333C"), 10, 1), textColor = TextColor },
|
||||
border = new RectOffset(12, 12, 12, 12),
|
||||
padding = new RectOffset(12, 12, 6, 6),
|
||||
fontSize = 18,
|
||||
alignment = TextAnchor.MiddleLeft,
|
||||
richText = true
|
||||
};
|
||||
|
||||
Title = new GUIStyle(GUI.skin.label)
|
||||
{
|
||||
fontSize = 42, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter,
|
||||
normal = { textColor = TextColor }, richText = true, wordWrap = true
|
||||
};
|
||||
|
||||
Header = new GUIStyle(GUI.skin.label)
|
||||
{
|
||||
fontSize = 26, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleLeft,
|
||||
normal = { textColor = Accent }, richText = true, wordWrap = true
|
||||
};
|
||||
|
||||
Label = new GUIStyle(GUI.skin.label)
|
||||
{
|
||||
fontSize = 19, alignment = TextAnchor.UpperLeft, wordWrap = true, richText = true,
|
||||
normal = { textColor = TextColor }
|
||||
};
|
||||
|
||||
LabelCenter = new GUIStyle(Label) { alignment = TextAnchor.MiddleCenter };
|
||||
|
||||
Small = new GUIStyle(Label) { fontSize = 16, normal = { textColor = Muted } };
|
||||
SmallCenter = new GUIStyle(Small) { alignment = TextAnchor.MiddleCenter };
|
||||
|
||||
Button = MakeButton(Hex("2E333D"), Hex("3B414D"), Hex("4A5160"), TextColor);
|
||||
ButtonAccent = MakeButton(Hex("C9862A"), Accent, Hex("FFC266"), Hex("16181D"));
|
||||
ButtonDanger = MakeButton(Hex("8E2F2A"), Red, Hex("FF7A70"), Color.white);
|
||||
ButtonTab = MakeButton(Hex("23262E"), Hex("2E333D"), Hex("3B414D"), Muted);
|
||||
ButtonTabActive = MakeButton(Hex("3B414D"), Hex("444B59"), Hex("4A5160"), Accent);
|
||||
}
|
||||
|
||||
private static GUIStyle MakeButton(Color normal, Color hover, Color active, Color text)
|
||||
{
|
||||
return new GUIStyle(GUI.skin.button)
|
||||
{
|
||||
fontSize = 19,
|
||||
fontStyle = FontStyle.Bold,
|
||||
alignment = TextAnchor.MiddleCenter,
|
||||
wordWrap = true,
|
||||
richText = true,
|
||||
border = new RectOffset(10, 10, 10, 10),
|
||||
padding = new RectOffset(12, 12, 6, 6),
|
||||
normal = { background = Rounded(normal, null, 8, 0), textColor = text },
|
||||
hover = { background = Rounded(hover, null, 8, 0), textColor = text },
|
||||
active = { background = Rounded(active, null, 8, 0), textColor = text },
|
||||
focused = { background = Rounded(normal, null, 8, 0), textColor = text }
|
||||
};
|
||||
}
|
||||
|
||||
public static Color WithAlpha(this Color c, float a) { c.a = a; return c; }
|
||||
|
||||
public static GUIStyle WithCenter(this GUIStyle s) => new GUIStyle(s) { alignment = TextAnchor.MiddleCenter };
|
||||
|
||||
public static Texture2D Solid(Color c)
|
||||
{
|
||||
string key = "s" + ColorUtility.ToHtmlStringRGBA(c);
|
||||
if (texCache.TryGetValue(key, out Texture2D t) && t != null) return t;
|
||||
t = new Texture2D(1, 1, TextureFormat.RGBA32, false) { hideFlags = HideFlags.HideAndDontSave };
|
||||
t.SetPixel(0, 0, c);
|
||||
t.Apply();
|
||||
texCache[key] = t;
|
||||
return t;
|
||||
}
|
||||
|
||||
/// <summary>Текстура скругленного прямоугольника для 9-slice фона окон и кнопок.</summary>
|
||||
public static Texture2D Rounded(Color fill, Color? border, int radius, int borderWidth)
|
||||
{
|
||||
string key = $"r{ColorUtility.ToHtmlStringRGBA(fill)}_{(border.HasValue ? ColorUtility.ToHtmlStringRGBA(border.Value) : "n")}_{radius}_{borderWidth}";
|
||||
if (texCache.TryGetValue(key, out Texture2D cached) && cached != null) return cached;
|
||||
|
||||
int size = radius * 2 + 4;
|
||||
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
|
||||
{
|
||||
hideFlags = HideFlags.HideAndDontSave,
|
||||
wrapMode = TextureWrapMode.Clamp,
|
||||
filterMode = FilterMode.Bilinear
|
||||
};
|
||||
|
||||
for (int y = 0; y < size; y++)
|
||||
{
|
||||
for (int x = 0; x < size; x++)
|
||||
{
|
||||
float cx = Mathf.Clamp(x + 0.5f, radius, size - radius);
|
||||
float cy = Mathf.Clamp(y + 0.5f, radius, size - radius);
|
||||
float d = Vector2.Distance(new Vector2(x + 0.5f, y + 0.5f), new Vector2(cx, cy));
|
||||
float alpha = Mathf.Clamp01(radius - d + 0.5f);
|
||||
Color c = fill;
|
||||
if (border.HasValue && borderWidth > 0 && d > radius - borderWidth - 0.5f)
|
||||
c = border.Value;
|
||||
c.a *= alpha;
|
||||
tex.SetPixel(x, y, c);
|
||||
}
|
||||
}
|
||||
tex.Apply();
|
||||
texCache[key] = tex;
|
||||
return tex;
|
||||
}
|
||||
|
||||
public static void DrawRect(Rect r, Color c)
|
||||
{
|
||||
GUI.DrawTexture(r, Solid(c));
|
||||
}
|
||||
|
||||
public static void ProgressBar(Rect r, float value01, Color fill, string caption = null)
|
||||
{
|
||||
DrawRect(r, Hex("0E1013"));
|
||||
Rect f = new Rect(r.x + 2, r.y + 2, Mathf.Max(0f, (r.width - 4) * Mathf.Clamp01(value01)), r.height - 4);
|
||||
DrawRect(f, fill);
|
||||
if (!string.IsNullOrEmpty(caption))
|
||||
GUI.Label(r, caption, SmallCenter);
|
||||
}
|
||||
|
||||
/// <summary>Кнопка со звуком нажатия.</summary>
|
||||
public static bool Btn(Rect r, string text, GUIStyle style = null)
|
||||
{
|
||||
bool pressed = GUI.Button(r, text, style ?? Button);
|
||||
if (pressed) ProceduralAudioManager.Instance?.PlayUi();
|
||||
return pressed;
|
||||
}
|
||||
|
||||
public static string Money(float usd)
|
||||
{
|
||||
GameEconomyManager eco = GameEconomyManager.Instance;
|
||||
return eco != null ? eco.FormatMoney(usd) : $"${usd:N0}";
|
||||
}
|
||||
|
||||
public static string Check(bool ok) => ok ? "<color=#4CD07D>●</color>" : "<color=#E5534B>●</color>";
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 31f032666548afa4397485bd3185817c
|
||||
@@ -0,0 +1,229 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Справочник данных деталей, канистр и материалов (Resources/Perekup/PartCatalog).
|
||||
/// Создается автонастройкой «Arcade Simulator → Auto-Setup». Если ассета нет — используются
|
||||
/// безопасные процедурные значения по умолчанию, чтобы игра никогда не падала с NullReference.
|
||||
/// </summary>
|
||||
[CreateAssetMenu(fileName = "PartCatalog", menuName = "Car System/Part Catalog")]
|
||||
public class PartCatalog : ScriptableObject
|
||||
{
|
||||
[Header("Подкапотные агрегаты")]
|
||||
public CarPartData battery;
|
||||
public CarPartData sparkPlugs;
|
||||
public CarPartData airFilter;
|
||||
public CarPartData oilFilter;
|
||||
public CarPartData radiator;
|
||||
public CarPartData alternator;
|
||||
public CarPartData fuelFilter;
|
||||
|
||||
[Header("Кузов и ходовая")]
|
||||
public CarPartData wheel;
|
||||
public CarPartData hood;
|
||||
public CarPartData door;
|
||||
public CarPartData trunk;
|
||||
public CarPartData fender;
|
||||
public CarPartData bumperFront;
|
||||
public CarPartData bumperBack;
|
||||
|
||||
[Header("Канистры технических жидкостей")]
|
||||
public GameObject canisterEngineOil;
|
||||
public GameObject canisterCoolant;
|
||||
public GameObject canisterBrakeFluid;
|
||||
public GameObject canisterWasherFluid;
|
||||
|
||||
[Header("Материалы")]
|
||||
public Material ghost;
|
||||
public Material carPaint;
|
||||
public List<NamedMaterial> materials = new List<NamedMaterial>();
|
||||
|
||||
[Serializable]
|
||||
public class NamedMaterial
|
||||
{
|
||||
public string key;
|
||||
public Material material;
|
||||
}
|
||||
|
||||
private static PartCatalog cached;
|
||||
private static readonly Dictionary<string, Material> runtimeMaterials = new Dictionary<string, Material>();
|
||||
|
||||
public static PartCatalog Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (cached != null) return cached;
|
||||
cached = Resources.Load<PartCatalog>("Perekup/PartCatalog");
|
||||
if (cached == null)
|
||||
{
|
||||
cached = CreateInstance<PartCatalog>();
|
||||
cached.hideFlags = HideFlags.DontSave;
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Сброс кэша после создания/изменения ассета каталога автонастройкой.</summary>
|
||||
public static void ResetCache()
|
||||
{
|
||||
cached = null;
|
||||
particleMaterial = null;
|
||||
dirtOverlay = null;
|
||||
runtimeMaterials.Clear();
|
||||
}
|
||||
|
||||
public CarPartData GetEngineData(EnginePartType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case EnginePartType.Battery: return battery;
|
||||
case EnginePartType.SparkPlugs: return sparkPlugs;
|
||||
case EnginePartType.AirFilter: return airFilter;
|
||||
case EnginePartType.OilFilter: return oilFilter;
|
||||
case EnginePartType.Radiator: return radiator;
|
||||
case EnginePartType.Alternator: return alternator;
|
||||
case EnginePartType.FuelFilter: return fuelFilter;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
public GameObject GetCanister(FluidType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case FluidType.EngineOil: return canisterEngineOil;
|
||||
case FluidType.Coolant: return canisterCoolant;
|
||||
case FluidType.BrakeFluid: return canisterBrakeFluid;
|
||||
case FluidType.WasherFluid: return canisterWasherFluid;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Материал по ключу (metal, black, battery, red, blue, yellow, white, rubber, copper, steam...).</summary>
|
||||
public Material GetMaterial(string key, Color fallbackColor)
|
||||
{
|
||||
foreach (NamedMaterial nm in materials)
|
||||
if (nm != null && nm.key == key && nm.material != null)
|
||||
return nm.material;
|
||||
|
||||
if (runtimeMaterials.TryGetValue(key, out Material m) && m != null) return m;
|
||||
m = CreateLitMaterial(fallbackColor);
|
||||
m.name = "Runtime_" + key;
|
||||
runtimeMaterials[key] = m;
|
||||
return m;
|
||||
}
|
||||
|
||||
private static Material particleMaterial;
|
||||
private static Material dirtOverlay;
|
||||
|
||||
/// <summary>Материал слоя грязи (прозрачная текстура подтеков/пыли), из каталога или процедурный.</summary>
|
||||
public static Material DirtOverlayMaterial
|
||||
{
|
||||
get
|
||||
{
|
||||
if (dirtOverlay != null) return dirtOverlay;
|
||||
foreach (NamedMaterial nm in Instance.materials)
|
||||
if (nm != null && nm.key == "dirt_overlay" && nm.material != null) return dirtOverlay = nm.material;
|
||||
|
||||
dirtOverlay = CreateLitMaterial(Color.white, 0.05f);
|
||||
dirtOverlay.name = "Runtime_DirtOverlay";
|
||||
Texture2D tex = GenerateDirtTexture(256);
|
||||
if (dirtOverlay.HasProperty("_BaseMap")) dirtOverlay.SetTexture("_BaseMap", tex);
|
||||
dirtOverlay.mainTexture = tex;
|
||||
MakeTransparent(dirtOverlay);
|
||||
return dirtOverlay;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Процедурная текстура грязи: землистые разводы и брызги снизу с альфа-каналом.</summary>
|
||||
public static Texture2D GenerateDirtTexture(int size)
|
||||
{
|
||||
Texture2D t = new Texture2D(size, size, TextureFormat.RGBA32, true) { name = "Tex_Dirt", wrapMode = TextureWrapMode.Repeat };
|
||||
Color mud = new Color(0.33f, 0.27f, 0.19f);
|
||||
Color dust = new Color(0.55f, 0.5f, 0.42f);
|
||||
for (int y = 0; y < size; y++)
|
||||
{
|
||||
for (int x = 0; x < size; x++)
|
||||
{
|
||||
float u = x / (float)size, v = y / (float)size;
|
||||
float n1 = Mathf.PerlinNoise(u * 6f + 3.1f, v * 6f + 7.7f);
|
||||
float n2 = Mathf.PerlinNoise(u * 22f + 11.3f, v * 22f + 1.9f);
|
||||
float n3 = Mathf.PerlinNoise(u * 60f, v * 60f);
|
||||
float a = Mathf.Clamp01(0.35f + n1 * 0.55f + (n2 - 0.5f) * 0.5f + (n3 - 0.5f) * 0.25f);
|
||||
Color c = Color.Lerp(mud, dust, n2);
|
||||
c.a = a;
|
||||
t.SetPixel(x, y, c);
|
||||
}
|
||||
}
|
||||
t.Apply();
|
||||
return t;
|
||||
}
|
||||
|
||||
/// <summary>Общий материал частиц (вода, пар, масло, краска) с поддержкой цвета вершин.</summary>
|
||||
public static Material ParticleMaterial
|
||||
{
|
||||
get
|
||||
{
|
||||
if (particleMaterial != null) return particleMaterial;
|
||||
Material fromCatalog = null;
|
||||
foreach (NamedMaterial nm in Instance.materials)
|
||||
if (nm != null && nm.key == "fx_particle" && nm.material != null) fromCatalog = nm.material;
|
||||
if (fromCatalog != null) return particleMaterial = fromCatalog;
|
||||
|
||||
Shader sh = Shader.Find("Universal Render Pipeline/Particles/Unlit") ?? Shader.Find("Particles/Standard Unlit") ?? Shader.Find("Sprites/Default");
|
||||
particleMaterial = new Material(sh) { name = "Runtime_Particles" };
|
||||
MakeTransparent(particleMaterial);
|
||||
return particleMaterial;
|
||||
}
|
||||
}
|
||||
|
||||
public static Material CreateLitMaterial(Color color, float smoothness = 0.35f, float metallic = 0f)
|
||||
{
|
||||
Shader sh = Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard");
|
||||
Material m = new Material(sh);
|
||||
if (m.HasProperty("_BaseColor")) m.SetColor("_BaseColor", color);
|
||||
m.color = color;
|
||||
if (m.HasProperty("_Smoothness")) m.SetFloat("_Smoothness", smoothness);
|
||||
if (m.HasProperty("_Metallic")) m.SetFloat("_Metallic", metallic);
|
||||
return m;
|
||||
}
|
||||
|
||||
public static Material CreateUnlitMaterial(Color color, bool transparent = false)
|
||||
{
|
||||
Shader sh = Shader.Find("Universal Render Pipeline/Unlit") ?? Shader.Find("Unlit/Color");
|
||||
Material m = new Material(sh);
|
||||
if (m.HasProperty("_BaseColor")) m.SetColor("_BaseColor", color);
|
||||
m.color = color;
|
||||
if (transparent) MakeTransparent(m);
|
||||
return m;
|
||||
}
|
||||
|
||||
public static void MakeTransparent(Material m)
|
||||
{
|
||||
if (m == null) return;
|
||||
if (m.HasProperty("_Surface"))
|
||||
{
|
||||
m.SetFloat("_Surface", 1f);
|
||||
m.SetFloat("_Blend", 0f);
|
||||
m.SetOverrideTag("RenderType", "Transparent");
|
||||
m.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
|
||||
m.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
|
||||
m.SetInt("_ZWrite", 0);
|
||||
m.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
|
||||
m.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
|
||||
}
|
||||
}
|
||||
|
||||
public static Material CreateEmissiveMaterial(Color baseColor, Color emission)
|
||||
{
|
||||
Material m = CreateLitMaterial(baseColor, 0.6f);
|
||||
if (m.HasProperty("_EmissionColor"))
|
||||
{
|
||||
m.EnableKeyword("_EMISSION");
|
||||
m.SetColor("_EmissionColor", emission);
|
||||
m.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6c7c67713f6f6c34f893fa402dadbd17
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cb7191cd571f4b29b09140c0787d0f56
|
||||
timeCreated: 1789819619
|
||||
@@ -0,0 +1,8 @@
|
||||
using UnityEngine;
|
||||
|
||||
public interface IInteractable
|
||||
{
|
||||
// Передаем ссылку на игрока, чтобы объект знал, кто с ним взаимодействует
|
||||
void Interact(GameObject interactor);
|
||||
string GetPrompt();
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5da3094495bf4ea2a8c39ac8fcf67557
|
||||
timeCreated: 1789819376
|
||||
@@ -0,0 +1,6 @@
|
||||
using UnityEngine;
|
||||
|
||||
public interface ISecondaryInteractable
|
||||
{
|
||||
void SecondaryInteract(GameObject interactor);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a19e1c56cc01408881999f83291b4acf
|
||||
timeCreated: 1791155204
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 21024185f8ef48cbba28354e34565425
|
||||
timeCreated: 1789818491
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c62998bcb5b44a948aa3df20fbca06fa
|
||||
timeCreated: 1789819562
|
||||
@@ -0,0 +1,100 @@
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>Руки игрока: переноска снятых деталей (CarPart) и канистр с жидкостями (FluidCanister).</summary>
|
||||
public class PlayerHands : MonoBehaviour
|
||||
{
|
||||
[Header("Точка удержания")]
|
||||
[Tooltip("Пустой дочерний объект перед камерой игрока")]
|
||||
[SerializeField] private Transform holdPoint;
|
||||
|
||||
[Header("Клавиши управления")]
|
||||
[SerializeField] private KeyCode dropKey = KeyCode.G;
|
||||
[SerializeField] private KeyCode throwKey = KeyCode.Mouse1; // Правая кнопка мыши
|
||||
[SerializeField] private float throwForce = 7f;
|
||||
|
||||
private CarPart currentPart;
|
||||
private FluidCanister currentCanister;
|
||||
|
||||
public bool IsHolding => currentPart != null;
|
||||
public bool IsHoldingCanister => currentCanister != null;
|
||||
public bool IsHoldingAnything => currentPart != null || currentCanister != null;
|
||||
public CarPart CurrentPart => currentPart;
|
||||
public FluidCanister CurrentCanister => currentCanister;
|
||||
public Transform HoldPoint => holdPoint;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (holdPoint == null)
|
||||
{
|
||||
Camera cam = GetComponentInChildren<Camera>();
|
||||
if (cam != null)
|
||||
{
|
||||
Transform hp = cam.transform.Find("HoldPoint");
|
||||
if (hp == null)
|
||||
{
|
||||
hp = new GameObject("HoldPoint").transform;
|
||||
hp.SetParent(cam.transform, false);
|
||||
hp.localPosition = new Vector3(0f, -0.25f, 0.85f);
|
||||
}
|
||||
holdPoint = hp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (!IsHolding || GameInputLock.IsLocked) return;
|
||||
|
||||
// Бросить под ноги
|
||||
if (Input.GetKeyDown(dropKey))
|
||||
{
|
||||
DropCurrentPart(Vector3.zero);
|
||||
}
|
||||
// Бросить вперед с силой
|
||||
else if (Input.GetKeyDown(throwKey))
|
||||
{
|
||||
Vector3 force = holdPoint.forward * throwForce;
|
||||
DropCurrentPart(force);
|
||||
}
|
||||
}
|
||||
|
||||
public void PickUp(CarPart part)
|
||||
{
|
||||
if (currentCanister != null) return;
|
||||
if (IsHolding)
|
||||
{
|
||||
// Если уже что-то держим — роняем старую деталь под ноги
|
||||
DropCurrentPart(Vector3.zero);
|
||||
}
|
||||
|
||||
currentPart = part;
|
||||
currentPart.OnPickedUp(holdPoint);
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.Pickup, holdPoint != null ? holdPoint.position : transform.position, 0.5f);
|
||||
}
|
||||
|
||||
public void DropCurrentPart(Vector3 impulse)
|
||||
{
|
||||
if (!IsHolding) return;
|
||||
|
||||
CarPart dropped = currentPart;
|
||||
currentPart = null; // Освобождаем руки
|
||||
dropped.OnDropped(impulse);
|
||||
}
|
||||
|
||||
public void ClearHandAfterInstall()
|
||||
{
|
||||
currentPart = null;
|
||||
}
|
||||
|
||||
public void SetHeldCanister(FluidCanister canister)
|
||||
{
|
||||
currentCanister = canister;
|
||||
}
|
||||
|
||||
/// <summary>Положить всё из рук (перед посадкой в машину, при открытии меню).</summary>
|
||||
public void DropEverything()
|
||||
{
|
||||
if (currentCanister != null) currentCanister.DropCanister();
|
||||
if (currentPart != null) DropCurrentPart(Vector3.zero);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 962f82a2c1ed4c7288b8c49e0a91b607
|
||||
timeCreated: 1790290101
|
||||
@@ -0,0 +1,321 @@
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Луч взаимодействия (3.2 м) с приоритетами:
|
||||
/// 1) зоны установки и горловины, если в руках деталь/канистра; 2) колесные болты рядом с лучом;
|
||||
/// 3) подкапотные агрегаты, бачки, щуп и сливная пробка; 4) домкрат и кирпичи; 5) детали кузова и посадка в авто [F].
|
||||
/// </summary>
|
||||
public class PlayerInteractor : MonoBehaviour
|
||||
{
|
||||
[Header("Настройки луча")]
|
||||
[SerializeField] private float interactRange = 3.2f;
|
||||
[SerializeField] private LayerMask interactableLayer;
|
||||
|
||||
[Header("Клавиши управления")]
|
||||
[SerializeField] private KeyCode primaryKey = KeyCode.E;
|
||||
[SerializeField] private KeyCode secondaryKey = KeyCode.R;
|
||||
[SerializeField] private KeyCode enterVehicleKey = KeyCode.F;
|
||||
|
||||
[Header("Ссылки")]
|
||||
[SerializeField] private UIManager uiManager;
|
||||
|
||||
private CarPart lastHoveredPart;
|
||||
private PlayerHands cachedHands;
|
||||
|
||||
/// <summary>Объект под прицелом в текущем кадре (для диагностики и HUD).</summary>
|
||||
public static GameObject CurrentTarget { get; private set; }
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (uiManager == null) uiManager = FindAnyObjectByType<UIManager>();
|
||||
cachedHands = GetComponentInParent<PlayerHands>();
|
||||
if (cachedHands == null) cachedHands = FindAnyObjectByType<PlayerHands>();
|
||||
if (interactableLayer.value == 0) interactableLayer = ~0;
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
ResetProgressTargets();
|
||||
if (uiManager != null) uiManager.HidePrompt();
|
||||
CurrentTarget = null;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
CurrentTarget = null;
|
||||
|
||||
if (GameInputLock.IsLocked)
|
||||
{
|
||||
ResetProgressTargets();
|
||||
uiManager?.HidePrompt();
|
||||
return;
|
||||
}
|
||||
|
||||
if (CarJack.ActiveJackInHand != null) return;
|
||||
|
||||
if (cachedHands == null) cachedHands = FindAnyObjectByType<PlayerHands>();
|
||||
|
||||
// Канистра в руках — заливкой и подсказками управляет сама канистра
|
||||
if (cachedHands != null && cachedHands.IsHoldingCanister)
|
||||
{
|
||||
ResetProgressTargets();
|
||||
uiManager?.ShowPrompt(cachedHands.CurrentCanister != null ? cachedHands.CurrentCanister.StatusHint : "[G] Поставить канистру");
|
||||
return;
|
||||
}
|
||||
|
||||
Ray ray = new Ray(transform.position, transform.forward);
|
||||
GameObject playerRoot = transform.root.gameObject;
|
||||
|
||||
// 0. Если в руках деталь — проверяем все зоны установки по лучу (чтобы кузов не перекрывал зону колеса!)
|
||||
if (cachedHands != null && cachedHands.IsHolding)
|
||||
{
|
||||
RaycastHit[] allHits = Physics.RaycastAll(ray, interactRange, interactableLayer, QueryTriggerInteraction.Collide);
|
||||
foreach (var h in allHits)
|
||||
{
|
||||
CarPartMountZone zone = h.collider.GetComponentInParent<CarPartMountZone>();
|
||||
if (zone != null)
|
||||
{
|
||||
ResetProgressTargets();
|
||||
string zPrompt = zone.GetPrompt();
|
||||
if (!string.IsNullOrEmpty(zPrompt))
|
||||
uiManager?.ShowPrompt(zPrompt);
|
||||
else
|
||||
uiManager?.HidePrompt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
uiManager?.ShowPrompt($"В руках: {cachedHands.CurrentPart.DisplayName} | [G] Положить [ПКМ] Бросить");
|
||||
return;
|
||||
}
|
||||
|
||||
// Сливная пробка картера под днищем (луч может проходить под порогом)
|
||||
if (TryDrainPlug(ray, playerRoot)) return;
|
||||
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, interactRange, interactableLayer, QueryTriggerInteraction.Collide))
|
||||
{
|
||||
CurrentTarget = hit.collider.gameObject;
|
||||
|
||||
// 1. ТОЧНЫЙ ПОИСК БЛИЖАЙШЕГО К ПРИЦЕЛУ БОЛТА
|
||||
WheelBolt bestBolt = FindClosestBoltToRay(ray, hit.point);
|
||||
if (bestBolt != null)
|
||||
{
|
||||
ResetProgressTargets();
|
||||
string boltPrompt = bestBolt.GetPrompt();
|
||||
if (!string.IsNullOrEmpty(boltPrompt))
|
||||
uiManager?.ShowPrompt(boltPrompt);
|
||||
else
|
||||
uiManager?.HidePrompt();
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. ПОДКАПОТНОЕ ПРОСТРАНСТВО: агрегаты, бачки, щуп
|
||||
bool isEngineBayTarget = hit.collider.GetComponentInParent<EnginePart>() != null
|
||||
|| hit.collider.GetComponentInParent<CarFluidCap>() != null
|
||||
|| hit.collider.GetComponentInParent<OilDipstick>() != null;
|
||||
|
||||
if (!isEngineBayTarget)
|
||||
{
|
||||
// 3. ДОМКРАТ ПОД ПОРОГОМ
|
||||
CarJack jack = hit.collider.GetComponentInParent<CarJack>();
|
||||
if (jack == null)
|
||||
{
|
||||
Collider[] nearJackCols = Physics.OverlapSphere(hit.point, 0.22f, interactableLayer, QueryTriggerInteraction.Collide);
|
||||
foreach (var c in nearJackCols)
|
||||
{
|
||||
jack = c.GetComponentInParent<CarJack>();
|
||||
if (jack != null) break;
|
||||
}
|
||||
}
|
||||
|
||||
if (jack != null)
|
||||
{
|
||||
ResetProgressTargets();
|
||||
uiManager?.ShowPrompt(jack.GetPrompt());
|
||||
if (Input.GetKeyDown(primaryKey))
|
||||
jack.Interact(playerRoot);
|
||||
return;
|
||||
}
|
||||
|
||||
WheelBrickSupport bricks = hit.collider.GetComponentInParent<WheelBrickSupport>();
|
||||
if (bricks == null)
|
||||
{
|
||||
Collider[] nearBrickCols = Physics.OverlapSphere(hit.point, 0.22f, interactableLayer, QueryTriggerInteraction.Collide);
|
||||
foreach (var c in nearBrickCols)
|
||||
{
|
||||
bricks = c.GetComponentInParent<WheelBrickSupport>();
|
||||
if (bricks != null) break;
|
||||
}
|
||||
}
|
||||
|
||||
if (bricks != null)
|
||||
{
|
||||
ResetProgressTargets();
|
||||
uiManager?.ShowPrompt(bricks.GetPrompt());
|
||||
if (Input.GetKeyDown(primaryKey))
|
||||
bricks.Interact(playerRoot);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. ОБЫЧНЫЕ ДЕТАЛИ И АВТОМОБИЛЬ
|
||||
IInteractable interactable = hit.collider.GetComponentInParent<IInteractable>();
|
||||
VehicleInteraction vehicle = hit.collider.GetComponentInParent<VehicleInteraction>();
|
||||
CarPart part = hit.collider.GetComponentInParent<CarPart>();
|
||||
CarPartMountZone mountZone = hit.collider.GetComponentInParent<CarPartMountZone>();
|
||||
|
||||
if (part != lastHoveredPart)
|
||||
{
|
||||
ResetProgressTargets();
|
||||
lastHoveredPart = part;
|
||||
}
|
||||
|
||||
if (interactable != null || vehicle != null)
|
||||
{
|
||||
if (Input.GetKeyDown(enterVehicleKey) && vehicle != null)
|
||||
{
|
||||
vehicle.Interact(playerRoot);
|
||||
return;
|
||||
}
|
||||
|
||||
if (mountZone == null && part != null)
|
||||
{
|
||||
if (part.State == PartState.Dropped)
|
||||
{
|
||||
if (Input.GetKeyDown(primaryKey))
|
||||
part.Interact(playerRoot);
|
||||
}
|
||||
else if (part.State == PartState.Installed)
|
||||
{
|
||||
bool hasAnimator = part.GetComponent<CarPartAnimator>() != null;
|
||||
if (hasAnimator)
|
||||
{
|
||||
if (Input.GetKeyDown(primaryKey))
|
||||
part.Interact(playerRoot);
|
||||
|
||||
if (Input.GetKey(secondaryKey))
|
||||
part.ProcessUnbolting(playerRoot, Time.deltaTime);
|
||||
else
|
||||
part.ResetUnbolt();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Input.GetKey(primaryKey))
|
||||
part.ProcessUnbolting(playerRoot, Time.deltaTime);
|
||||
else
|
||||
part.ResetUnbolt();
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (mountZone == null && interactable != null && Input.GetKeyDown(primaryKey))
|
||||
{
|
||||
interactable.Interact(playerRoot);
|
||||
}
|
||||
|
||||
string finalPrompt = BuildPrompt(vehicle, interactable, part);
|
||||
if (!string.IsNullOrEmpty(finalPrompt))
|
||||
uiManager?.ShowPrompt(finalPrompt);
|
||||
else
|
||||
uiManager?.HidePrompt();
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
ResetProgressTargets();
|
||||
uiManager?.HidePrompt();
|
||||
}
|
||||
|
||||
private bool TryDrainPlug(Ray ray, GameObject playerRoot)
|
||||
{
|
||||
RaycastHit[] hits = Physics.RaycastAll(ray, interactRange, interactableLayer, QueryTriggerInteraction.Collide);
|
||||
foreach (RaycastHit h in hits)
|
||||
{
|
||||
OilDrainPlug plug = h.collider.GetComponent<OilDrainPlug>();
|
||||
if (plug == null) continue;
|
||||
|
||||
// Пробка доступна только снизу: камера должна быть невысоко над пробкой (присесть [Ctrl])
|
||||
if (transform.position.y - h.point.y > 1.25f) continue;
|
||||
|
||||
ResetProgressTargets();
|
||||
CurrentTarget = plug.gameObject;
|
||||
uiManager?.ShowPrompt(plug.GetPrompt());
|
||||
if (Input.GetKeyDown(primaryKey)) plug.Interact(playerRoot);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private WheelBolt FindClosestBoltToRay(Ray ray, Vector3 hitPoint)
|
||||
{
|
||||
WheelBolt closest = null;
|
||||
float minRayDist = 0.085f; // Радиус захвата точки прицела (8.5 см вокруг луча)
|
||||
|
||||
// 1. Ищем колесо в радиусе попадания луча и проверяем ВСЕ его дочерние болты напрямую
|
||||
// (работает даже если коллайдер шины перекрывает ступицу!)
|
||||
Collider[] nearCols = Physics.OverlapSphere(hitPoint, 0.35f, interactableLayer, QueryTriggerInteraction.Collide);
|
||||
foreach (var c in nearCols)
|
||||
{
|
||||
CarPart part = c.GetComponentInParent<CarPart>();
|
||||
if (part != null && part.TotalBoltsCount > 0 && part.State == PartState.Installed)
|
||||
{
|
||||
foreach (WheelBolt b in part.GetComponentsInChildren<WheelBolt>(true))
|
||||
{
|
||||
if (b == null || !b.IsAvailableForAim) continue;
|
||||
|
||||
Vector3 boltPos = b.WorldBoltCenter;
|
||||
float distToRay = Vector3.Cross(ray.direction, boltPos - ray.origin).magnitude;
|
||||
if (distToRay < minRayDist)
|
||||
{
|
||||
minRayDist = distToRay;
|
||||
closest = b;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// На случай если луч попал прямо в коллайдер самого болта
|
||||
WheelBolt directBolt = c.GetComponent<WheelBolt>();
|
||||
if (directBolt != null && directBolt.IsAvailableForAim)
|
||||
{
|
||||
float distToRay = Vector3.Cross(ray.direction, directBolt.WorldBoltCenter - ray.origin).magnitude;
|
||||
if (distToRay < minRayDist)
|
||||
{
|
||||
minRayDist = distToRay;
|
||||
closest = directBolt;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return closest;
|
||||
}
|
||||
|
||||
private string BuildPrompt(VehicleInteraction vehicle, IInteractable interactable, CarPart part)
|
||||
{
|
||||
string partPrompt = (interactable != null && !(interactable is VehicleInteraction))
|
||||
? interactable.GetPrompt()
|
||||
: string.Empty;
|
||||
|
||||
bool canEnter = vehicle != null && !vehicle.isPlayerInside;
|
||||
|
||||
// У непроданной машины на встрече или машины на площадке продажи — подсказка сделки
|
||||
if (vehicle != null && part == null)
|
||||
{
|
||||
CarOwnership own = vehicle.GetComponent<CarOwnership>();
|
||||
if (own != null && !own.isOwned)
|
||||
partPrompt = $"[B] Сделка: {own.carTitle} — ${own.askingPrice:N0}";
|
||||
}
|
||||
|
||||
if (canEnter && !string.IsNullOrEmpty(partPrompt))
|
||||
return $"[F] Сесть | {partPrompt}";
|
||||
if (canEnter)
|
||||
return "[F] Сесть в машину";
|
||||
|
||||
return partPrompt;
|
||||
}
|
||||
|
||||
private void ResetProgressTargets()
|
||||
{
|
||||
if (lastHoveredPart != null) lastHoveredPart.ResetUnbolt();
|
||||
lastHoveredPart = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 55f66c5b12bc40f08c38b6fad86ad694
|
||||
timeCreated: 1789819467
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 590a609c93d0458ba9144576ebbcebd7
|
||||
timeCreated: 1789819518
|
||||
@@ -0,0 +1,52 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class PlayerInputHandler : MonoBehaviour
|
||||
{
|
||||
[Header("Components")]
|
||||
[SerializeField] private PlayerMovement playerMovement;
|
||||
[SerializeField] private PlayerLook playerLook;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (playerMovement == null) playerMovement = GetComponent<PlayerMovement>();
|
||||
if (playerLook == null) playerLook = GetComponentInChildren<PlayerLook>();
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
// Пока открыто меню/планшет/окно торга — игрок стоит на месте (гравитация продолжает работать)
|
||||
if (GameInputLock.IsLocked)
|
||||
{
|
||||
if (playerMovement != null) playerMovement.ProcessMove(Vector2.zero);
|
||||
return;
|
||||
}
|
||||
|
||||
HandleMovementInput();
|
||||
HandleLookInput();
|
||||
}
|
||||
|
||||
private void HandleMovementInput()
|
||||
{
|
||||
// Читаем оси WASD. GetAxisRaw дает более резкое, отзывчивое управление без инерции.
|
||||
float horizontal = Input.GetAxisRaw("Horizontal");
|
||||
float vertical = Input.GetAxisRaw("Vertical");
|
||||
|
||||
// Нормализуем вектор, чтобы игрок не двигался быстрее по диагонали
|
||||
Vector2 moveInput = new Vector2(horizontal, vertical).normalized;
|
||||
|
||||
if (playerMovement != null)
|
||||
playerMovement.ProcessMove(moveInput);
|
||||
}
|
||||
|
||||
private void HandleLookInput()
|
||||
{
|
||||
// Читаем движение мыши
|
||||
float mouseX = Input.GetAxis("Mouse X");
|
||||
float mouseY = Input.GetAxis("Mouse Y");
|
||||
|
||||
Vector2 lookInput = new Vector2(mouseX, mouseY);
|
||||
|
||||
if (playerLook != null && playerLook.enabled)
|
||||
playerLook.ProcessLook(lookInput);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 00826943886c407c952993731de997e0
|
||||
timeCreated: 1789818508
|
||||
@@ -0,0 +1,53 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class PlayerLook : MonoBehaviour
|
||||
{
|
||||
[Header("Look Settings")]
|
||||
[SerializeField] private float mouseSensitivity = 150f;
|
||||
[SerializeField] private Transform playerBody;
|
||||
|
||||
private float xRotation = 0f;
|
||||
|
||||
public float Sensitivity => mouseSensitivity;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (playerBody == null) playerBody = transform.parent != null ? transform.parent : transform;
|
||||
mouseSensitivity = PlayerPrefs.GetFloat("perekup_sensitivity", mouseSensitivity);
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
// Блокируем курсор в центре экрана и скрываем его (если не открыто меню)
|
||||
GameInputLock.ApplyCursor();
|
||||
}
|
||||
|
||||
public void SetSensitivity(float value)
|
||||
{
|
||||
mouseSensitivity = Mathf.Clamp(value, 20f, 600f);
|
||||
PlayerPrefs.SetFloat("perekup_sensitivity", mouseSensitivity);
|
||||
}
|
||||
|
||||
/// <summary>Поворот взгляда в заданном направлении (после телепорта/выхода из машины).</summary>
|
||||
public void ResetPitch(float pitch = 0f)
|
||||
{
|
||||
xRotation = pitch;
|
||||
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
|
||||
}
|
||||
|
||||
public void ProcessLook(Vector2 input)
|
||||
{
|
||||
float mouseX = input.x * mouseSensitivity * Time.deltaTime;
|
||||
float mouseY = input.y * mouseSensitivity * Time.deltaTime;
|
||||
|
||||
// Расчет наклона камеры с ограничением, чтобы нельзя было сломать шею
|
||||
xRotation -= mouseY;
|
||||
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
|
||||
|
||||
// Применяем вращение камеры (вверх/вниз)
|
||||
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
|
||||
|
||||
// Вращаем само тело игрока (влево/вправо)
|
||||
playerBody.Rotate(Vector3.up * mouseX);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4662192a51344c429f6fb8cb1730a7e2
|
||||
timeCreated: 1789818561
|
||||
@@ -0,0 +1,117 @@
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(CharacterController))]
|
||||
public class PlayerMovement : MonoBehaviour
|
||||
{
|
||||
[Header("Movement Settings")]
|
||||
[SerializeField] private float moveSpeed = 4f;
|
||||
[SerializeField] private float crouchSpeed = 2f;
|
||||
[SerializeField] private float gravity = -9.81f;
|
||||
|
||||
[Header("Crouch Settings")]
|
||||
[SerializeField] private KeyCode crouchKey = KeyCode.LeftControl;
|
||||
[SerializeField] private float standHeight = 2.0f;
|
||||
[SerializeField] private float crouchHeight = 1.0f;
|
||||
[SerializeField] private float crouchTransitionSpeed = 10f;
|
||||
[SerializeField] private Transform playerCamera; // Ссылка на камеру игрока
|
||||
|
||||
[Header("Ground Check")]
|
||||
[SerializeField] private Transform groundCheck;
|
||||
[SerializeField] private float groundDistance = 0.4f;
|
||||
[SerializeField] private LayerMask groundMask;
|
||||
|
||||
private CharacterController controller;
|
||||
private Vector3 velocity;
|
||||
private bool isGrounded;
|
||||
|
||||
private float initialHeight;
|
||||
private Vector3 standCameraPos;
|
||||
private Vector3 crouchCameraPos;
|
||||
private Vector3 initialCenter;
|
||||
private bool isCrouching;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
controller = GetComponent<CharacterController>();
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
// Запоминаем исходные значения из Инспектора
|
||||
initialHeight = controller.height;
|
||||
initialCenter = controller.center;
|
||||
|
||||
if (playerCamera == null)
|
||||
{
|
||||
Camera cam = GetComponentInChildren<Camera>();
|
||||
if (cam != null) playerCamera = cam.transform;
|
||||
}
|
||||
|
||||
if (playerCamera != null)
|
||||
{
|
||||
standCameraPos = playerCamera.localPosition;
|
||||
// Камера опускается ровно на разницу высоты
|
||||
crouchCameraPos = new Vector3(
|
||||
standCameraPos.x,
|
||||
standCameraPos.y - (standHeight - crouchHeight),
|
||||
standCameraPos.z
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
HandleCrouch();
|
||||
}
|
||||
|
||||
private void HandleCrouch()
|
||||
{
|
||||
if (Input.GetKeyDown(crouchKey))
|
||||
{
|
||||
isCrouching = !isCrouching;
|
||||
}
|
||||
|
||||
float targetHeight = isCrouching ? crouchHeight : standHeight;
|
||||
float currentDelta = initialHeight - targetHeight;
|
||||
|
||||
// ГЛАВНАЯ ФОРМУЛА: дно капсулы остается на земле
|
||||
Vector3 targetCenter = new Vector3(
|
||||
initialCenter.x,
|
||||
initialCenter.y - (currentDelta * 0.5f),
|
||||
initialCenter.z
|
||||
);
|
||||
|
||||
controller.height = Mathf.MoveTowards(controller.height, targetHeight, Time.deltaTime * crouchTransitionSpeed);
|
||||
controller.center = Vector3.MoveTowards(controller.center, targetCenter, Time.deltaTime * crouchTransitionSpeed);
|
||||
|
||||
if (playerCamera != null)
|
||||
{
|
||||
Vector3 targetCamPos = isCrouching ? crouchCameraPos : standCameraPos;
|
||||
playerCamera.localPosition = Vector3.MoveTowards(playerCamera.localPosition, targetCamPos, Time.deltaTime * crouchTransitionSpeed);
|
||||
}
|
||||
}
|
||||
|
||||
public void ProcessMove(Vector2 input)
|
||||
{
|
||||
// Проверка касания земли (сфера на уровне ног)
|
||||
isGrounded = groundCheck != null
|
||||
? Physics.CheckSphere(groundCheck.position, groundDistance, groundMask, QueryTriggerInteraction.Ignore) || controller.isGrounded
|
||||
: controller.isGrounded;
|
||||
|
||||
if (isGrounded && velocity.y < 0)
|
||||
{
|
||||
velocity.y = -2f; // Небольшое прижатие к земле для стабильного спуска по склонам
|
||||
}
|
||||
|
||||
// Выбор текущей скорости в зависимости от состояния приседа
|
||||
float currentSpeed = isCrouching ? crouchSpeed : moveSpeed;
|
||||
|
||||
// Движение относительно локальных координат игрока
|
||||
Vector3 move = transform.right * input.x + transform.forward * input.y;
|
||||
controller.Move(move * (currentSpeed * Time.deltaTime));
|
||||
|
||||
// Применение гравитации
|
||||
velocity.y += gravity * Time.deltaTime;
|
||||
controller.Move(velocity * Time.deltaTime);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bf210e4b179e4c4a93ffda4241a24602
|
||||
timeCreated: 1789818546
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c01700faa0d14262a0eafda9e075cb96
|
||||
timeCreated: 1791393477
|
||||
@@ -0,0 +1,755 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
|
||||
public enum ToolType
|
||||
{
|
||||
Hands, RustCleaner, Putty, Sander, SprayCan, Wrench, PressureWasher, ThicknessGauge, OBDScanner
|
||||
}
|
||||
|
||||
public class PlayerToolManager : MonoBehaviour
|
||||
{
|
||||
[Serializable]
|
||||
public struct ToolVisualSlot
|
||||
{
|
||||
public ToolType toolType;
|
||||
[Tooltip("Перетащите сюда префаб или объект 3D-модели инструмента")]
|
||||
public GameObject toolModelOrPrefab;
|
||||
public Vector3 positionOffset;
|
||||
public Vector3 rotationOffset;
|
||||
}
|
||||
|
||||
[Header("Текущий инструмент")]
|
||||
public ToolType currentTool = ToolType.Hands;
|
||||
|
||||
[Header("3D-модели инструментов в руках")]
|
||||
[SerializeField] private ToolVisualSlot[] toolModelsInHand;
|
||||
[SerializeField] private Vector3 handAnchorLocalPos = new Vector3(0.32f, -0.26f, 0.55f);
|
||||
|
||||
[Header("Луч инструмента")]
|
||||
[SerializeField] private float toolRange = 2.8f;
|
||||
[SerializeField] private LayerMask interactableLayer;
|
||||
|
||||
[Header("Время полной обработки детали при ведении мыши, сек")]
|
||||
[SerializeField] private float cleanTime = 3.5f;
|
||||
[SerializeField] private float puttyTime = 2.5f;
|
||||
[SerializeField] private float sandTime = 3.0f;
|
||||
[SerializeField] private float paintTime = 2.5f;
|
||||
|
||||
[Header("Перекраска целой детали")]
|
||||
[SerializeField] private Color sprayPaintColor = new Color(0.1f, 0.4f, 0.8f);
|
||||
|
||||
private Camera playerCam;
|
||||
private Transform toolHandAnchor;
|
||||
private readonly Dictionary<ToolType, GameObject> spawnedTools = new Dictionary<ToolType, GameObject>();
|
||||
private GameObject activeToolObj;
|
||||
|
||||
private Vector3 lastHitPoint;
|
||||
private bool hadHitLastFrame;
|
||||
|
||||
[Header("Мойка высокого давления")]
|
||||
[SerializeField] private float washTime = 2.2f;
|
||||
[SerializeField] private float washRadius = 0.9f;
|
||||
private ParticleSystem washerSpray;
|
||||
private bool soundActive;
|
||||
|
||||
public static PlayerToolManager Instance { get; private set; }
|
||||
|
||||
public static string GetToolName(ToolType t)
|
||||
{
|
||||
switch (t)
|
||||
{
|
||||
case ToolType.Hands: return "Руки";
|
||||
case ToolType.RustCleaner: return "Зачистка (дрель с кордщёткой)";
|
||||
case ToolType.Putty: return "Шпатель (шпаклёвка)";
|
||||
case ToolType.Sander: return "Наждачка (шлифовка)";
|
||||
case ToolType.SprayCan: return "Баллончик (покраска)";
|
||||
case ToolType.Wrench: return "Баллонный / гаечный ключ";
|
||||
case ToolType.PressureWasher: return "Мойка высокого давления (Керхер)";
|
||||
case ToolType.ThicknessGauge: return "Толщиномер ЛКП";
|
||||
case ToolType.OBDScanner: return "OBD-сканер ошибок";
|
||||
default: return t.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsDiplomaTool(ToolType t) => t == ToolType.ThicknessGauge || t == ToolType.OBDScanner;
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (Instance == this) Instance = null;
|
||||
}
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
Instance = this;
|
||||
playerCam = GetComponentInChildren<Camera>();
|
||||
if (playerCam == null) playerCam = Camera.main;
|
||||
if (interactableLayer.value == 0) interactableLayer = ~0;
|
||||
|
||||
InitializeHandTools();
|
||||
UpdateToolVisuals();
|
||||
}
|
||||
|
||||
private void InitializeHandTools()
|
||||
{
|
||||
if (playerCam == null) return;
|
||||
|
||||
GameObject anchorObj = new GameObject("ToolHandAnchor");
|
||||
toolHandAnchor = anchorObj.transform;
|
||||
toolHandAnchor.SetParent(playerCam.transform, false);
|
||||
toolHandAnchor.localPosition = handAnchorLocalPos;
|
||||
toolHandAnchor.localRotation = Quaternion.identity;
|
||||
|
||||
foreach (ToolType type in Enum.GetValues(typeof(ToolType)))
|
||||
{
|
||||
if (type == ToolType.Hands) continue;
|
||||
|
||||
GameObject customSource = null;
|
||||
Vector3 posOff = Vector3.zero;
|
||||
Vector3 rotOff = Vector3.zero;
|
||||
|
||||
if (toolModelsInHand != null)
|
||||
{
|
||||
foreach (var s in toolModelsInHand)
|
||||
{
|
||||
if (s.toolType == type && s.toolModelOrPrefab != null)
|
||||
{
|
||||
customSource = s.toolModelOrPrefab;
|
||||
posOff = s.positionOffset;
|
||||
rotOff = s.rotationOffset;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Если префаб еще не назначен вручную — автоматически берем из Assets/Prefabs/Tools
|
||||
#if UNITY_EDITOR
|
||||
if (customSource == null)
|
||||
{
|
||||
string pPath = GetDefaultPrefabPath(type);
|
||||
if (!string.IsNullOrEmpty(pPath))
|
||||
{
|
||||
customSource = UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>(pPath);
|
||||
posOff = GetDefaultPositionOffset(type);
|
||||
rotOff = GetDefaultRotationOffset(type);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
GameObject wrapper = new GameObject($"HandTool_{type}");
|
||||
wrapper.transform.SetParent(toolHandAnchor, false);
|
||||
|
||||
if (customSource != null)
|
||||
{
|
||||
GameObject instance = !customSource.scene.IsValid()
|
||||
? Instantiate(customSource, wrapper.transform)
|
||||
: customSource;
|
||||
|
||||
instance.transform.SetParent(wrapper.transform, false);
|
||||
instance.transform.localPosition = Vector3.zero;
|
||||
instance.transform.localRotation = Quaternion.Euler(rotOff);
|
||||
|
||||
foreach (var col in instance.GetComponentsInChildren<Collider>(true)) col.enabled = false;
|
||||
foreach (var rb in instance.GetComponentsInChildren<Rigidbody>(true)) Destroy(rb);
|
||||
|
||||
Renderer rend = instance.GetComponentInChildren<Renderer>();
|
||||
if (rend != null)
|
||||
{
|
||||
Vector3 centerOffset = wrapper.transform.position - rend.bounds.center;
|
||||
instance.transform.position += centerOffset;
|
||||
instance.transform.localPosition += posOff;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
BuildFallbackToolModel(wrapper.transform, type);
|
||||
}
|
||||
|
||||
wrapper.SetActive(false);
|
||||
spawnedTools[type] = wrapper;
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetDefaultPrefabPath(ToolType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case ToolType.RustCleaner: return "Assets/Prefabs/Tools/Tool_RustCleaner.prefab";
|
||||
case ToolType.Putty: return "Assets/Prefabs/Tools/Tool_PuttySpatula.prefab";
|
||||
case ToolType.Sander: return "Assets/Prefabs/Tools/Tool_SandingBlock.prefab";
|
||||
case ToolType.SprayCan: return "Assets/Prefabs/Tools/Tool_SprayCan.prefab";
|
||||
case ToolType.Wrench: return "Assets/Asset/Workplace Tools/Prefabs/Wrench_Combination.prefab";
|
||||
default: return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
private static Vector3 GetDefaultPositionOffset(ToolType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case ToolType.RustCleaner: return new Vector3(0.02f, -0.06f, 0.12f);
|
||||
case ToolType.Putty: return new Vector3(0.01f, -0.04f, 0.08f);
|
||||
case ToolType.Sander: return new Vector3(0.01f, -0.05f, 0.06f);
|
||||
case ToolType.SprayCan: return new Vector3(0.02f, -0.08f, 0.06f);
|
||||
case ToolType.Wrench: return new Vector3(0.02f, -0.02f, 0.10f);
|
||||
default: return Vector3.zero;
|
||||
}
|
||||
}
|
||||
|
||||
private static Vector3 GetDefaultRotationOffset(ToolType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case ToolType.RustCleaner: return new Vector3(25f, -20f, 15f);
|
||||
case ToolType.Putty: return new Vector3(15f, -10f, 0f);
|
||||
case ToolType.Sander: return new Vector3(10f, -15f, 5f);
|
||||
case ToolType.SprayCan: return new Vector3(0f, -25f, 0f);
|
||||
case ToolType.Wrench: return new Vector3(0f, -15f, 45f);
|
||||
default: return Vector3.zero;
|
||||
}
|
||||
}
|
||||
|
||||
private void BuildWasherLance(Transform parent)
|
||||
{
|
||||
Material black = new Material(Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard")) { color = new Color(0.08f, 0.08f, 0.09f) };
|
||||
GameObject lance = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
|
||||
Destroy(lance.GetComponent<Collider>());
|
||||
lance.name = "Lance";
|
||||
lance.transform.SetParent(parent, false);
|
||||
lance.transform.localPosition = new Vector3(0f, 0.05f, 0.3f);
|
||||
lance.transform.localRotation = Quaternion.Euler(90f, 0f, 0f);
|
||||
lance.transform.localScale = new Vector3(0.018f, 0.28f, 0.018f);
|
||||
lance.GetComponent<Renderer>().sharedMaterial = black;
|
||||
|
||||
GameObject nozzle = new GameObject("Nozzle");
|
||||
nozzle.transform.SetParent(parent, false);
|
||||
nozzle.transform.localPosition = new Vector3(0f, 0.05f, 0.6f);
|
||||
}
|
||||
|
||||
private void AddScreen(Transform parent, Vector3 localPos, Color color)
|
||||
{
|
||||
GameObject scr = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
Destroy(scr.GetComponent<Collider>());
|
||||
scr.transform.SetParent(parent, false);
|
||||
scr.transform.localPosition = localPos;
|
||||
scr.transform.localRotation = Quaternion.Euler(-25f, -10f, 0f);
|
||||
scr.transform.localScale = new Vector3(0.05f, 0.045f, 0.004f);
|
||||
scr.GetComponent<Renderer>().sharedMaterial = PartCatalog.CreateEmissiveMaterial(color * 0.4f, color * 1.5f);
|
||||
}
|
||||
|
||||
private void EnsureWasherSpray()
|
||||
{
|
||||
if (washerSpray != null || !spawnedTools.TryGetValue(ToolType.PressureWasher, out GameObject tool) || tool == null) return;
|
||||
|
||||
Transform nozzle = tool.transform.Find("Nozzle");
|
||||
GameObject pObj = new GameObject("WaterJet");
|
||||
pObj.transform.SetParent(nozzle != null ? nozzle : tool.transform, false);
|
||||
pObj.transform.localPosition = nozzle != null ? Vector3.zero : new Vector3(0f, 0.05f, 0.6f);
|
||||
pObj.transform.localRotation = Quaternion.identity;
|
||||
|
||||
washerSpray = pObj.AddComponent<ParticleSystem>();
|
||||
var main = washerSpray.main;
|
||||
main.startLifetime = 0.35f;
|
||||
main.startSpeed = new ParticleSystem.MinMaxCurve(9f, 13f);
|
||||
main.startSize = new ParticleSystem.MinMaxCurve(0.02f, 0.06f);
|
||||
main.startColor = new Color(0.75f, 0.88f, 1f, 0.55f);
|
||||
main.simulationSpace = ParticleSystemSimulationSpace.World;
|
||||
main.gravityModifier = 0.6f;
|
||||
main.maxParticles = 600;
|
||||
main.playOnAwake = false;
|
||||
var emission = washerSpray.emission;
|
||||
emission.rateOverTime = 260f;
|
||||
var shape = washerSpray.shape;
|
||||
shape.shapeType = ParticleSystemShapeType.Cone;
|
||||
shape.angle = 4f;
|
||||
shape.radius = 0.005f;
|
||||
var collision = washerSpray.collision;
|
||||
collision.enabled = true;
|
||||
collision.type = ParticleSystemCollisionType.World;
|
||||
collision.dampen = 0.6f;
|
||||
collision.bounce = 0.2f;
|
||||
collision.lifetimeLoss = 0.4f;
|
||||
pObj.GetComponent<ParticleSystemRenderer>().sharedMaterial = PartCatalog.ParticleMaterial;
|
||||
washerSpray.Stop();
|
||||
}
|
||||
|
||||
private void BuildFallbackToolModel(Transform parent, ToolType type)
|
||||
{
|
||||
GameObject prim = GameObject.CreatePrimitive(
|
||||
type == ToolType.SprayCan ? PrimitiveType.Cylinder : PrimitiveType.Cube);
|
||||
Destroy(prim.GetComponent<Collider>());
|
||||
prim.transform.SetParent(parent, false);
|
||||
|
||||
Renderer r = prim.GetComponent<Renderer>();
|
||||
Material mat = new Material(Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard"));
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case ToolType.RustCleaner:
|
||||
prim.transform.localScale = new Vector3(0.08f, 0.06f, 0.22f);
|
||||
mat.color = new Color(0.85f, 0.35f, 0.1f);
|
||||
break;
|
||||
case ToolType.Putty:
|
||||
prim.transform.localScale = new Vector3(0.12f, 0.015f, 0.20f);
|
||||
prim.transform.localRotation = Quaternion.Euler(15f, 0f, 0f);
|
||||
mat.color = new Color(0.75f, 0.75f, 0.78f);
|
||||
break;
|
||||
case ToolType.Sander:
|
||||
prim.transform.localScale = new Vector3(0.11f, 0.08f, 0.18f);
|
||||
mat.color = new Color(0.2f, 0.65f, 0.3f);
|
||||
break;
|
||||
case ToolType.SprayCan:
|
||||
prim.transform.localScale = new Vector3(0.07f, 0.11f, 0.07f);
|
||||
mat.color = sprayPaintColor;
|
||||
break;
|
||||
case ToolType.Wrench:
|
||||
prim.transform.localScale = new Vector3(0.04f, 0.04f, 0.28f);
|
||||
prim.transform.localRotation = Quaternion.Euler(0f, -15f, 0f);
|
||||
mat.color = new Color(0.6f, 0.63f, 0.67f);
|
||||
break;
|
||||
case ToolType.PressureWasher:
|
||||
prim.transform.localScale = new Vector3(0.07f, 0.16f, 0.12f);
|
||||
prim.transform.localRotation = Quaternion.Euler(-10f, 0f, 0f);
|
||||
mat.color = new Color(0.95f, 0.78f, 0.08f);
|
||||
BuildWasherLance(parent);
|
||||
break;
|
||||
case ToolType.ThicknessGauge:
|
||||
prim.transform.localScale = new Vector3(0.07f, 0.13f, 0.025f);
|
||||
prim.transform.localRotation = Quaternion.Euler(-25f, -10f, 0f);
|
||||
mat.color = new Color(0.12f, 0.12f, 0.14f);
|
||||
AddScreen(parent, new Vector3(0f, 0.025f, -0.014f), new Color(0.2f, 0.9f, 0.5f));
|
||||
break;
|
||||
case ToolType.OBDScanner:
|
||||
prim.transform.localScale = new Vector3(0.1f, 0.16f, 0.03f);
|
||||
prim.transform.localRotation = Quaternion.Euler(-25f, -10f, 0f);
|
||||
mat.color = new Color(0.85f, 0.35f, 0.08f);
|
||||
AddScreen(parent, new Vector3(0f, 0.03f, -0.017f), new Color(0.3f, 0.7f, 1f));
|
||||
break;
|
||||
}
|
||||
r.sharedMaterial = mat;
|
||||
}
|
||||
|
||||
public void SelectTool(ToolType newTool)
|
||||
{
|
||||
if (GameEconomyManager.Instance != null && !GameEconomyManager.Instance.DiplomaFeatures && IsDiplomaTool(newTool))
|
||||
{
|
||||
GameHUD.Notify("Диагностика доступна в Дипломной версии", GameUI.Muted);
|
||||
return;
|
||||
}
|
||||
currentTool = newTool;
|
||||
UpdateToolVisuals();
|
||||
GameHUD.Notify($"Инструмент: {GetToolName(newTool)}", GameUI.Muted);
|
||||
}
|
||||
|
||||
private void UpdateToolVisuals()
|
||||
{
|
||||
activeToolObj = null;
|
||||
foreach (var kvp in spawnedTools)
|
||||
{
|
||||
bool active = kvp.Key == currentTool && currentTool != ToolType.Hands;
|
||||
if (kvp.Value != null)
|
||||
{
|
||||
kvp.Value.SetActive(active);
|
||||
if (active) activeToolObj = kvp.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
AnimateHandTool();
|
||||
|
||||
bool lmb = Input.GetMouseButton(0) && !GameInputLock.IsLocked;
|
||||
|
||||
// С канистрой в руках подсказками заливки управляет сама канистра
|
||||
PlayerHands hands = GetComponent<PlayerHands>();
|
||||
if (hands != null && hands.IsHoldingCanister)
|
||||
{
|
||||
StopToolEffects();
|
||||
return;
|
||||
}
|
||||
|
||||
if (GameInputLock.IsLocked || currentTool == ToolType.Hands || currentTool == ToolType.Wrench || Input.GetKey(KeyCode.Tab))
|
||||
{
|
||||
hadHitLastFrame = false;
|
||||
StopToolEffects();
|
||||
RestorationHUD.Instance?.Hide();
|
||||
return;
|
||||
}
|
||||
|
||||
switch (currentTool)
|
||||
{
|
||||
case ToolType.PressureWasher: UpdateWasher(lmb); return;
|
||||
case ToolType.ThicknessGauge: UpdateThicknessGauge(); return;
|
||||
case ToolType.OBDScanner: UpdateObdScanner(); return;
|
||||
}
|
||||
|
||||
if (!TryFindTarget(out CarPartVisuals visuals, out Vector3 hitPoint))
|
||||
{
|
||||
hadHitLastFrame = false;
|
||||
StopToolEffects();
|
||||
RestorationHUD.Instance?.Hide();
|
||||
return;
|
||||
}
|
||||
|
||||
CarPart part = visuals.GetComponent<CarPart>();
|
||||
string partName = (part != null && part.Data != null) ? part.DisplayName : CleanName(visuals.gameObject.name);
|
||||
|
||||
bool isCorrect = IsToolMatchingStage(currentTool, visuals.Stage);
|
||||
string hint = GetContextualHint(visuals.Stage, isCorrect);
|
||||
bool working = false;
|
||||
|
||||
// Блокировка кузовных работ по грязному металлу
|
||||
if (visuals.IsDirty)
|
||||
{
|
||||
isCorrect = false;
|
||||
hint = "(!) Деталь грязная! Сначала смойте грязь мойкой высокого давления [Tab]";
|
||||
}
|
||||
else if (lmb)
|
||||
{
|
||||
float moveMultiplier = MoveMultiplier(hitPoint);
|
||||
|
||||
if (moveMultiplier < 0.08f && visuals.Stage != RepairStage.Healthy && visuals.Stage != RepairStage.Repaired)
|
||||
{
|
||||
hint = "Водите инструментом по детали!";
|
||||
}
|
||||
else if (isCorrect)
|
||||
{
|
||||
working = UseTool(visuals, moveMultiplier);
|
||||
}
|
||||
}
|
||||
|
||||
SetToolSound(working, hitPoint);
|
||||
|
||||
lastHitPoint = hitPoint;
|
||||
hadHitLastFrame = true;
|
||||
|
||||
RestorationHUD.Instance?.ShowRestorationProgress(
|
||||
partName,
|
||||
visuals.Stage,
|
||||
visuals.StageProgress,
|
||||
hint,
|
||||
isCorrect);
|
||||
}
|
||||
|
||||
private float MoveMultiplier(Vector3 hitPoint)
|
||||
{
|
||||
float mouseSpeed = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")).magnitude;
|
||||
float worldSpeed = hadHitLastFrame ? (Vector3.Distance(hitPoint, lastHitPoint) / Mathf.Max(Time.deltaTime, 0.001f)) : 0f;
|
||||
return Mathf.Clamp(mouseSpeed * 0.7f + worldSpeed * 2.0f, 0f, 2.2f);
|
||||
}
|
||||
|
||||
private void SetToolSound(bool on, Vector3 pos)
|
||||
{
|
||||
LoopId id = currentTool == ToolType.RustCleaner ? LoopId.Grinder
|
||||
: currentTool == ToolType.SprayCan ? LoopId.Spray
|
||||
: currentTool == ToolType.PressureWasher ? LoopId.Water
|
||||
: LoopId.Sander;
|
||||
if (on)
|
||||
{
|
||||
soundActive = true;
|
||||
ProceduralAudioManager.Instance?.SetLoop(this, id, true, pos, currentTool == ToolType.Putty ? 0.35f : 0.75f);
|
||||
}
|
||||
else if (soundActive)
|
||||
{
|
||||
soundActive = false;
|
||||
if (ProceduralAudioManager.Existing != null) ProceduralAudioManager.Existing.SetLoop(this, id, false, pos);
|
||||
}
|
||||
}
|
||||
|
||||
private void StopToolEffects()
|
||||
{
|
||||
if (washerSpray != null && washerSpray.isPlaying) washerSpray.Stop();
|
||||
if (soundActive)
|
||||
{
|
||||
soundActive = false;
|
||||
if (ProceduralAudioManager.Existing != null) ProceduralAudioManager.Existing.SetLoop(this, LoopId.Water, false, Vector3.zero);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDisable() => StopToolEffects();
|
||||
|
||||
// ===================== МОЙКА ВЫСОКОГО ДАВЛЕНИЯ =====================
|
||||
|
||||
private void UpdateWasher(bool lmb)
|
||||
{
|
||||
EnsureWasherSpray();
|
||||
if (washerSpray != null)
|
||||
{
|
||||
if (lmb && !washerSpray.isPlaying) washerSpray.Play();
|
||||
else if (!lmb && washerSpray.isPlaying) washerSpray.Stop();
|
||||
}
|
||||
|
||||
Vector3 soundPos = playerCam != null ? playerCam.transform.position : transform.position;
|
||||
if (!TryFindTarget(out CarPartVisuals visuals, out Vector3 hitPoint))
|
||||
{
|
||||
SetToolSound(lmb, soundPos);
|
||||
hadHitLastFrame = false;
|
||||
RestorationHUD.Instance?.ShowCustomMessage(lmb ? "Струя воды... Наведите на грязную машину" : "[Удерж. ЛКМ] Мыть • Наведите на кузов или детали машины");
|
||||
return;
|
||||
}
|
||||
|
||||
SetToolSound(lmb, hitPoint);
|
||||
string partName = visuals.GetComponent<CarPart>() != null ? visuals.GetComponent<CarPart>().DisplayName : CleanName(visuals.gameObject.name);
|
||||
|
||||
if (lmb)
|
||||
{
|
||||
float move = MoveMultiplier(hitPoint);
|
||||
if (move < 0.08f && visuals.DirtAmount > 0f)
|
||||
{
|
||||
RestorationHUD.Instance?.ShowCustomMessage($"Водите струей по детали!\n{partName}: грязь {Mathf.RoundToInt(visuals.DirtAmount * 100f)}%");
|
||||
}
|
||||
else
|
||||
{
|
||||
float amount = Time.deltaTime * Mathf.Max(move, 0.3f) / washTime;
|
||||
visuals.Wash(amount);
|
||||
|
||||
// Струя задевает соседние детали в радиусе пятна
|
||||
VehicleInteraction car = visuals.GetComponentInParent<VehicleInteraction>();
|
||||
if (car != null)
|
||||
{
|
||||
foreach (CarPartVisuals v in car.GetComponentsInChildren<CarPartVisuals>())
|
||||
{
|
||||
if (v == visuals) continue;
|
||||
Renderer r = v.GetComponent<Renderer>();
|
||||
if (r != null && r.bounds.SqrDistance(hitPoint) < washRadius * washRadius)
|
||||
v.Wash(amount * 0.6f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lastHitPoint = hitPoint;
|
||||
hadHitLastFrame = true;
|
||||
|
||||
float carDirt = CarDirt(visuals);
|
||||
string state = visuals.DirtAmount <= 0f ? "Чисто — блестит!" : $"Грязь: {Mathf.RoundToInt(visuals.DirtAmount * 100f)}%";
|
||||
RestorationHUD.Instance?.ShowCustomMessage($"Мойка: {partName}\n{state} | Машина в целом: {Mathf.RoundToInt((1f - carDirt) * 100f)}% чистоты");
|
||||
}
|
||||
|
||||
public static float CarDirt(Component anyPart)
|
||||
{
|
||||
VehicleInteraction car = anyPart != null ? anyPart.GetComponentInParent<VehicleInteraction>() : null;
|
||||
if (car == null) return 0f;
|
||||
float sum = 0f;
|
||||
int n = 0;
|
||||
foreach (CarPartVisuals v in car.GetComponentsInChildren<CarPartVisuals>())
|
||||
{
|
||||
if (!v.HasPaintSlots) continue;
|
||||
sum += v.DirtAmount;
|
||||
n++;
|
||||
}
|
||||
return n > 0 ? sum / n : 0f;
|
||||
}
|
||||
|
||||
// ===================== ДИАГНОСТИКА =====================
|
||||
|
||||
private void UpdateThicknessGauge()
|
||||
{
|
||||
if (!TryFindTarget(out CarPartVisuals visuals, out Vector3 hitPoint))
|
||||
{
|
||||
RestorationHUD.Instance?.ShowCustomMessage("Толщиномер ЛКП: приложите датчик к кузовной детали");
|
||||
return;
|
||||
}
|
||||
|
||||
CarPart part = visuals.GetComponent<CarPart>();
|
||||
string partName = part != null ? part.DisplayName : CleanName(visuals.gameObject.name);
|
||||
int microns = visuals.PaintThicknessMicrons;
|
||||
string verdict;
|
||||
if (visuals.Stage == RepairStage.Cleaned) verdict = "<color=#9AA0A6>Голый металл</color>";
|
||||
else if (microns < 90) verdict = "<color=#E5534B>Коррозия, ЛКП разрушено</color>";
|
||||
else if (microns <= 160) verdict = "<color=#4CD07D>Заводской окрас</color>";
|
||||
else if (microns <= 500) verdict = "<color=#F2A93B>Перекрас / шпаклёвка</color>";
|
||||
else verdict = "<color=#E5534B>Толстый слой шпаклёвки</color>";
|
||||
|
||||
CarOwnership own = CarOwnership.Get(visuals.gameObject);
|
||||
if (own != null)
|
||||
{
|
||||
own.thicknessChecked = true;
|
||||
if (visuals.HiddenRepaint && visuals.Stage == RepairStage.Healthy && !own.hiddenRepaintFound)
|
||||
{
|
||||
own.hiddenRepaintFound = true;
|
||||
GameHUD.Notify($"Найден скрытый перекрас: {partName} ({microns} мкм) — аргумент для торга!", GameUI.Accent);
|
||||
}
|
||||
}
|
||||
|
||||
RestorationHUD.Instance?.ShowCustomMessage($"Толщиномер ЛКП — {partName}\n{microns} мкм • {verdict}");
|
||||
}
|
||||
|
||||
private void UpdateObdScanner()
|
||||
{
|
||||
if (playerCam == null) return;
|
||||
Ray ray = new Ray(playerCam.transform.position, playerCam.transform.forward);
|
||||
VehicleInteraction car = null;
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, toolRange + 1.5f, ~0, QueryTriggerInteraction.Collide))
|
||||
car = hit.collider.GetComponentInParent<VehicleInteraction>();
|
||||
|
||||
if (car == null)
|
||||
{
|
||||
RestorationHUD.Instance?.ShowCustomMessage("OBD-сканер: наведитесь на автомобиль, чтобы подключиться к диагностическому разъему");
|
||||
return;
|
||||
}
|
||||
|
||||
EngineBayManager bay = car.GetComponent<EngineBayManager>();
|
||||
if (bay == null)
|
||||
{
|
||||
RestorationHUD.Instance?.ShowCustomMessage("OBD-сканер: у этой машины нет диагностического разъема");
|
||||
return;
|
||||
}
|
||||
|
||||
CarOwnership own = car.GetComponent<CarOwnership>();
|
||||
if (own != null && !own.obdScanned)
|
||||
{
|
||||
own.obdScanned = true;
|
||||
GameHUD.Notify("Диагностика OBD выполнена — ошибки двигателя учтены при торге", GameUI.Blue);
|
||||
}
|
||||
|
||||
var codes = bay.GetObdCodes();
|
||||
string body = codes.Count == 0
|
||||
? "<color=#4CD07D>Ошибок не обнаружено. Двигатель исправен.</color>"
|
||||
: "<color=#E5534B>" + string.Join("\n", codes) + "</color>";
|
||||
RestorationHUD.Instance?.ShowCustomMessage($"OBD-II сканер — ошибок: {codes.Count}\n{body}");
|
||||
}
|
||||
|
||||
private void AnimateHandTool()
|
||||
{
|
||||
if (toolHandAnchor == null) return;
|
||||
|
||||
if (activeToolObj != null && Input.GetMouseButton(0))
|
||||
{
|
||||
float t = Time.time;
|
||||
Vector3 offset = (currentTool == ToolType.RustCleaner || currentTool == ToolType.Sander)
|
||||
? new Vector3(Mathf.Sin(t * 50f), Mathf.Cos(t * 60f), 0f) * 0.008f
|
||||
: new Vector3(Mathf.Sin(t * 12f) * 0.02f, Mathf.Cos(t * 8f) * 0.012f, 0f);
|
||||
|
||||
toolHandAnchor.localPosition = Vector3.Lerp(toolHandAnchor.localPosition, handAnchorLocalPos + offset, Time.deltaTime * 20f);
|
||||
|
||||
// Вращение кордщетки на машинке для зачистки
|
||||
if (currentTool == ToolType.RustCleaner)
|
||||
{
|
||||
Transform brush = activeToolObj.transform.Find("BrushPivot");
|
||||
if (brush != null) brush.Rotate(0f, 0f, 1800f * Time.deltaTime, Space.Self);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
toolHandAnchor.localPosition = Vector3.Lerp(toolHandAnchor.localPosition, handAnchorLocalPos, Time.deltaTime * 12f);
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryFindTarget(out CarPartVisuals visuals, out Vector3 hitPoint)
|
||||
{
|
||||
visuals = null;
|
||||
hitPoint = Vector3.zero;
|
||||
if (playerCam == null) return false;
|
||||
|
||||
Ray ray = new Ray(playerCam.transform.position, playerCam.transform.forward);
|
||||
RaycastHit[] hits = Physics.RaycastAll(ray, toolRange, interactableLayer, QueryTriggerInteraction.Collide);
|
||||
System.Array.Sort(hits, (a, b) => a.distance.CompareTo(b.distance));
|
||||
|
||||
foreach (RaycastHit hit in hits)
|
||||
{
|
||||
if (hit.collider.GetComponentInParent<PlayerToolManager>() != null) continue;
|
||||
|
||||
// Деталь под лучом, иначе ближайшая часть основного кузова этой машины
|
||||
CarPartVisuals v = CarPartVisuals.FindAt(hit.collider, hit.point);
|
||||
if (v != null)
|
||||
{
|
||||
visuals = v;
|
||||
hitPoint = hit.point;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Твердая поверхность без кузовной краски (стена, асфальт) перекрывает всё, что за ней
|
||||
if (!hit.collider.isTrigger) break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool UseTool(CarPartVisuals visuals, float speedMult)
|
||||
{
|
||||
float dt = Time.deltaTime * speedMult;
|
||||
|
||||
switch (currentTool)
|
||||
{
|
||||
case ToolType.RustCleaner: return visuals.CleanRust(dt / cleanTime);
|
||||
case ToolType.Putty: return visuals.ApplyPutty(dt / puttyTime);
|
||||
case ToolType.Sander: return visuals.Sand(dt / sandTime);
|
||||
case ToolType.SprayCan:
|
||||
if (visuals.Stage == RepairStage.Sanded) return visuals.PaintRepair(dt / paintTime);
|
||||
return visuals.Recolor(sprayPaintColor);
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsToolMatchingStage(ToolType tool, RepairStage stage)
|
||||
{
|
||||
switch (stage)
|
||||
{
|
||||
case RepairStage.Rusted: return tool == ToolType.RustCleaner;
|
||||
case RepairStage.Cleaned: return tool == ToolType.Putty;
|
||||
case RepairStage.Puttied: return tool == ToolType.Sander;
|
||||
case RepairStage.Sanded: return tool == ToolType.SprayCan;
|
||||
case RepairStage.Healthy:
|
||||
case RepairStage.Repaired:
|
||||
return tool == ToolType.SprayCan; // Баллончик может перекрашивать
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
private string GetContextualHint(RepairStage stage, bool isCorrectTool)
|
||||
{
|
||||
if (stage == RepairStage.Healthy || stage == RepairStage.Repaired)
|
||||
{
|
||||
return (currentTool == ToolType.SprayCan)
|
||||
? "[Удерж. ЛКМ] Перекрасить деталь в цвет баллончика"
|
||||
: "Деталь в отличном состоянии, ремонт не требуется";
|
||||
}
|
||||
|
||||
if (!isCorrectTool)
|
||||
{
|
||||
return $"(!) Нужен инструмент: {RequiredToolName(stage)} [Нажмите TAB]";
|
||||
}
|
||||
|
||||
switch (stage)
|
||||
{
|
||||
case RepairStage.Rusted: return "[Удерж. ЛКМ] Зачистить ржавчину • Водите кордщёткой по детали";
|
||||
case RepairStage.Cleaned: return "[Удерж. ЛКМ] Нанести шпаклёвку • Заполните зачищенный металл";
|
||||
case RepairStage.Puttied: return "[Удерж. ЛКМ] Зашлифовать шпаклёвку • Выровняйте поверхность";
|
||||
case RepairStage.Sanded: return "[Удерж. ЛКМ] Нанести автоэмаль • Равномерно распыляйте краску";
|
||||
default: return "[Удерж. ЛКМ] Водите инструментом по детали";
|
||||
}
|
||||
}
|
||||
|
||||
private static string RequiredToolName(RepairStage stage)
|
||||
{
|
||||
switch (stage)
|
||||
{
|
||||
case RepairStage.Rusted: return "Зачистка ржавчины (Кордщётка)";
|
||||
case RepairStage.Cleaned: return "Шпатель (Шпаклёвка)";
|
||||
case RepairStage.Puttied: return "Шлифовальный брусок";
|
||||
case RepairStage.Sanded: return "Баллончик краски";
|
||||
default: return "Руки";
|
||||
}
|
||||
}
|
||||
|
||||
private static string CleanName(string raw)
|
||||
{
|
||||
string n = raw.ToLowerInvariant();
|
||||
if (n.Contains("door_lf") || n.Contains("door_fl") || n.Contains("door_l")) return "Передняя левая дверь";
|
||||
if (n.Contains("door_rf") || n.Contains("door_fr") || n.Contains("door_r")) return "Передняя правая дверь";
|
||||
if (n.Contains("door_lr") || n.Contains("door_rl")) return "Задняя левая дверь";
|
||||
if (n.Contains("door_rr")) return "Задняя правая дверь";
|
||||
if (n.Contains("hood")) return "Капот";
|
||||
if (n.Contains("trunk") || n.Contains("tailgate")) return "Крышка багажника";
|
||||
if (n.Contains("fender_l")) return "Переднее левое крыло";
|
||||
if (n.Contains("fender_r")) return "Переднее правое крыло";
|
||||
if (n.Contains("bamper_f") || n.Contains("bumper_f")) return "Передний бампер";
|
||||
if (n.Contains("bamper_b") || n.Contains("bumper_b")) return "Задний бампер";
|
||||
if (n.Contains("body")) return "Кузов";
|
||||
return raw;
|
||||
}
|
||||
|
||||
public void SetSprayColor(Color color) => sprayPaintColor = color;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 79b9bf3c26bc4f38a11491b3776b8121
|
||||
timeCreated: 1791393489
|
||||
@@ -0,0 +1,184 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
/// <summary>
|
||||
/// Радиальное меню инструментов (удерживать Tab, выбрать мышью, отпустить).
|
||||
/// Рисуется через OnGUI, поэтому работает для любого количества инструментов
|
||||
/// (руки, зачистка, шпатель, наждачка, баллончик, ключ, мойка Керхер, толщиномер, OBD-сканер).
|
||||
/// Колесо мыши и клавиши 1–9 — быстрый выбор.
|
||||
/// </summary>
|
||||
public class ToolRadialMenu : MonoBehaviour
|
||||
{
|
||||
[Header("Ссылки")]
|
||||
[Tooltip("Старая панель uGUI (скрывается — меню рисуется процедурно)")]
|
||||
[SerializeField] private GameObject menuPanel;
|
||||
[SerializeField] private PlayerToolManager toolManager;
|
||||
[SerializeField] private Image[] sectorIcons;
|
||||
|
||||
[Header("Цвета выделения")]
|
||||
[SerializeField] private Color normalColor = Color.white;
|
||||
[SerializeField] private Color selectedColor = Color.yellow;
|
||||
|
||||
private int selectedIndex = 0;
|
||||
private bool isMenuOpen = false;
|
||||
private readonly List<ToolType> tools = new List<ToolType>();
|
||||
|
||||
private static readonly string[] Icons = { "Р", "З", "Ш", "Н", "Б", "К", "М", "Т", "OBD" };
|
||||
|
||||
private void Start()
|
||||
{
|
||||
if (menuPanel != null) menuPanel.SetActive(false);
|
||||
if (toolManager == null) toolManager = FindAnyObjectByType<PlayerToolManager>();
|
||||
}
|
||||
|
||||
private void RebuildToolList()
|
||||
{
|
||||
tools.Clear();
|
||||
bool diploma = GameEconomyManager.Instance == null || GameEconomyManager.Instance.DiplomaFeatures;
|
||||
foreach (ToolType t in System.Enum.GetValues(typeof(ToolType)))
|
||||
{
|
||||
if (!diploma && PlayerToolManager.IsDiplomaTool(t)) continue;
|
||||
tools.Add(t);
|
||||
}
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (toolManager == null) toolManager = FindAnyObjectByType<PlayerToolManager>();
|
||||
if (toolManager == null || !toolManager.isActiveAndEnabled) return;
|
||||
|
||||
bool otherWindowOpen = GameInputLock.IsLockedByOther(this);
|
||||
|
||||
// Открытие/закрытие по клавише Tab
|
||||
if (Input.GetKeyDown(KeyCode.Tab) && !otherWindowOpen)
|
||||
{
|
||||
OpenMenu();
|
||||
}
|
||||
else if (isMenuOpen && (Input.GetKeyUp(KeyCode.Tab) || otherWindowOpen))
|
||||
{
|
||||
CloseMenuAndApply();
|
||||
}
|
||||
|
||||
if (isMenuOpen)
|
||||
{
|
||||
CalculateMouseSector();
|
||||
return;
|
||||
}
|
||||
|
||||
if (otherWindowOpen) return;
|
||||
|
||||
// Быстрый выбор: колесо мыши и цифры
|
||||
if (tools.Count == 0) RebuildToolList();
|
||||
float wheel = Input.mouseScrollDelta.y;
|
||||
if (Mathf.Abs(wheel) > 0.01f && tools.Count > 0)
|
||||
{
|
||||
int cur = Mathf.Max(0, tools.IndexOf(toolManager.currentTool));
|
||||
int next = (cur + (wheel < 0 ? 1 : -1) + tools.Count) % tools.Count;
|
||||
toolManager.SelectTool(tools[next]);
|
||||
}
|
||||
|
||||
for (int i = 0; i < Mathf.Min(9, tools.Count); i++)
|
||||
{
|
||||
if (Input.GetKeyDown(KeyCode.Alpha1 + i))
|
||||
toolManager.SelectTool(tools[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private void OpenMenu()
|
||||
{
|
||||
RebuildToolList();
|
||||
isMenuOpen = true;
|
||||
selectedIndex = Mathf.Max(0, tools.IndexOf(toolManager.currentTool));
|
||||
GameInputLock.Lock(this);
|
||||
}
|
||||
|
||||
private void CalculateMouseSector()
|
||||
{
|
||||
if (tools.Count == 0) return;
|
||||
|
||||
Vector2 screenCenter = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f);
|
||||
Vector2 mouseDelta = (Vector2)Input.mousePosition - screenCenter;
|
||||
|
||||
// Если мышь почти в центре - ничего не меняем
|
||||
if (mouseDelta.magnitude < 40f * GameUI.Scale) return;
|
||||
|
||||
// Угол от верхней точки по часовой стрелке
|
||||
float angle = Mathf.Atan2(mouseDelta.x, mouseDelta.y) * Mathf.Rad2Deg;
|
||||
if (angle < 0) angle += 360f;
|
||||
|
||||
float sectorSize = 360f / tools.Count;
|
||||
selectedIndex = Mathf.Clamp(Mathf.FloorToInt((angle + sectorSize * 0.5f) % 360f / sectorSize), 0, tools.Count - 1);
|
||||
}
|
||||
|
||||
private void CloseMenuAndApply()
|
||||
{
|
||||
isMenuOpen = false;
|
||||
GameInputLock.Unlock(this);
|
||||
|
||||
if (tools.Count > 0 && selectedIndex < tools.Count && tools[selectedIndex] != toolManager.currentTool)
|
||||
toolManager.SelectTool(tools[selectedIndex]);
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
if (isMenuOpen)
|
||||
{
|
||||
isMenuOpen = false;
|
||||
GameInputLock.Unlock(this);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnGUI()
|
||||
{
|
||||
if (!isMenuOpen || tools.Count == 0) return;
|
||||
GameUI.Begin(-5);
|
||||
|
||||
float cx = GameUI.VirtualWidth * 0.5f;
|
||||
float cy = GameUI.VirtualHeight * 0.5f;
|
||||
float radius = 250f;
|
||||
|
||||
GUI.DrawTexture(new Rect(cx - radius - 90, cy - radius - 90, (radius + 90) * 2, (radius + 90) * 2),
|
||||
GameUI.Rounded(GameUI.Bg.WithAlpha(0.72f), null, 60, 0));
|
||||
|
||||
GUI.Label(new Rect(cx - 160, cy - 40, 320, 40), "ИНСТРУМЕНТЫ", GameUI.Header.WithCenter());
|
||||
if (selectedIndex < tools.Count)
|
||||
GUI.Label(new Rect(cx - 170, cy, 340, 60), PlayerToolManager.GetToolName(tools[selectedIndex]), GameUI.LabelCenter);
|
||||
|
||||
for (int i = 0; i < tools.Count; i++)
|
||||
{
|
||||
float a = (360f / tools.Count) * i * Mathf.Deg2Rad;
|
||||
Vector2 p = new Vector2(cx + Mathf.Sin(a) * radius, cy - Mathf.Cos(a) * radius);
|
||||
bool sel = i == selectedIndex;
|
||||
float size = sel ? 128f : 108f;
|
||||
Rect r = new Rect(p.x - size * 0.5f, p.y - size * 0.5f, size, size);
|
||||
|
||||
Color fill = sel ? GameUI.Accent : GameUI.PanelLight;
|
||||
GUI.DrawTexture(r, GameUI.Rounded(fill, sel ? Color.white : GameUI.Hex("3A3F4A"), 18, 2));
|
||||
|
||||
int idx = (int)tools[i];
|
||||
string icon = idx < Icons.Length ? Icons[idx] : "•";
|
||||
GUIStyle st = new GUIStyle(GameUI.LabelCenter) { fontSize = sel ? 34 : 30, normal = { textColor = sel ? GameUI.Bg : GameUI.TextColor } };
|
||||
GUI.Label(new Rect(r.x, r.y + 6, r.width, r.height * 0.55f), icon, st);
|
||||
GUIStyle sm = new GUIStyle(GameUI.SmallCenter) { fontSize = 13, wordWrap = true, normal = { textColor = sel ? GameUI.Bg : GameUI.Muted } };
|
||||
GUI.Label(new Rect(r.x + 4, r.y + r.height * 0.55f, r.width - 8, r.height * 0.42f), $"{i + 1}. {ShortName(tools[i])}", sm);
|
||||
}
|
||||
}
|
||||
|
||||
private static string ShortName(ToolType t)
|
||||
{
|
||||
switch (t)
|
||||
{
|
||||
case ToolType.Hands: return "Руки";
|
||||
case ToolType.RustCleaner: return "Зачистка";
|
||||
case ToolType.Putty: return "Шпатель";
|
||||
case ToolType.Sander: return "Наждачка";
|
||||
case ToolType.SprayCan: return "Баллончик";
|
||||
case ToolType.Wrench: return "Ключ";
|
||||
case ToolType.PressureWasher: return "Мойка";
|
||||
case ToolType.ThicknessGauge: return "Толщиномер";
|
||||
case ToolType.OBDScanner: return "OBD-сканер";
|
||||
default: return t.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 2836 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user