216 lines
11 KiB
C#
216 lines
11 KiB
C#
using System.Collections.Generic;
|
||
using UnityEngine;
|
||
|
||
/// <summary>
|
||
/// Игровой HUD (OnGUI): счет в $/BYN, часы и день, уведомления, подсказки клавиш, текущий инструмент
|
||
/// и приборная панель автомобиля (скорость, запуск, индикаторы АКБ, масла, перегрева, тормозов, фар).
|
||
/// </summary>
|
||
public class GameHUD : MonoBehaviour
|
||
{
|
||
private struct Toast
|
||
{
|
||
public string text;
|
||
public Color color;
|
||
public float time;
|
||
}
|
||
|
||
private static readonly List<Toast> toasts = new List<Toast>();
|
||
private static string contextHint;
|
||
private static int contextHintFrame = -1;
|
||
private bool showVictory;
|
||
|
||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
|
||
private static void ResetStatics()
|
||
{
|
||
toasts.Clear();
|
||
contextHint = null;
|
||
}
|
||
|
||
public static void Notify(string text, Color color)
|
||
{
|
||
if (string.IsNullOrEmpty(text)) return;
|
||
if (toasts.Count > 0 && toasts[toasts.Count - 1].text == text)
|
||
{
|
||
Toast t = toasts[toasts.Count - 1];
|
||
t.time = Time.unscaledTime;
|
||
toasts[toasts.Count - 1] = t;
|
||
return;
|
||
}
|
||
toasts.Add(new Toast { text = text, color = color, time = Time.unscaledTime });
|
||
if (toasts.Count > 5) toasts.RemoveAt(0);
|
||
}
|
||
|
||
/// <summary>Подсказка над прицелом на текущий кадр (зона продажи, сделка и т.п.).</summary>
|
||
public static void SetContextHint(string text)
|
||
{
|
||
contextHint = text;
|
||
contextHintFrame = Time.frameCount;
|
||
}
|
||
|
||
private void Start()
|
||
{
|
||
if (GameEconomyManager.Instance != null)
|
||
GameEconomyManager.Instance.OnAutosalonOpened += () =>
|
||
{
|
||
showVictory = true;
|
||
GameInputLock.Lock(this);
|
||
};
|
||
}
|
||
|
||
private void OnGUI()
|
||
{
|
||
MainMenuAndBootManager menu = MainMenuAndBootManager.Instance;
|
||
if (menu != null && !menu.IsPlaying) return;
|
||
|
||
GameUI.Begin(10);
|
||
float w = GameUI.VirtualWidth;
|
||
float h = GameUI.VirtualHeight;
|
||
GameEconomyManager eco = GameEconomyManager.Instance;
|
||
|
||
// ---- Счет ----
|
||
string moneyText;
|
||
if (eco == null) moneyText = "";
|
||
else if (eco.Unlimited) moneyText = "<b>СВОБОДНЫЙ РЕЖИМ</b> <color=#9AA0A6>(Курсовая версия)</color>";
|
||
else moneyText = $"<b><color=#4CD07D>{eco.FormatMoney(eco.Money)}</color></b> <color=#9AA0A6>Цель: Автосалон {eco.FormatShort(eco.AutosalonGoal)}</color>";
|
||
if (!string.IsNullOrEmpty(moneyText))
|
||
GUI.Label(new Rect(20, 18, 760, 46), moneyText, GameUI.Badge);
|
||
|
||
// ---- Время ----
|
||
TimeAndWeatherManager tw = TimeAndWeatherManager.Instance;
|
||
if (tw != null)
|
||
GUI.Label(new Rect(w - 290, 18, 270, 46), $"<b>{tw.ClockText}</b> День {tw.Day}", GameUI.Badge.WithCenter());
|
||
|
||
// ---- Уведомления ----
|
||
float y = 80f;
|
||
for (int i = toasts.Count - 1; i >= 0; i--)
|
||
{
|
||
float age = Time.unscaledTime - toasts[i].time;
|
||
if (age > 5f)
|
||
{
|
||
toasts.RemoveAt(i);
|
||
continue;
|
||
}
|
||
}
|
||
foreach (Toast t in toasts)
|
||
{
|
||
float age = Time.unscaledTime - t.time;
|
||
float alpha = Mathf.Clamp01(5f - age);
|
||
Color prev = GUI.color;
|
||
GUI.color = new Color(1f, 1f, 1f, alpha);
|
||
GUI.Label(new Rect(20, y, 640, 40), $"<color=#{ColorUtility.ToHtmlStringRGB(t.color)}>■</color> {t.text}", GameUI.Badge);
|
||
GUI.color = prev;
|
||
y += 46f;
|
||
}
|
||
|
||
// ---- Контекстная подсказка ----
|
||
if (contextHintFrame >= Time.frameCount - 1 && !string.IsNullOrEmpty(contextHint))
|
||
GUI.Label(new Rect(w * 0.5f - 420, h * 0.5f + 160, 840, 46), contextHint, GameUI.Badge.WithCenter());
|
||
|
||
VehicleInteraction car = VehicleInteraction.Current;
|
||
if (car != null) DrawDashboard(car, w, h);
|
||
else DrawOnFoot(w, h);
|
||
|
||
if (showVictory && eco != null) DrawVictory(eco, w, h);
|
||
}
|
||
|
||
private void DrawOnFoot(float w, float h)
|
||
{
|
||
PlayerToolManager tm = PlayerToolManager.Instance;
|
||
if (tm != null)
|
||
{
|
||
string usage = ToolUsage(tm.currentTool);
|
||
GUIStyle st = new GUIStyle(GameUI.Badge) { wordWrap = true };
|
||
string text = $"<b>{PlayerToolManager.GetToolName(tm.currentTool)}</b> <color=#9AA0A6>[Tab] / [1–9]</color>\n<size=14><color=#C9CDD2>{usage}</color></size>";
|
||
float th = st.CalcHeight(new GUIContent(text), 450f);
|
||
GUI.Label(new Rect(w - 470, h - 80 - th, 450, th), text, st);
|
||
}
|
||
|
||
bool diploma = GameEconomyManager.Instance == null || GameEconomyManager.Instance.DiplomaFeatures;
|
||
string keys = "[M] Планшет [Tab] Инструменты [E] Действие [F] Сесть [G] Положить [Ctrl] Присесть [T] Такси [H] Подсказки [Esc] Меню";
|
||
if (diploma) keys += " [K] Магазин/Склад [B] Сделка";
|
||
GUI.Label(new Rect(20, h - 44, w - 520, 30), keys, GameUI.Small);
|
||
}
|
||
|
||
private void DrawDashboard(VehicleInteraction car, float w, float h)
|
||
{
|
||
CarController cc = car.Controller;
|
||
if (cc == null) return;
|
||
EngineBayManager bay = cc.EngineBay;
|
||
CarLightingController lights = car.GetComponent<CarLightingController>();
|
||
|
||
Rect panel = new Rect(w * 0.5f - 330, h - 150, 660, 130);
|
||
GUI.Box(panel, GUIContent.none, GameUI.Panel);
|
||
|
||
GUIStyle big = new GUIStyle(GameUI.Title) { fontSize = 54, alignment = TextAnchor.MiddleLeft };
|
||
GUI.Label(new Rect(panel.x + 24, panel.y + 10, 220, 70), $"{cc.SpeedKmH:F0}", big);
|
||
GUI.Label(new Rect(panel.x + 26, panel.y + 74, 200, 30), "км/ч", GameUI.Small);
|
||
|
||
string engine = cc.EngineRunning ? "<color=#4CD07D>ДВИГАТЕЛЬ РАБОТАЕТ</color>" : "<color=#9AA0A6>Двигатель заглушен — [W] завести</color>";
|
||
GUI.Label(new Rect(panel.x + 200, panel.y + 14, 440, 30), engine, GameUI.Label);
|
||
|
||
float ix = panel.x + 200;
|
||
float iy = panel.y + 56;
|
||
Indicator(ref ix, iy, "АКБ", bay != null && bay.BatteryWarning);
|
||
Indicator(ref ix, iy, "МАСЛО", bay != null && bay.OilWarning);
|
||
Indicator(ref ix, iy, "t° ОЖ", bay != null && bay.TempWarning);
|
||
Indicator(ref ix, iy, "(!) ТОРМ", bay != null && bay.BrakeWarning);
|
||
string lightText = lights == null ? "ФАРЫ" : (lights.Mode == CarLightingController.HeadlightMode.High ? "ДАЛЬНИЙ" : (lights.Mode == CarLightingController.HeadlightMode.Low ? "БЛИЖНИЙ" : "ФАРЫ"));
|
||
Indicator(ref ix, iy, lightText, lights != null && lights.Mode != CarLightingController.HeadlightMode.Off, GameUI.Blue);
|
||
|
||
if (cc.DashboardMessageTimer > 0f && !string.IsNullOrEmpty(cc.DashboardMessage))
|
||
{
|
||
Rect msg = new Rect(w * 0.5f - 420, h - 214, 840, 52);
|
||
GUI.Label(msg, $"<b>{cc.DashboardMessage}</b>", GameUI.Badge.WithCenter());
|
||
}
|
||
|
||
if (bay != null && bay.IsOverheating)
|
||
GUI.Label(new Rect(w * 0.5f - 420, h - 270, 840, 50), "<color=#E5534B><b>ПЕРЕГРЕВ ДВИГАТЕЛЯ! Скорость ограничена. Долейте антифриз</b></color>", GameUI.Badge.WithCenter());
|
||
|
||
GUI.Label(new Rect(20, h - 44, w - 40, 30), "[W/S] Газ/Тормоз [A/D] Руль [Space] Ручник [L] Фары [F] Выйти [M] Планшет [Enter] Продать на площадке", GameUI.Small);
|
||
}
|
||
|
||
private static void Indicator(ref float x, float y, string label, bool active, Color? onColor = null)
|
||
{
|
||
Color c = active ? (onColor ?? GameUI.Red) : GameUI.Hex("2A2E37");
|
||
Rect r = new Rect(x, y, 84, 40);
|
||
GUI.DrawTexture(r, GameUI.Rounded(c, null, 6, 0));
|
||
GUIStyle st = new GUIStyle(GameUI.SmallCenter) { fontSize = 14, fontStyle = FontStyle.Bold, normal = { textColor = active ? Color.white : GameUI.Muted } };
|
||
GUI.Label(r, label, st);
|
||
x += 90f;
|
||
}
|
||
|
||
private void DrawVictory(GameEconomyManager eco, float w, float h)
|
||
{
|
||
GameUI.DrawRect(new Rect(0, 0, w, h), GameUI.Bg.WithAlpha(0.7f));
|
||
Rect r = new Rect(w * 0.5f - 420, h * 0.5f - 230, 840, 460);
|
||
GUI.Box(r, GUIContent.none, GameUI.PanelSolid);
|
||
GUI.Label(new Rect(r.x, r.y + 30, r.width, 60), "АВТОСАЛОН ОТКРЫТ!", GameUI.Title);
|
||
GUI.Label(new Rect(r.x + 50, r.y + 120, r.width - 100, 200),
|
||
$"Поздравляем! Вы прошли путь от гаражного перекупа до владельца собственного автосалона.\n\n" +
|
||
$"Сделок: {eco.DealsCompleted}\nЧистая прибыль: {eco.FormatMoney(eco.TotalProfit)}\nНа счету: {eco.FormatMoney(eco.Money)}",
|
||
GameUI.LabelCenter);
|
||
if (GameUI.Btn(new Rect(r.x + 220, r.y + 360, 400, 60), "ПРОДОЛЖИТЬ ИГРУ", GameUI.ButtonAccent))
|
||
{
|
||
showVictory = false;
|
||
GameInputLock.Unlock(this);
|
||
}
|
||
}
|
||
|
||
private static string ToolUsage(ToolType t)
|
||
{
|
||
switch (t)
|
||
{
|
||
case ToolType.Hands: return "Брать детали и канистры [E], снимать агрегаты [удерж. E], открывать капот/двери [E]";
|
||
case ToolType.RustCleaner: return "Этап 1: зажмите ЛКМ и водите по ржавчине до голого металла";
|
||
case ToolType.Putty: return "Этап 2: шпаклюйте зачищенный металл — ЛКМ и движение мышью";
|
||
case ToolType.Sander: return "Этап 3: шлифуйте шпаклевку до ровной поверхности";
|
||
case ToolType.SprayCan: return "Этап 4: покраска в родной цвет. По целой детали — перекраска";
|
||
case ToolType.Wrench: return "Колесные болты и свечи/генератор/радиатор: ЛКМ или удерж. E";
|
||
case ToolType.PressureWasher: return "Зажмите ЛКМ и водите струей по кузову — грязь смывается";
|
||
case ToolType.ThicknessGauge: return "Наведите на панель: 95–120 мкм — завод, 250–450 — перекрас";
|
||
case ToolType.OBDScanner: return "Наведите на машину — коды ошибок двигателя";
|
||
default: return "";
|
||
}
|
||
}
|
||
}
|