using System.Collections.Generic; using UnityEngine; /// /// Помощник игрока: панель «ЧТО ДЕЛАТЬ» с текущей задачей и чек-листом восстановления, /// экранные указатели к цели (встреча с продавцом, гараж, площадка продажи) и подписи над объектами гаража. /// [H] — свернуть/развернуть панель. /// public class GuideSystem : MonoBehaviour { private class Step { public bool done; public string text; } private struct NavTarget { public Vector3 pos; public string label; public Color color; } [SerializeField] private KeyCode toggleKey = KeyCode.H; public static GuideSystem Instance { get; private set; } private bool collapsed; private float refreshTimer; private string headline = ""; private string action = ""; private readonly List steps = new List(); private readonly List navTargets = new List(); private Transform player; private Camera cachedCam; private CarSellZone sellZone; private void Awake() => Instance = this; private void OnDestroy() { if (Instance == this) Instance = null; } private void Update() { if (Input.GetKeyDown(toggleKey) && !GameInputLock.IsLocked) collapsed = !collapsed; refreshTimer -= Time.unscaledDeltaTime; if (refreshTimer <= 0f) { refreshTimer = 0.4f; Refresh(); } } private Vector3 PlayerPos { get { if (VehicleInteraction.Current != null) return VehicleInteraction.Current.transform.position; if (player == null) { PlayerMovement pm = FindAnyObjectByType(); if (pm != null) player = pm.transform; } return player != null ? player.position : Vector3.zero; } } private static string Key(string k) => $"[{k}]"; // ===================== ЛОГИКА ЗАДАЧ ===================== private void Refresh() { steps.Clear(); navTargets.Clear(); GameEconomyManager eco = GameEconomyManager.Instance; CarMarketManager market = FindAnyObjectByType(); if (sellZone == null) sellZone = FindAnyObjectByType(); Vector3 pp = PlayerPos; Vector3 garagePos = eco != null && eco.garageCenter != null ? eco.garageCenter.position : Vector3.zero; // Машина игрока: приоритет — стоящая в гараже CarOwnership car = null; foreach (CarOwnership c in CarOwnership.All) { if (c == null || !c.isOwned) continue; if (car == null || (eco != null && eco.IsInGarage(c.transform.position) && !eco.IsInGarage(car.transform.position))) car = c; } CarListing meeting = market != null ? market.ActiveMeetingListing : null; CarOwnership meetingCar = meeting != null && meeting.spawnedInstance != null ? meeting.spawnedInstance.GetComponent() : null; if (meetingCar != null && meetingCar.isOwned) meetingCar = null; if (car != null && (meetingCar == null || eco == null || eco.IsInGarage(car.transform.position))) { BuildRestorationSteps(car, eco, garagePos, pp); return; } if (meetingCar != null) { float dist = Vector3.Distance(pp, meetingCar.transform.position); if (dist > 15f) { headline = $"Встреча с продавцом: {meetingCar.carTitle}"; action = $"Идите к зеленой метке ({dist:F0} м) или вызовите такси {Key("T")}."; navTargets.Add(new NavTarget { pos = meetingCar.transform.position + Vector3.up * 1.5f, label = "Продавец", color = GameUI.Green }); } else { headline = $"Осмотр: {meetingCar.carTitle} — {GameUI.Money(meetingCar.askingPrice).Split(' ')[0]}"; action = $"Найдите дефекты, чтобы сбить цену, затем нажмите {Key("B")} — торг и покупка."; } steps.Add(new Step { done = dist <= 15f, text = "Доехать до продавца" }); steps.Add(new Step { done = true, text = "Осмотреть кузов и колеса (ржавчина, спущенные шины) — видно сразу" }); steps.Add(new Step { done = meetingCar.hoodInspected, text = $"Открыть капот {Key("E")} и проверить масляный щуп" }); steps.Add(new Step { done = meetingCar.obdScanned, text = $"OBD-сканер {Key("9")}: навести на машину — коды ошибок" }); steps.Add(new Step { done = meetingCar.thicknessChecked, text = $"Толщиномер {Key("8")}: проверить панели на перекрас" }); steps.Add(new Step { done = false, text = $"{Key("B")} Торговаться и купить (можно с эвакуатором)" }); return; } // Ничего нет — ищем машину на рынке headline = "Найдите машину на перепродажу"; action = $"Откройте планшет {Key("M")} → «АвтоБазар», выберите объявление и нажмите «Договориться о встрече»."; steps.Add(new Step { done = false, text = $"Планшет авторынка {Key("M")}" }); steps.Add(new Step { done = false, text = "Выбрать недорогую машину с дефектами — на ней больше заработок" }); steps.Add(new Step { done = false, text = "«Договориться о встрече» — появится GPS-метка" }); if (eco != null && !eco.Unlimited) steps.Add(new Step { done = false, text = $"На счету {eco.FormatShort(eco.Money)} — цель {eco.FormatShort(eco.AutosalonGoal)} (Автосалон)" }); } private void BuildRestorationSteps(CarOwnership car, GameEconomyManager eco, Vector3 garagePos, Vector3 pp) { bool inGarage = eco == null || eco.IsInGarage(car.transform.position); if (!inGarage) { headline = $"Доставьте {car.carTitle} в гараж"; action = $"Сядьте {Key("F")} и езжайте к метке «Гараж». Если машина не на ходу — купите эвакуатор при сделке или вызовите такси {Key("T")} и вернитесь позже."; navTargets.Add(new NavTarget { pos = garagePos + Vector3.up * 2f, label = "Гараж №17", color = GameUI.Accent }); steps.Add(new Step { done = false, text = "Пригнать машину в гаражный кооператив" }); return; } CarInspection.SaleReport r = CarInspection.EvaluateForSale(car); headline = $"Восстановление: {car.carTitle} ({Mathf.RoundToInt(r.score * 100f)}%)"; steps.Add(new Step { done = r.washed, text = $"Помыть кузов: мойка {Key("7")}, зажать ЛКМ и водить струей" }); steps.Add(new Step { done = r.rustFixed, text = $"Ржавчина: зачистка {Key("2")} → шпатель {Key("3")} → наждачка {Key("4")} → краска {Key("5")}" }); steps.Add(new Step { done = r.bodyComplete, text = $"Недостающие кузовные детали: купить в ноутбуке {Key("K")} и поставить в зеленую зону" }); steps.Add(new Step { done = r.wheelsOk, text = $"Колеса: домкрат под порог {Key("E")}, ключ {Key("6")} — болты, замена колеса, затянуть" }); steps.Add(new Step { done = r.engineOk, text = $"Под капотом: агрегаты < 80% снять {Key("Удерж. E")} и заменить новыми из {Key("K")}" }); steps.Add(new Step { done = r.fluidsOk, text = $"Жидкости: канистру с полки {Key("E")}, открыть крышку бачка {Key("E")}, лить {Key("ЛКМ")}" }); steps.Add(new Step { done = false, text = $"Выгнать на зеленую площадку продажи и нажать {Key("Enter")}" }); if (!r.washed) action = $"Грязь мешает ремонту. Выберите мойку высокого давления {Key("Tab")} или {Key("7")}, зажмите ЛКМ и водите струей по всему кузову."; else if (!r.rustFixed) action = $"Найдите ржавые места (рыжие пятна). Зачистка {Key("2")}, шпаклевка {Key("3")}, шлифовка {Key("4")}, покраска {Key("5")} — зажмите ЛКМ и водите мышью по детали."; else if (!r.bodyComplete) action = $"Откройте ноутбук {Key("K")} → «Кузовные панели», купите деталь, возьмите её со стола выдачи и удерживайте {Key("E")} у зеленого силуэта на машине."; else if (!r.wheelsOk) action = $"Возьмите домкрат {Key("E")}, поставьте под порог у колеса и поднимите {Key("Удерж. E")}. Ключом {Key("6")} выкрутите 4 болта, снимите колесо, наденьте новое (купить в {Key("K")}) и затяните болты. Кирпичи убираются {Key("E")}."; else if (!r.engineOk) action = $"Откройте капот {Key("E")} и наведитесь на агрегаты — видно состояние в %. Севший АКБ можно зарядить на складе {Key("K")}. Изношенное снимите и замените новым."; else if (!r.fluidsOk) action = $"Канистры стоят на полке справа. Желтая — масло, розовая — антифриз, белая — тормозная, синяя — омывайка. Старое масло: домкрат спереди, присесть {Key("Ctrl")}, сливная пробка снизу {Key("E")}."; else { action = $"Машина готова! Сядьте {Key("F")}, выгоните её на зеленую площадку перед гаражом и нажмите {Key("Enter")}."; if (sellZone != null) navTargets.Add(new NavTarget { pos = sellZone.transform.position + Vector3.up * 1.5f, label = "Площадка продажи", color = GameUI.Green }); } if (r.issues.Count > 0 && r.washed && r.rustFixed) action += $"\n{r.issues[0]}"; } // ===================== ОТРИСОВКА ===================== private Camera ActiveCamera() { if (cachedCam != null && cachedCam.isActiveAndEnabled) return cachedCam; cachedCam = Camera.main; if (cachedCam == null || !cachedCam.isActiveAndEnabled) { PlayerLook look = FindAnyObjectByType(); cachedCam = look != null ? look.GetComponent() : null; } if (cachedCam == null || !cachedCam.isActiveAndEnabled) { CarOrbitCamera orbit = FindAnyObjectByType(); cachedCam = orbit != null ? orbit.GetComponent() : null; } return cachedCam; } private void OnGUI() { MainMenuAndBootManager menu = MainMenuAndBootManager.Instance; if (menu != null && !menu.IsPlaying) return; GameUI.Begin(9); float w = GameUI.VirtualWidth; float h = GameUI.VirtualHeight; Camera cam = ActiveCamera(); if (cam != null && !GameInputLock.IsLocked) { DrawWorldLabels(cam); foreach (NavTarget t in navTargets) DrawNavMarker(cam, t, w, h); } DrawPanel(w); } private void DrawPanel(float w) { float pw = 470f; float x = w - pw - 20f; float y = 76f; if (collapsed) { GUI.Label(new Rect(x, y, pw, 40), $"ЧТО ДЕЛАТЬ [H] показать", GameUI.Badge); return; } GUIStyle stepStyle = new GUIStyle(GameUI.Label) { fontSize = 16 }; GUIStyle actionStyle = new GUIStyle(GameUI.Label) { fontSize = 17 }; float inner = pw - 36f; float hHead = GameUI.Header.CalcHeight(new GUIContent(headline), inner); float hAction = actionStyle.CalcHeight(new GUIContent(action), inner); float hSteps = 0f; foreach (Step s in steps) hSteps += stepStyle.CalcHeight(new GUIContent("● " + s.text), inner - 10f) + 4f; float total = 50f + hHead + hAction + hSteps + 34f; Rect r = new Rect(x, y, pw, total); GUI.Box(r, GUIContent.none, GameUI.Panel); GUI.Label(new Rect(x + 18, y + 10, inner, 24), "ЧТО ДЕЛАТЬ [H] свернуть", GameUI.Small); float cy = y + 36; GUIStyle head = new GUIStyle(GameUI.Header) { fontSize = 20 }; GUI.Label(new Rect(x + 18, cy, inner, hHead), headline, head); cy += hHead + 4; GUI.Label(new Rect(x + 18, cy, inner, hAction), action, actionStyle); cy += hAction + 10; GameUI.DrawRect(new Rect(x + 18, cy, inner, 1), GameUI.Hex("3A3F4A")); cy += 8; bool currentMarked = false; foreach (Step s in steps) { string mark; if (s.done) mark = "●"; else if (!currentMarked) { mark = "►"; currentMarked = true; } else mark = "○"; string text = s.done ? $"{s.text}" : s.text; float sh = stepStyle.CalcHeight(new GUIContent("● " + s.text), inner - 10f); GUI.Label(new Rect(x + 18, cy, inner, sh), $"{mark} {text}", stepStyle); cy += sh + 4; } } private void DrawWorldLabels(Camera cam) { Vector3 pp = PlayerPos; foreach (WorldLabel l in WorldLabel.All) { if (l == null) continue; Vector3 wp = l.WorldPoint; float d = Vector3.Distance(pp, wp); if (d > l.showDistance) continue; Vector3 sp = cam.WorldToScreenPoint(wp); if (sp.z <= 0.2f) continue; float s = GameUI.Scale; Vector2 p = new Vector2(sp.x / s, (Screen.height - sp.y) / s); float alpha = Mathf.Clamp01((l.showDistance - d) / 2.5f); Color prev = GUI.color; GUI.color = new Color(1f, 1f, 1f, alpha); string text = string.IsNullOrEmpty(l.hint) ? $"{l.title}" : $"{l.title}\n{l.hint}"; GUIStyle st = new GUIStyle(GameUI.Badge) { alignment = TextAnchor.MiddleCenter, fontSize = 16, wordWrap = true }; Vector2 size = new Vector2(300f, st.CalcHeight(new GUIContent(text), 300f) + 4f); GUI.Label(new Rect(p.x - size.x * 0.5f, p.y - size.y, size.x, size.y), text, st); GUI.color = prev; } } private void DrawNavMarker(Camera cam, NavTarget t, float w, float h) { Vector3 sp = cam.WorldToScreenPoint(t.pos); float s = GameUI.Scale; bool behind = sp.z < 0f; Vector2 p = new Vector2(sp.x / s, (Screen.height - sp.y) / s); if (behind) p = new Vector2(w - p.x, h - p.y); const float margin = 70f; bool offscreen = behind || p.x < margin || p.x > w - margin || p.y < margin + 40 || p.y > h - margin - 60; if (offscreen) { Vector2 c = new Vector2(w * 0.5f, h * 0.5f); Vector2 dir = (p - c); if (behind) dir = -dir; if (dir.sqrMagnitude < 1f) dir = Vector2.up; dir.Normalize(); float k = Mathf.Min((w * 0.5f - margin) / Mathf.Max(Mathf.Abs(dir.x), 0.001f), (h * 0.5f - margin - 50f) / Mathf.Max(Mathf.Abs(dir.y), 0.001f)); p = c + dir * k; } float dist = Vector3.Distance(PlayerPos, t.pos); GUI.DrawTexture(new Rect(p.x - 14, p.y - 14, 28, 28), GameUI.Rounded(t.color, Color.white, 13, 2)); string label = $"{t.label} {dist:F0} м"; GUIStyle st = new GUIStyle(GameUI.Badge) { alignment = TextAnchor.MiddleCenter, fontSize = 16 }; GUI.Label(new Rect(p.x - 130, p.y + 18, 260, 32), label, st); } }