First Commit

This commit is contained in:
bybohka committed 2026-11-19 23:24:44 +03:00
commit eed6b79efc
2836 files changed
+948481

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
using UnityEngine;
/// <summary>
/// Главный контроллер интерфейса авторынка и телефона перекупа.
/// Обеспечивает мост между сценой, CarMarketManager, современным SmartphoneUI и MeetingWaypointHUD.
/// </summary>
public class CarMarketUI : MonoBehaviour
{
[Header("Клавиши открытия телефона")]
[SerializeField] private KeyCode toggleKeyPrimary = KeyCode.P;
[SerializeField] private KeyCode toggleKeySecondary = KeyCode.M;
[Header("Ссылки")]
[SerializeField] private CarMarketManager marketManager;
[SerializeField] private SmartphoneUI smartphoneUI;
[SerializeField] private MeetingWaypointHUD waypointHUD;
private void Awake()
{
if (marketManager == null)
marketManager = GetComponent<CarMarketManager>() ?? FindAnyObjectByType<CarMarketManager>();
if (smartphoneUI == null)
smartphoneUI = GetComponent<SmartphoneUI>() ?? FindAnyObjectByType<SmartphoneUI>();
if (smartphoneUI == null)
{
smartphoneUI = gameObject.AddComponent<SmartphoneUI>();
}
if (waypointHUD == null)
waypointHUD = GetComponent<MeetingWaypointHUD>() ?? FindAnyObjectByType<MeetingWaypointHUD>();
if (waypointHUD == null)
{
waypointHUD = gameObject.AddComponent<MeetingWaypointHUD>();
}
// Гарантируем наличие аудиофидбека
_ = PhoneAudioFeedback.Instance;
}
public void ToggleMarket(bool open)
{
if (smartphoneUI != null)
smartphoneUI.TogglePhone(open);
}
}
+3
View File
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8127b59452c04faaba54481666998822
timeCreated: 1792711836
+215
View File
@@ -0,0 +1,215 @@
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 "";
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 565ef9c62cfcfe44b869fd961af13cd2
+392
View File
@@ -0,0 +1,392 @@
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Ноутбук гаража [K]: вкладка «Магазин запчастей и жидкостей» (выдача на стол в гараже или на кассе АЗС)
/// и вкладка «Склад запчастей / Продажа на Куфар» со снятыми деталями, их состоянием, зарядкой АКБ и продажей.
/// </summary>
public class GarageWarehouseUI : MonoBehaviour
{
private enum Tab { Shop, Warehouse }
private class ShopItem
{
public string title;
public string category;
public float price;
public System.Action<Vector3> spawn;
}
[SerializeField] private KeyCode openKey = KeyCode.K;
[SerializeField] private float wheelPrice = 85f;
[SerializeField] private float chargePrice = 8f;
public static GarageWarehouseUI Instance { get; private set; }
private bool isOpen;
private Tab tab = Tab.Shop;
private Vector2 scroll;
private int deliveryIndex;
private Transform customDelivery;
private string statusLine;
private readonly List<ShopItem> items = new List<ShopItem>();
private Transform player;
private void Awake() => Instance = this;
private void OnDestroy() { if (Instance == this) Instance = null; }
private void Update()
{
if (isOpen)
{
if (Input.GetKeyDown(KeyCode.Escape) || Input.GetKeyDown(openKey)) Close();
return;
}
if (!Input.GetKeyDown(openKey) || GameInputLock.IsLocked || VehicleInteraction.Current != null) return;
MainMenuAndBootManager menu = MainMenuAndBootManager.Instance;
if (menu != null && !menu.IsPlaying) return;
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco != null && !eco.DiplomaFeatures)
{
GameHUD.Notify("Магазин и склад «Куфар» доступны в Дипломной версии", GameUI.Muted);
return;
}
if (ShopCounter.PlayerNearby != null)
{
Open(ShopCounter.PlayerNearby.DeliveryPoint);
return;
}
if (PlayerPos(out Vector3 p) && eco != null && !eco.IsInGarage(p))
{
GameHUD.Notify("Ноутбук магазина и склада находится в гараже (или на кассе АЗС)", GameUI.Accent);
return;
}
Open(null);
}
private bool PlayerPos(out Vector3 pos)
{
if (player == null)
{
PlayerMovement pm = FindAnyObjectByType<PlayerMovement>();
if (pm != null) player = pm.transform;
}
pos = player != null ? player.position : Vector3.zero;
return player != null;
}
public void Open(Transform deliveryOverride)
{
customDelivery = deliveryOverride;
isOpen = true;
statusLine = deliveryOverride != null ? "Заказы выдаются на кассе магазина автохимии" : "Заказы выдаются на стол выдачи в гараже";
GameInputLock.Lock(this);
ProceduralAudioManager.Instance?.Play(SfxId.Notification);
}
private void Close()
{
isOpen = false;
GameInputLock.Unlock(this);
}
private Vector3 NextDeliveryPos()
{
int i = deliveryIndex++;
if (customDelivery != null)
{
int slot = i % 5;
return customDelivery.position + customDelivery.right * ((slot - 2) * 0.45f) + Vector3.up * (0.3f + (i / 5 % 3) * 0.35f);
}
GameEconomyManager eco = GameEconomyManager.Instance;
return eco != null ? eco.GetDeliveryPosition(i % 15) : Vector3.up;
}
// ===================== МАГАЗИН =====================
private void BuildShop()
{
items.Clear();
foreach (EnginePartType t in new[] { EnginePartType.Battery, EnginePartType.SparkPlugs, EnginePartType.AirFilter, EnginePartType.OilFilter, EnginePartType.Radiator, EnginePartType.Alternator })
{
EnginePartType type = t;
CarPartData d = PartCatalog.Instance.GetEngineData(type);
float price = d != null && d.basePrice > 0f ? d.basePrice : EnginePart.GetDefaultPrice(type);
items.Add(new ShopItem
{
title = EnginePart.GetDisplayName(type) + " (новый)",
category = "Подкапотные агрегаты",
price = price,
spawn = pos => EnginePartFactory.CreatePart(type, null, pos, Quaternion.identity, 0.6f, true)
});
}
foreach (FluidType t in new[] { FluidType.EngineOil, FluidType.Coolant, FluidType.BrakeFluid, FluidType.WasherFluid })
{
FluidType type = t;
items.Add(new ShopItem
{
title = FluidCanister.GetDefaultTitle(type),
category = "Автохимия и жидкости",
price = CanisterPrice(type),
spawn = pos => SpawnCanister(type, pos)
});
}
// Колеса и кузовные детали для машин игрока в гараже
foreach (CarOwnership car in CarOwnership.All)
{
if (car == null || !car.isOwned) continue;
CarPart wheelTemplate = null;
foreach (CarPart p in car.GetComponentsInChildren<CarPart>(true))
{
if (!p.IsWheel) continue;
if (wheelTemplate == null || (p.State == PartState.Installed && p.gameObject.activeInHierarchy)) wheelTemplate = p;
}
if (wheelTemplate != null)
{
CarPart template = wheelTemplate;
items.Add(new ShopItem
{
title = $"Колесо в сборе — {car.carTitle}",
category = "Колеса",
price = wheelPrice,
spawn = pos => CarWheelCondition.CreateSpareFrom(template, pos)
});
}
foreach (CarPartMountZone z in car.GetComponentsInChildren<CarPartMountZone>(true))
{
CarPart target = z.TargetPart;
if (target == null || target.IsWheel || target.GetComponent<EnginePart>() != null) continue;
if (target.gameObject.activeInHierarchy) continue; // Снятая деталь лежит рядом — её можно поставить обратно
CarPart t2 = target;
items.Add(new ShopItem
{
title = $"{t2.DisplayName} — {car.carTitle}",
category = "Кузовные панели",
price = t2.Data != null ? t2.Data.basePrice : 150f,
spawn = pos => t2.SpawnAsNewPart(pos)
});
}
}
}
private static float CanisterPrice(FluidType t)
{
switch (t)
{
case FluidType.EngineOil: return 38f;
case FluidType.Coolant: return 22f;
case FluidType.BrakeFluid: return 12f;
default: return 6f;
}
}
public static FluidCanister SpawnCanister(FluidType type, Vector3 pos)
{
GameObject prefab = PartCatalog.Instance.GetCanister(type);
GameObject go;
if (prefab != null)
{
go = Instantiate(prefab, pos, Quaternion.identity);
}
else
{
go = new GameObject("Canister_" + type);
go.transform.position = pos;
EnginePartFactory.Prim(PrimitiveType.Cube, go.transform, "Body", Vector3.zero, new Vector3(0.2f, 0.28f, 0.12f),
PartCatalog.Instance.GetMaterial("canister_" + type, FluidCanister.GetDefaultColor(type)));
BoxCollider bc = go.AddComponent<BoxCollider>();
bc.size = new Vector3(0.2f, 0.3f, 0.12f);
go.AddComponent<FluidCanister>();
}
go.layer = EnginePartFactory.InteractLayer;
FluidCanister can = go.GetComponent<FluidCanister>();
if (can == null) can = go.AddComponent<FluidCanister>();
can.Configure(type, FluidCanister.GetDefaultTitle(type), FluidCanister.GetDefaultLiters(type), FluidCanister.GetDefaultColor(type));
Rigidbody rb = go.GetComponent<Rigidbody>();
if (rb == null) rb = go.AddComponent<Rigidbody>();
rb.mass = 4f;
rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
return can;
}
private void BuyItem(ShopItem item)
{
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco != null && !eco.TrySpend(item.price, item.title)) return;
item.spawn?.Invoke(NextDeliveryPos());
statusLine = $"Куплено: {item.title}. Заберите заказ на столе выдачи.";
GameHUD.Notify($"Куплено: {item.title} — {GameUI.Money(item.price)}", GameUI.Green);
}
// ===================== СКЛАД =====================
private List<Component> CollectWarehouse()
{
List<Component> list = new List<Component>();
GameEconomyManager eco = GameEconomyManager.Instance;
Vector3 center = customDelivery != null ? customDelivery.position : (eco != null && eco.garageCenter != null ? eco.garageCenter.position : Vector3.zero);
float radius = customDelivery != null ? 15f : (eco != null ? eco.garageRadius : 30f);
foreach (CarPart p in FindObjectsByType<CarPart>(FindObjectsSortMode.None))
{
if (p.State != PartState.Dropped || !p.gameObject.activeInHierarchy) continue;
if (Vector3.Distance(p.transform.position, center) > radius) continue;
list.Add(p);
}
foreach (FluidCanister c in FindObjectsByType<FluidCanister>(FindObjectsSortMode.None))
{
if (c.State != FluidCanister.CanisterState.OnGround) continue;
if (Vector3.Distance(c.transform.position, center) > radius) continue;
list.Add(c);
}
return list;
}
private static float KufarPrice(CarPart p)
{
float basePrice = p.Data != null && p.Data.basePrice > 0f ? p.Data.basePrice : 40f;
EnginePart ep = p.GetComponent<EnginePart>();
if (ep != null) basePrice = ep.BasePrice;
if (p.IsWheel) basePrice = 85f;
return Mathf.Max(3f, Mathf.Round(basePrice * (p.ConditionPercent / 100f) * 0.5f));
}
// ===================== ОТРИСОВКА =====================
private void OnGUI()
{
if (!isOpen) 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));
Rect r = new Rect(w * 0.5f - 640, h * 0.5f - 440, 1280, 880);
GUI.Box(r, GUIContent.none, GameUI.PanelSolid);
GUI.Label(new Rect(r.x + 30, r.y + 16, 700, 44), "НОУТБУК ГАРАЖА", GameUI.Header);
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco != null)
GUI.Label(new Rect(r.xMax - 560, r.y + 22, 530, 34), eco.Unlimited ? "Свободный режим: деньги не ограничены" : $"На счету: <color=#4CD07D>{eco.FormatMoney(eco.Money)}</color>", GameUI.Label);
if (GameUI.Btn(new Rect(r.x + 30, r.y + 70, 400, 50), "Магазин запчастей и жидкостей", tab == Tab.Shop ? GameUI.ButtonTabActive : GameUI.ButtonTab)) { tab = Tab.Shop; scroll = Vector2.zero; }
if (GameUI.Btn(new Rect(r.x + 440, r.y + 70, 400, 50), "Склад запчастей / Продажа на Куфар", tab == Tab.Warehouse ? GameUI.ButtonTabActive : GameUI.ButtonTab)) { tab = Tab.Warehouse; scroll = Vector2.zero; }
Rect view = new Rect(r.x + 30, r.y + 136, r.width - 60, r.height - 240);
if (tab == Tab.Shop) DrawShop(view);
else DrawWarehouse(view);
GUI.Label(new Rect(r.x + 30, r.yMax - 84, r.width - 300, 60), statusLine, GameUI.Small);
if (GameUI.Btn(new Rect(r.xMax - 240, r.yMax - 80, 210, 54), "ЗАКРЫТЬ [K]")) Close();
}
private void DrawShop(Rect view)
{
BuildShop();
float rowH = 50f;
int categories = 0;
string last = null;
foreach (ShopItem i in items) if (i.category != last) { categories++; last = i.category; }
float contentH = items.Count * rowH + categories * 42f + 10f;
scroll = GUI.BeginScrollView(view, scroll, new Rect(0, 0, view.width - 24, contentH));
float y = 0f;
last = null;
foreach (ShopItem item in items)
{
if (item.category != last)
{
last = item.category;
GUI.Label(new Rect(0, y + 6, view.width, 32), $"<color=#F2A93B><b>{item.category}</b></color>", GameUI.Label);
y += 42f;
}
GameUI.DrawRect(new Rect(0, y, view.width - 30, rowH - 6), GameUI.PanelLight.WithAlpha(0.5f));
GUI.Label(new Rect(14, y + 10, view.width - 420, 32), item.title, GameUI.Label);
GUI.Label(new Rect(view.width - 400, y + 10, 160, 32), GameUI.Money(item.price).Split(' ')[0], GameUI.Label);
if (GameUI.Btn(new Rect(view.width - 220, y + 4, 180, rowH - 14), "Купить", GameUI.ButtonAccent))
BuyItem(item);
y += rowH;
}
GUI.EndScrollView();
}
private void DrawWarehouse(Rect view)
{
List<Component> stock = CollectWarehouse();
float rowH = 52f;
GUI.Label(new Rect(view.x + 14, view.y - 4, 500, 30), "<b>Наименование детали</b>", GameUI.Small);
GUI.Label(new Rect(view.x + view.width - 760, view.y - 4, 180, 30), "<b>Состояние (%)</b>", GameUI.Small);
Rect inner = new Rect(view.x, view.y + 30, view.width, view.height - 30);
scroll = GUI.BeginScrollView(inner, scroll, new Rect(0, 0, inner.width - 24, Mathf.Max(inner.height, stock.Count * rowH + 10)));
float y = 0f;
if (stock.Count == 0)
GUI.Label(new Rect(10, 10, inner.width - 40, 60), "Склад пуст. Снятые детали, колеса и канистры, лежащие в гараже, появятся здесь.", GameUI.Small);
foreach (Component c in stock)
{
if (c == null) continue;
GameUI.DrawRect(new Rect(0, y, inner.width - 30, rowH - 6), GameUI.PanelLight.WithAlpha(0.5f));
if (c is CarPart part)
{
EnginePart ep = part.GetComponent<EnginePart>();
GUI.Label(new Rect(14, y + 11, inner.width - 800, 32), part.DisplayName, GameUI.Label);
string cond = ep != null ? ep.ShortStatus : $"{Mathf.RoundToInt(part.ConditionPercent)}%";
GUI.Label(new Rect(inner.width - 760, y + 11, 220, 32), cond, GameUI.Label);
if (ep != null && ep.partType == EnginePartType.Battery && ep.charge < 99f)
{
if (GameUI.Btn(new Rect(inner.width - 520, y + 4, 220, rowH - 14), $"Зарядить (${chargePrice:F0})"))
{
if (GameEconomyManager.Instance == null || GameEconomyManager.Instance.TrySpend(chargePrice, "Зарядка АКБ"))
{
ep.charge = 100f;
statusLine = "Аккумулятор заряжен зарядным устройством до 100%";
}
}
}
else if (ep != null && ep.partType == EnginePartType.AirFilter && ep.condition < 70f)
{
if (GameUI.Btn(new Rect(inner.width - 520, y + 4, 220, rowH - 14), "Очистить (продуть)"))
{
ep.condition = 70f;
statusLine = "Воздушный фильтр продут компрессором: 70%";
}
}
float price = KufarPrice(part);
if (GameUI.Btn(new Rect(inner.width - 280, y + 4, 240, rowH - 14), $"Продать на Куфар ${price:F0}", GameUI.ButtonAccent))
{
GameEconomyManager.Instance?.Earn(price, $"Куфар: {part.DisplayName}");
statusLine = $"Продано на Куфар: {part.DisplayName} за ${price:F0}";
part.HideAsSold();
}
}
else if (c is FluidCanister can)
{
GUI.Label(new Rect(14, y + 11, inner.width - 800, 32), can.FluidName, GameUI.Label);
GUI.Label(new Rect(inner.width - 760, y + 11, 220, 32), $"{can.CurrentLiters:F1} л ({Mathf.RoundToInt(can.Fill01 * 100f)}%)", GameUI.Label);
float price = Mathf.Max(1f, Mathf.Round(CanisterPrice(can.Type) * can.Fill01 * 0.5f));
if (GameUI.Btn(new Rect(inner.width - 280, y + 4, 240, rowH - 14), $"Продать на Куфар ${price:F0}", GameUI.ButtonAccent))
{
GameEconomyManager.Instance?.Earn(price, $"Куфар: {can.FluidName}");
Destroy(can.gameObject);
}
}
y += rowH;
}
GUI.EndScrollView();
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: bba5cacc6a409134282bed3a60caba3d
+307
View File
@@ -0,0 +1,307 @@
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Помощник игрока: панель «ЧТО ДЕЛАТЬ» с текущей задачей и чек-листом восстановления,
/// экранные указатели к цели (встреча с продавцом, гараж, площадка продажи) и подписи над объектами гаража.
/// [H] — свернуть/развернуть панель.
/// </summary>
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<Step> steps = new List<Step>();
private readonly List<NavTarget> navTargets = new List<NavTarget>();
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<PlayerMovement>();
if (pm != null) player = pm.transform;
}
return player != null ? player.position : Vector3.zero;
}
}
private static string Key(string k) => $"<color=#F2A93B><b>[{k}]</b></color>";
// ===================== ЛОГИКА ЗАДАЧ =====================
private void Refresh()
{
steps.Clear();
navTargets.Clear();
GameEconomyManager eco = GameEconomyManager.Instance;
CarMarketManager market = FindAnyObjectByType<CarMarketManager>();
if (sellZone == null) sellZone = FindAnyObjectByType<CarSellZone>();
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<CarOwnership>() : 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<color=#9AA0A6>{r.issues[0]}</color>";
}
// ===================== ОТРИСОВКА =====================
private Camera ActiveCamera()
{
if (cachedCam != null && cachedCam.isActiveAndEnabled) return cachedCam;
cachedCam = Camera.main;
if (cachedCam == null || !cachedCam.isActiveAndEnabled)
{
PlayerLook look = FindAnyObjectByType<PlayerLook>();
cachedCam = look != null ? look.GetComponent<Camera>() : null;
}
if (cachedCam == null || !cachedCam.isActiveAndEnabled)
{
CarOrbitCamera orbit = FindAnyObjectByType<CarOrbitCamera>();
cachedCam = orbit != null ? orbit.GetComponent<Camera>() : 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), $"<b>ЧТО ДЕЛАТЬ</b> <color=#9AA0A6>[H] показать</color>", 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), "<b><color=#9AA0A6>ЧТО ДЕЛАТЬ</color></b> <color=#5F656E>[H] свернуть</color>", 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 = "<color=#4CD07D>●</color>";
else if (!currentMarked) { mark = "<color=#F2A93B>►</color>"; currentMarked = true; }
else mark = "<color=#5F656E>○</color>";
string text = s.done ? $"<color=#7E858E>{s.text}</color>" : 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) ? $"<b>{l.title}</b>" : $"<b>{l.title}</b>\n<size=14><color=#C9CDD2>{l.hint}</color></size>";
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 = $"<b>{t.label}</b> {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);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 06bb6753a81f67547a5c453dc7d57b00
+439
View File
@@ -0,0 +1,439 @@
using UnityEngine;
using UnityEngine.SceneManagement;
/// <summary>
/// Экран загрузки, Главное меню на фоне 3D-гаража, Руководство, Настройки, Об авторе, Пауза (Esc)
/// и вводный брифинг карьеры. Весь интерфейс — OnGUI, работает без ссылок в Инспекторе.
/// </summary>
public class MainMenuAndBootManager : MonoBehaviour
{
public enum MenuState { Boot, MainMenu, Briefing, Playing, Paused }
private enum Modal { None, Guide, Settings, About }
public static MainMenuAndBootManager Instance { get; private set; }
[Header("Экран загрузки")]
[SerializeField] private float bootDuration = 2f;
[SerializeField] private string gameTitle = "ПЕРЕКУПЩИК ПРОВИНЦИИ";
[SerializeField] private string gameSubtitle = "Arcade Simulator • Arcade Driving с элементами торговли";
[Header("Фон меню")]
[SerializeField] private bool spawnShowcaseCar = true;
[SerializeField] private float menuCameraDistance = 7.5f;
[Header("Об авторе")]
[SerializeField] private string authorLine = "Разработчик: Савило Кирилл Валерьевич, гр. 324401, БГУИР, кафедра ВМиП, 2026";
public MenuState State { get; private set; } = MenuState.Boot;
public bool IsPlaying => State == MenuState.Playing;
private Modal modal = Modal.None;
private float bootTimer;
private int tipIndex;
private Camera menuCamera;
private Camera playerCamera;
private GameObject showcaseCar;
private float orbitAngle;
private GameMode pendingMode;
private Vector2 guideScroll;
private static readonly string[] Tips =
{
"Сначала смойте грязь с кузова мойкой, чтобы увидеть скрытые очаги коррозии...",
"Проверяйте уровень масла и заряд аккумулятора под капотом перед выездом...",
"Толщиномер покажет скрытый перекрас: 250–450 мкм — повод сбросить цену.",
"OBD-сканер найдет пропуски зажигания и проблемы с зарядкой ещё до покупки.",
"Колесо снимается только когда эта сторона поднята домкратом и откручены 4 болта.",
"Полностью вымытая машина продается на 8% дороже!"
};
private void Awake()
{
Instance = this;
GameInputLock.ClearAll();
GameInputLock.Lock(this);
Time.timeScale = 1f;
}
private void OnDestroy()
{
if (Instance == this) Instance = null;
}
private void Start()
{
tipIndex = Random.Range(0, Tips.Length);
PlayerLook look = FindAnyObjectByType<PlayerLook>();
playerCamera = look != null ? look.GetComponent<Camera>() : Camera.main;
_ = ProceduralAudioManager.Instance;
SetupMenuCamera();
if (spawnShowcaseCar) SpawnShowcaseCar();
SetMenuView(true);
}
// ===================== ФОН МЕНЮ =====================
private Vector3 FocusPoint
{
get
{
if (showcaseCar != null) return showcaseCar.transform.position + Vector3.up * 0.7f;
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco != null && eco.garageCarSpot != null) return eco.garageCarSpot.position + Vector3.up * 0.7f;
return Vector3.up;
}
}
private void SetupMenuCamera()
{
GameObject camObj = new GameObject("MenuCamera");
menuCamera = camObj.AddComponent<Camera>();
menuCamera.fieldOfView = 50f;
menuCamera.nearClipPlane = 0.1f;
menuCamera.farClipPlane = 1500f;
menuCamera.depth = 50f;
}
private void SpawnShowcaseCar()
{
GameEconomyManager eco = GameEconomyManager.Instance;
CarMarketManager market = FindAnyObjectByType<CarMarketManager>();
if (eco == null || eco.garageCarSpot == null || market == null || market.Catalog == null || market.Catalog.Length == 0) return;
CarCatalogItem item = market.Catalog[0];
foreach (CarCatalogItem c in market.Catalog)
if (c != null && c.carPrefab != null && c.carPrefab.name.Contains("Covet")) { item = c; break; }
if (item == null || item.carPrefab == null) return;
showcaseCar = Instantiate(item.carPrefab, eco.garageCarSpot.position + Vector3.up * 0.4f, eco.garageCarSpot.rotation);
showcaseCar.name = "ProjectCar_" + item.carPrefab.name;
CarConditionGenerator gen = showcaseCar.GetComponent<CarConditionGenerator>();
if (gen != null) gen.ApplyConditionBySeed(Random.Range(1000, 99999), new Color(0.12f, 0.32f, 0.75f), false, out _);
CarOwnership own = showcaseCar.GetComponent<CarOwnership>();
if (own == null) own = showcaseCar.AddComponent<CarOwnership>();
own.carTitle = item.carTitle;
own.marketValue = item.idealPrice;
own.askingPrice = item.idealPrice * 0.45f;
own.year = Random.Range(item.minYear, item.maxYear + 1);
own.isOwned = true;
own.isStarterCar = true;
own.purchasePrice = 0f;
}
private void SetMenuView(bool menu)
{
if (menuCamera != null) menuCamera.gameObject.SetActive(menu);
if (playerCamera != null) playerCamera.enabled = !menu;
}
private void LateUpdate()
{
if (menuCamera == null || !menuCamera.gameObject.activeSelf) return;
orbitAngle += Time.unscaledDeltaTime * 9f;
Vector3 focus = FocusPoint;
Quaternion rot = Quaternion.Euler(16f, orbitAngle, 0f);
menuCamera.transform.position = focus - rot * Vector3.forward * menuCameraDistance;
menuCamera.transform.LookAt(focus);
}
// ===================== ЛОГИКА СОСТОЯНИЙ =====================
private void Update()
{
if (State == MenuState.Boot)
{
bootTimer += Time.unscaledDeltaTime;
if (bootTimer >= bootDuration) State = MenuState.MainMenu;
return;
}
if (Input.GetKeyDown(KeyCode.Escape))
{
if (modal != Modal.None)
{
modal = Modal.None;
}
else if (State == MenuState.Playing && !GameInputLock.IsLocked && !GameInputLock.WasJustUnlocked && CarJack.ActiveJackInHand == null)
{
State = MenuState.Paused;
GameInputLock.Lock(this);
Time.timeScale = 0f;
}
else if (State == MenuState.Paused)
{
Resume();
}
}
}
private void Resume()
{
State = MenuState.Playing;
modal = Modal.None;
Time.timeScale = 1f;
GameInputLock.Unlock(this);
}
private void StartGame(GameMode mode)
{
pendingMode = mode;
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco != null) eco.StartGame(mode);
if (mode == GameMode.Career && showcaseCar != null)
{
Destroy(showcaseCar);
showcaseCar = null;
}
// Игрок появляется во дворе гаражного кооператива
if (eco != null && eco.playerSpawnPoint != null)
{
PlayerMovement pm = FindAnyObjectByType<PlayerMovement>();
if (pm != null)
{
CharacterController cc = pm.GetComponent<CharacterController>();
if (cc != null) cc.enabled = false;
pm.transform.SetPositionAndRotation(eco.playerSpawnPoint.position, eco.playerSpawnPoint.rotation);
if (cc != null) cc.enabled = true;
}
}
SetMenuView(false);
State = MenuState.Briefing;
}
private void FinishBriefing()
{
State = MenuState.Playing;
GameInputLock.Unlock(this);
GameHUD.Notify(pendingMode == GameMode.Career
? "Откройте планшет авторынка [M] и найдите первую машину"
: "В гараже стоит проектная машина — начните с мойки [Tab → Мойка]", GameUI.Accent);
}
private void ReturnToMainMenu()
{
Time.timeScale = 1f;
GameInputLock.ClearAll();
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex >= 0 ? SceneManager.GetActiveScene().buildIndex : 0);
}
private static void QuitGame()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
// ===================== ОТРИСОВКА =====================
private void OnGUI()
{
if (State == MenuState.Playing) return;
GameUI.Begin(-20);
float w = GameUI.VirtualWidth;
float h = GameUI.VirtualHeight;
switch (State)
{
case MenuState.Boot: DrawBoot(w, h); break;
case MenuState.MainMenu: DrawMainMenu(w, h); break;
case MenuState.Briefing: DrawBriefing(w, h); break;
case MenuState.Paused: DrawPause(w, h); break;
}
if (modal != Modal.None) DrawModal(w, h);
}
private void DrawBoot(float w, float h)
{
GameUI.DrawRect(new Rect(0, 0, w, h), GameUI.Bg);
// Индустриальные полосы
for (int i = 0; i < 14; i++)
GameUI.DrawRect(new Rect(-200 + i * 160, h - 26, 80, 26), GameUI.Accent.WithAlpha(0.85f));
GameUI.DrawRect(new Rect(0, h - 30, w, 4), GameUI.Hex("2F333C"));
GUI.Label(new Rect(0, h * 0.30f, w, 80), gameTitle, new GUIStyle(GameUI.Title) { fontSize = 72 });
GUI.Label(new Rect(0, h * 0.30f + 86, w, 40), gameSubtitle, GameUI.SmallCenter);
float p = Mathf.Clamp01(bootTimer / Mathf.Max(0.1f, bootDuration));
Rect bar = new Rect(w * 0.5f - 420, h * 0.58f, 840, 26);
GameUI.ProgressBar(bar, p, GameUI.Accent);
GUI.Label(new Rect(bar.x, bar.y + 34, bar.width, 30), $"Загрузка гаражного кооператива... {Mathf.RoundToInt(p * 100f)}%", GameUI.SmallCenter);
int tip = (tipIndex + Mathf.FloorToInt(bootTimer / 1.1f)) % Tips.Length;
GUI.Label(new Rect(w * 0.5f - 520, h * 0.70f, 1040, 70), $"<color=#F2A93B>Совет:</color> {Tips[tip]}", GameUI.LabelCenter);
}
private void DrawMainMenu(float w, float h)
{
GameUI.DrawRect(new Rect(0, 0, 640, h), GameUI.Bg.WithAlpha(0.88f));
GameUI.DrawRect(new Rect(640, 0, 4, h), GameUI.Accent);
GUI.Label(new Rect(40, 70, 580, 70), gameTitle, new GUIStyle(GameUI.Title) { fontSize = 38, alignment = TextAnchor.MiddleLeft, wordWrap = false });
GUI.Label(new Rect(42, 140, 560, 30), "Arcade Simulator — гаражный кооператив и авторынок", GameUI.Small);
GameEconomyManager eco = GameEconomyManager.Instance;
bool diploma = eco == null || eco.DiplomaFeatures;
float y = 230f;
const float bw = 560f, bh = 64f, gap = 14f;
GUI.enabled = diploma;
if (GameUI.Btn(new Rect(40, y, bw, bh), "НОВАЯ ИГРА\n<size=15>ДИПЛОМНЫЙ РЕЖИМ — КАРЬЕРА ПЕРЕКУПА</size>", GameUI.ButtonAccent))
StartGame(GameMode.Career);
GUI.enabled = true;
y += bh + gap;
if (GameUI.Btn(new Rect(40, y, bw, bh), "СВОБОДНЫЙ РЕЖИМ\n<size=15>КУРСОВАЯ ВЕРСИЯ</size>"))
StartGame(GameMode.Free);
y += bh + gap;
if (GameUI.Btn(new Rect(40, y, bw, bh), "РУКОВОДСТВО И УПРАВЛЕНИЕ")) modal = Modal.Guide;
y += bh + gap;
if (GameUI.Btn(new Rect(40, y, bw, bh), "НАСТРОЙКИ")) modal = Modal.Settings;
y += bh + gap;
if (GameUI.Btn(new Rect(40, y, bw, bh), "ОБ АВТОРЕ")) modal = Modal.About;
y += bh + gap;
if (GameUI.Btn(new Rect(40, y, bw, bh), "ВЫХОД", GameUI.ButtonDanger)) QuitGame();
GUI.Label(new Rect(40, h - 60, 560, 30), diploma ? "Версия: Дипломный проект (isDiplomaVersion = true)" : "Версия: Курсовая работа (isDiplomaVersion = false)", GameUI.Small);
}
private void DrawBriefing(float w, float h)
{
GameUI.DrawRect(new Rect(0, 0, w, h), GameUI.Bg.WithAlpha(0.55f));
Rect r = new Rect(w * 0.5f - 460, h * 0.5f - 250, 920, 500);
GUI.Box(r, GUIContent.none, GameUI.PanelSolid);
bool career = pendingMode == GameMode.Career;
GUI.Label(new Rect(r.x + 40, r.y + 26, r.width - 80, 50), career ? "ВВОДНЫЙ БРИФИНГ" : "СВОБОДНЫЙ РЕЖИМ (КУРСОВАЯ ВЕРСИЯ)", GameUI.Header);
string text = career
? "Добро пожаловать в гаражный кооператив! На вашем счету стартовый капитал $5 000. Откройте планшет авторынка [M], найдите выгодный автомобиль с дефектами, договоритесь о встрече, проведите осмотр кузова и подкапотного пространства, поторгуйтесь с продавцом, вымойте и восстановите машину в гараже и продайте с наценкой. Ваша цель — заработать и открыть собственный Автосалон!"
: "Деньги не ограничены. В гараже уже стоит проектная машина: вымойте её мойкой высокого давления, поднимите домкратом и замените колеса, пройдите 4 этапа кузовного ремонта ржавчины (зачистка → шпаклёвка → шлифовка → покраска) и выезжайте на аркадный тест-драйв. Планшет авторынка [M] и GPS-метки тоже доступны.";
GUI.Label(new Rect(r.x + 40, r.y + 90, r.width - 80, 280), text, new GUIStyle(GameUI.Label) { fontSize = 22 });
if (GameUI.Btn(new Rect(r.x + r.width * 0.5f - 200, r.y + r.height - 90, 400, 60), "ПРИСТУПИТЬ К РАБОТЕ", GameUI.ButtonAccent))
FinishBriefing();
}
private void DrawPause(float w, float h)
{
GameUI.DrawRect(new Rect(0, 0, w, h), GameUI.Bg.WithAlpha(0.7f));
Rect r = new Rect(w * 0.5f - 260, h * 0.5f - 270, 520, 540);
GUI.Box(r, GUIContent.none, GameUI.PanelSolid);
GUI.Label(new Rect(r.x, r.y + 20, r.width, 60), "ПАУЗА", GameUI.Title);
float y = r.y + 110;
if (GameUI.Btn(new Rect(r.x + 40, y, r.width - 80, 60), "ПРОДОЛЖИТЬ", GameUI.ButtonAccent)) Resume();
y += 74;
if (GameUI.Btn(new Rect(r.x + 40, y, r.width - 80, 60), "РУКОВОДСТВО И УПРАВЛЕНИЕ")) modal = Modal.Guide;
y += 74;
if (GameUI.Btn(new Rect(r.x + 40, y, r.width - 80, 60), "НАСТРОЙКИ")) modal = Modal.Settings;
y += 74;
if (GameUI.Btn(new Rect(r.x + 40, y, r.width - 80, 60), "ГЛАВНОЕ МЕНЮ")) ReturnToMainMenu();
y += 74;
if (GameUI.Btn(new Rect(r.x + 40, y, r.width - 80, 60), "ВЫХОД", GameUI.ButtonDanger)) QuitGame();
}
private void DrawModal(float w, float h)
{
GameUI.DrawRect(new Rect(0, 0, w, h), GameUI.Bg.WithAlpha(0.6f));
Rect r = modal == Modal.Guide
? new Rect(w * 0.5f - 640, h * 0.5f - 430, 1280, 860)
: new Rect(w * 0.5f - 420, h * 0.5f - 230, 840, 460);
GUI.Box(r, GUIContent.none, GameUI.PanelSolid);
switch (modal)
{
case Modal.Guide: DrawGuide(r); break;
case Modal.Settings: DrawSettings(r); break;
case Modal.About: DrawAbout(r); break;
}
if (GameUI.Btn(new Rect(r.xMax - 220, r.yMax - 76, 190, 52), "ЗАКРЫТЬ")) modal = Modal.None;
}
private void DrawGuide(Rect r)
{
GUI.Label(new Rect(r.x + 30, r.y + 20, r.width - 60, 46), "РУКОВОДСТВО И УПРАВЛЕНИЕ", GameUI.Header);
Rect view = new Rect(r.x + 30, r.y + 76, r.width - 60, r.height - 170);
string text =
"<b><color=#F2A93B>Пешком</color></b>\n" +
"WASD — ходьба, мышь — обзор, Ctrl — присесть (переключение), E — действие/взять, R (удерж.) — снять дверь/капот/багажник, " +
"G — положить деталь, ПКМ — бросить, F — сесть в машину, Tab (удерж.) — радиальное меню инструментов, 1–9 / колесо мыши — быстрый выбор, " +
"M — планшет авторынка, K — магазин запчастей и склад (в гараже), B — сделка/торг с продавцом, Esc — пауза.\n\n" +
"<b><color=#F2A93B>За рулем</color></b>\n" +
"W/S — газ/тормоз (первое нажатие W запускает двигатель), A/D — руль, Space — ручник, L — фары (выкл → ближний → дальний), " +
"F/E — выйти, Enter — выставить машину на продажу на площадке перед гаражом.\n\n" +
"<b><color=#F2A93B>Кузовной ремонт (4 этапа)</color></b>\n" +
"0) Мойка высокого давления: зажмите ЛКМ и водите струей — по грязному металлу работать нельзя.\n" +
"1) Зачистка ржавчины до голого металла (дрель с кордщёткой) → 2) Шпаклёвка (шпатель) → 3) Шлифовка (наждачка) → 4) Покраска (баллончик). " +
"Прогресс идет только при движении мыши по детали.\n\n" +
"<b><color=#F2A93B>Ходовая и колеса</color></b>\n" +
"Возьмите домкрат [E], подведите силуэт под порог у колеса и установите [E]. Удерживайте E — подъем, R — опускание, G — бросить. " +
"Баллонным ключом [Tab → Ключ] выкрутите 4 болта (ЛКМ/E), снимите колесо [E], наденьте новое на ступицу и затяните болты. " +
"Кирпичи под пустой ступицей убираются [E] только после установки колеса и затяжки всех болтов.\n\n" +
"<b><color=#F2A93B>Подкапотное пространство (ДВС)</color></b>\n" +
"Откройте капот [E]. Наведите прицел на узел — видно название и состояние в %. Аккумулятор и фильтры снимаются руками (удерж. E), " +
"свечи, генератор и радиатор — гаечным ключом. Новые агрегаты покупаются в магазине [K] и ставятся в подсвеченную зону. " +
"Масляный щуп показывает уровень и состояние масла. Для замены масла поднимите перед авто домкратом, присядьте и открутите сливную пробку снизу [E], " +
"затем залейте свежее масло сверху. Жидкости: желтая канистра — масло 5W-40, розовая — антифриз G12, белая — тормозная DOT-4, синяя — омывайка. " +
"Возьмите канистру [E], откройте крышку бачка [E] и удерживайте ЛКМ/E.\n\n" +
"<b><color=#F2A93B>Диагностика и торг</color></b>\n" +
"Толщиномер ЛКП: 95–120 мкм — завод, 250–450 мкм — перекрас/шпаклёвка. OBD-сканер выводит коды ошибок двигателя. " +
"Найденные дефекты становятся аргументами в окне торга [B] и снижают цену на 10–25%.\n\n" +
"<b><color=#F2A93B>Продажа</color></b>\n" +
"Пригоните машину на зеленую площадку продажи перед гаражом и нажмите Enter. Оценка учитывает мойку, ремонт ржавчины, комплектность, " +
"4 целых затянутых колеса, исправные агрегаты (> 80%) и свежие жидкости (> 85%). Полностью восстановленная машина дорожает на 45–75%.";
float contentH = GameUI.Label.CalcHeight(new GUIContent(text), view.width - 30) + 20;
guideScroll = GUI.BeginScrollView(view, guideScroll, new Rect(0, 0, view.width - 24, contentH));
GUI.Label(new Rect(0, 0, view.width - 30, contentH), text, GameUI.Label);
GUI.EndScrollView();
}
private void DrawSettings(Rect r)
{
GUI.Label(new Rect(r.x + 30, r.y + 20, r.width - 60, 46), "НАСТРОЙКИ", GameUI.Header);
ProceduralAudioManager audio = ProceduralAudioManager.Instance;
PlayerLook look = FindAnyObjectByType<PlayerLook>();
float y = r.y + 100;
float music = audio != null ? audio.musicVolume : 0.35f;
float sfx = audio != null ? audio.sfxVolume : 0.8f;
float sens = look != null ? look.Sensitivity : PlayerPrefs.GetFloat("perekup_sensitivity", 150f);
GUI.Label(new Rect(r.x + 40, y, 300, 30), $"Громкость музыки: {Mathf.RoundToInt(music * 100)}%", GameUI.Label);
float newMusic = GUI.HorizontalSlider(new Rect(r.x + 360, y + 10, r.width - 420, 24), music, 0f, 1f);
y += 70;
GUI.Label(new Rect(r.x + 40, y, 300, 30), $"Звуковые эффекты SFX: {Mathf.RoundToInt(sfx * 100)}%", GameUI.Label);
float newSfx = GUI.HorizontalSlider(new Rect(r.x + 360, y + 10, r.width - 420, 24), sfx, 0f, 1f);
y += 70;
GUI.Label(new Rect(r.x + 40, y, 300, 30), $"Чувствительность мыши: {Mathf.RoundToInt(sens)}", GameUI.Label);
float newSens = GUI.HorizontalSlider(new Rect(r.x + 360, y + 10, r.width - 420, 24), sens, 30f, 500f);
if (audio != null && (!Mathf.Approximately(newMusic, music) || !Mathf.Approximately(newSfx, sfx)))
audio.SetVolumes(newMusic, newSfx);
if (!Mathf.Approximately(newSens, sens))
{
if (look != null) look.SetSensitivity(newSens);
else PlayerPrefs.SetFloat("perekup_sensitivity", newSens);
}
}
private void DrawAbout(Rect r)
{
GUI.Label(new Rect(r.x + 30, r.y + 20, r.width - 60, 46), "ОБ АВТОРЕ", GameUI.Header);
GUI.Label(new Rect(r.x + 40, r.y + 100, r.width - 80, 220),
$"{gameTitle} — Arcade Simulator\n\nТема: «Создание компьютерного игрового приложения в жанре Arcade Driving с элементами торговли»\n\n{authorLine}",
new GUIStyle(GameUI.LabelCenter) { fontSize = 22 });
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: bf95aeab02c57ae4299c86dba072816a
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2765797f88663e745bb5edcd4ee02ae4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,386 @@
using UnityEngine;
using UnityEngine.UI;
using TMPro;
/// <summary>
/// Красивая 3D GPS-навигация и экранная метка пути до купленного или выбранного для встречи автомобиля.
/// Включает объемный луч-маяк в мире, экранную плашку с расстоянием, стрелку направления и оповещение о прибытии.
/// </summary>
public class MeetingWaypointHUD : MonoBehaviour
{
[Header("Ссылки")]
[SerializeField] private CarMarketManager marketManager;
[Header("Настройки метки")]
[SerializeField] private float heightAboveCar = 2.4f;
[SerializeField] private float arrivalDistance = 8f;
private Camera mainCam;
private GameObject beaconWorldRoot;
private GameObject beaconPillar;
private Transform activeTargetCar;
private CarListing currentListing;
private bool hasTriggeredArrival = false;
// UI элементы на Canvas
private GameObject hudContainer;
private RectTransform waypointRect;
private Image waypointBg;
private Image iconImage;
private TextMeshProUGUI titleText;
private TextMeshProUGUI distanceText;
private RectTransform arrowRect;
private Image arrowImage;
// Баннер прибытия
private GameObject arrivalBanner;
private CanvasGroup arrivalBannerGroup;
private float arrivalBannerTimer = 0f;
private void Awake()
{
if (marketManager == null)
marketManager = FindAnyObjectByType<CarMarketManager>();
CreateHUDHierarchy();
}
private void Start()
{
if (marketManager != null)
{
marketManager.OnMeetingArranged += HandleMeetingArranged;
marketManager.OnMeetingCleared += HandleMeetingCleared;
if (marketManager.ActiveMeetingListing != null)
HandleMeetingArranged(marketManager.ActiveMeetingListing);
}
}
private void OnDestroy()
{
if (marketManager != null)
{
marketManager.OnMeetingArranged -= HandleMeetingArranged;
marketManager.OnMeetingCleared -= HandleMeetingCleared;
}
if (beaconWorldRoot != null)
Destroy(beaconWorldRoot);
}
private void CreateHUDHierarchy()
{
Canvas canvas = FindAnyObjectByType<Canvas>();
if (canvas == null)
{
GameObject canvasObj = new GameObject("WaypointHUDCanvas");
canvas = canvasObj.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvas.sortingOrder = 95;
CanvasScaler scaler = canvasObj.AddComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1920, 1080);
scaler.matchWidthOrHeight = 0.5f;
canvasObj.AddComponent<GraphicRaycaster>();
}
// Корневой контейнер
hudContainer = new GameObject("MeetingWaypointHUD");
hudContainer.transform.SetParent(canvas.transform, false);
hudContainer.SetActive(false);
// 1. Плашка путевой метки
GameObject wpObj = new GameObject("WaypointBadge");
wpObj.transform.SetParent(hudContainer.transform, false);
waypointRect = wpObj.AddComponent<RectTransform>();
waypointRect.sizeDelta = new Vector2(230f, 48f);
waypointRect.pivot = new Vector2(0.5f, 0.5f);
waypointBg = wpObj.AddComponent<Image>();
waypointBg.sprite = ProceduralUISprites.GetSlicedRoundedRect(new Color(0.08f, 0.10f, 0.14f, 0.92f), new Color(0.06f, 0.75f, 0.45f, 0.85f), 2f, 14);
waypointBg.type = Image.Type.Sliced;
waypointBg.raycastTarget = false;
// Иконка машинки / пина
GameObject iconObj = new GameObject("Icon");
iconObj.transform.SetParent(wpObj.transform, false);
RectTransform iconRt = iconObj.AddComponent<RectTransform>();
iconRt.anchorMin = new Vector2(0f, 0.5f);
iconRt.anchorMax = new Vector2(0f, 0.5f);
iconRt.pivot = new Vector2(0f, 0.5f);
iconRt.anchoredPosition = new Vector2(12f, 0f);
iconRt.sizeDelta = new Vector2(28f, 28f);
iconImage = iconObj.AddComponent<Image>();
iconImage.sprite = ProceduralUISprites.GetMapPinIcon(64, new Color(0.1f, 0.95f, 0.55f));
iconImage.raycastTarget = false;
// Название автомобиля
GameObject titleObj = new GameObject("CarTitle");
titleObj.transform.SetParent(wpObj.transform, false);
RectTransform titleRt = titleObj.AddComponent<RectTransform>();
titleRt.anchorMin = new Vector2(0f, 0.5f);
titleRt.anchorMax = new Vector2(1f, 1f);
titleRt.offsetMin = new Vector2(46f, 0f);
titleRt.offsetMax = new Vector2(-12f, -4f);
titleText = titleObj.AddComponent<TextMeshProUGUI>();
titleText.fontSize = 14f;
titleText.fontStyle = FontStyles.Bold;
titleText.color = Color.white;
titleText.alignment = TextAlignmentOptions.Left;
titleText.raycastTarget = false;
// Дистанция в метрах
GameObject distObj = new GameObject("Distance");
distObj.transform.SetParent(wpObj.transform, false);
RectTransform distRt = distObj.AddComponent<RectTransform>();
distRt.anchorMin = new Vector2(0f, 0f);
distRt.anchorMax = new Vector2(1f, 0.5f);
distRt.offsetMin = new Vector2(46f, 4f);
distRt.offsetMax = new Vector2(-12f, 0f);
distanceText = distObj.AddComponent<TextMeshProUGUI>();
distanceText.fontSize = 13f;
distanceText.fontStyle = FontStyles.Bold;
distanceText.color = new Color(0.2f, 0.95f, 0.5f);
distanceText.alignment = TextAlignmentOptions.Left;
distanceText.raycastTarget = false;
// Стрелка направления на краю экрана
GameObject arrowObj = new GameObject("DirectionArrow");
arrowObj.transform.SetParent(wpObj.transform, false);
arrowRect = arrowObj.AddComponent<RectTransform>();
arrowRect.sizeDelta = new Vector2(20f, 20f);
arrowRect.pivot = new Vector2(0.5f, 0.5f);
arrowImage = arrowObj.AddComponent<Image>();
arrowImage.sprite = ProceduralUISprites.GetPointerArrow(32, new Color(0.1f, 0.95f, 0.55f));
arrowImage.raycastTarget = false;
arrowObj.SetActive(false);
// 2. Всплывающий баннер прибытия на локацию
arrivalBanner = new GameObject("ArrivalBanner");
arrivalBanner.transform.SetParent(canvas.transform, false);
RectTransform bannerRt = arrivalBanner.AddComponent<RectTransform>();
bannerRt.anchorMin = new Vector2(0.5f, 1f);
bannerRt.anchorMax = new Vector2(0.5f, 1f);
bannerRt.pivot = new Vector2(0.5f, 1f);
bannerRt.anchoredPosition = new Vector2(0f, -40f);
bannerRt.sizeDelta = new Vector2(560f, 72f);
Image bannerBg = arrivalBanner.AddComponent<Image>();
bannerBg.sprite = ProceduralUISprites.GetSlicedRoundedRect(new Color(0.06f, 0.08f, 0.12f, 0.94f), new Color(0.10f, 0.85f, 0.45f, 0.9f), 2f, 16);
bannerBg.type = Image.Type.Sliced;
bannerBg.raycastTarget = false;
arrivalBannerGroup = arrivalBanner.AddComponent<CanvasGroup>();
arrivalBannerGroup.alpha = 0f;
GameObject bannerTextObj = new GameObject("BannerText");
bannerTextObj.transform.SetParent(arrivalBanner.transform, false);
RectTransform btRt = bannerTextObj.AddComponent<RectTransform>();
btRt.anchorMin = Vector2.zero;
btRt.anchorMax = Vector2.one;
btRt.offsetMin = new Vector2(20f, 8f);
btRt.offsetMax = new Vector2(-20f, -8f);
TextMeshProUGUI bText = bannerTextObj.AddComponent<TextMeshProUGUI>();
bText.fontSize = 15f;
bText.alignment = TextAlignmentOptions.Center;
bText.color = Color.white;
bText.text = "<color=#10b981><b>📍 ВЫ ПРИБЫЛИ НА МЕСТО ВСТРЕЧИ!</b></color>\nОсмотрите кузов, проверьте наличие деталей и состояние колес.";
bText.raycastTarget = false;
arrivalBanner.SetActive(false);
}
private void HandleMeetingArranged(CarListing listing)
{
currentListing = listing;
hasTriggeredArrival = false;
if (listing != null && listing.spawnedInstance != null)
{
activeTargetCar = listing.spawnedInstance.transform;
CreateWorldBeacon(activeTargetCar.position);
hudContainer.SetActive(true);
titleText.text = $"{listing.catalogItem.carTitle} ({listing.year})";
}
}
private void HandleMeetingCleared()
{
currentListing = null;
activeTargetCar = null;
if (beaconWorldRoot != null) beaconWorldRoot.SetActive(false);
if (hudContainer != null) hudContainer.SetActive(false);
}
private void CreateWorldBeacon(Vector3 pos)
{
if (beaconWorldRoot == null)
{
beaconWorldRoot = new GameObject("MeetingGPS_WorldBeacon");
// Вертикальный полупрозрачный столб света
GameObject pillar = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
Destroy(pillar.GetComponent<Collider>());
pillar.transform.SetParent(beaconWorldRoot.transform, false);
// Столб начинается над крышей машины и виден издалека; вблизи скрывается, чтобы не мешать осмотру
pillar.transform.localPosition = new Vector3(0f, 28f, 0f);
pillar.transform.localScale = new Vector3(0.35f, 24f, 0.35f);
beaconPillar = pillar;
Renderer r = pillar.GetComponent<Renderer>();
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
r.sharedMaterial = PartCatalog.CreateUnlitMaterial(new Color(0.15f, 1f, 0.55f, 0.35f), true);
// Наземный круг
GameObject ring = GameObject.CreatePrimitive(PrimitiveType.Quad);
Destroy(ring.GetComponent<Collider>());
ring.transform.SetParent(beaconWorldRoot.transform, false);
ring.transform.localPosition = new Vector3(0f, 0.15f, 0f);
ring.transform.localRotation = Quaternion.Euler(90f, 0f, 0f);
ring.transform.localPosition = new Vector3(0f, 0.03f, 0f);
ring.transform.localScale = new Vector3(7f, 7f, 1f);
Renderer ringRend = ring.GetComponent<Renderer>();
ringRend.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
Material ringMat = PartCatalog.CreateUnlitMaterial(Color.white, true);
Texture2D ringTex = new Texture2D(128, 128, TextureFormat.RGBA32, false);
for (int y = 0; y < 128; y++)
for (int x = 0; x < 128; x++)
{
float d = Vector2.Distance(new Vector2(x, y), new Vector2(63.5f, 63.5f)) / 64f;
float a = Mathf.Clamp01(1f - Mathf.Abs(d - 0.85f) * 12f) * 0.8f;
ringTex.SetPixel(x, y, new Color(0.2f, 1f, 0.55f, a));
}
ringTex.Apply();
ringMat.mainTexture = ringTex;
if (ringMat.HasProperty("_BaseMap")) ringMat.SetTexture("_BaseMap", ringTex);
ringRend.sharedMaterial = ringMat;
}
beaconWorldRoot.transform.position = pos;
beaconWorldRoot.SetActive(true);
}
private void Update()
{
UpdateArrivalBanner();
if (activeTargetCar == null)
{
if (hudContainer != null && hudContainer.activeSelf)
hudContainer.SetActive(false);
if (beaconWorldRoot != null && beaconWorldRoot.activeSelf)
beaconWorldRoot.SetActive(false);
return;
}
if (beaconPillar != null && Camera.main != null)
{
bool far = Vector3.Distance(Camera.main.transform.position, activeTargetCar.position) > 18f;
if (beaconPillar.activeSelf != far) beaconPillar.SetActive(far);
}
if (beaconWorldRoot != null) beaconWorldRoot.transform.position = activeTargetCar.position;
// Если игрок уже сел внутрь машины — выключаем метку
VehicleInteraction vi = activeTargetCar.GetComponent<VehicleInteraction>();
if (vi != null && vi.isPlayerInside)
{
HandleMeetingCleared();
return;
}
if (mainCam == null || !mainCam.gameObject.activeInHierarchy)
mainCam = Camera.main ?? FindAnyObjectByType<Camera>();
if (mainCam == null) return;
Vector3 targetWorldPos = activeTargetCar.position + Vector3.up * heightAboveCar;
float dist = Vector3.Distance(mainCam.transform.position, targetWorldPos);
// Обновляем текст расстояния
if (dist >= 1000f)
distanceText.text = $"{(dist / 1000f):F1} км до авто";
else
distanceText.text = $"{dist:F0} м до встречи";
// Проверяем приближение
if (dist <= arrivalDistance && !hasTriggeredArrival)
{
hasTriggeredArrival = true;
ShowArrivalBanner();
}
// 3D -> 2D Screen Position
Vector3 screenPos = mainCam.WorldToScreenPoint(targetWorldPos);
bool isBehind = screenPos.z < 0f;
float marginX = 130f;
float marginY = 50f;
Vector2 screenCenter = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f);
bool isOffscreen = isBehind || screenPos.x < marginX || screenPos.x > (Screen.width - marginX)
|| screenPos.y < marginY || screenPos.y > (Screen.height - marginY);
if (isOffscreen)
{
if (isBehind)
{
screenPos.x = Screen.width - screenPos.x;
screenPos.y = Screen.height - screenPos.y;
}
Vector2 fromCenter = (new Vector2(screenPos.x, screenPos.y) - screenCenter).normalized;
if (fromCenter == Vector2.zero) fromCenter = Vector2.up;
float clampedX = Mathf.Clamp(screenCenter.x + fromCenter.x * (screenCenter.x - marginX), marginX, Screen.width - marginX);
float clampedY = Mathf.Clamp(screenCenter.y + fromCenter.y * (screenCenter.y - marginY), marginY, Screen.height - marginY);
waypointRect.position = new Vector3(clampedX, clampedY, 0f);
// Поворачиваем стрелку в направлении машины
arrowRect.gameObject.SetActive(true);
float angle = Mathf.Atan2(fromCenter.y, fromCenter.x) * Mathf.Rad2Deg - 90f;
arrowRect.rotation = Quaternion.Euler(0f, 0f, angle);
arrowRect.anchoredPosition = new Vector2(fromCenter.x * 125f, fromCenter.y * 32f);
}
else
{
waypointRect.position = screenPos;
arrowRect.gameObject.SetActive(false);
}
// Мягкая пульсация иконки
float pulse = 1f + Mathf.Sin(Time.time * 4f) * 0.08f;
iconImage.transform.localScale = new Vector3(pulse, pulse, 1f);
}
private void ShowArrivalBanner()
{
if (arrivalBanner == null) return;
arrivalBanner.SetActive(true);
arrivalBannerTimer = 5f;
PhoneAudioFeedback.Instance.PlayArrival();
}
private void UpdateArrivalBanner()
{
if (arrivalBanner == null || !arrivalBanner.activeSelf) return;
if (arrivalBannerTimer > 0f)
{
arrivalBannerTimer -= Time.deltaTime;
arrivalBannerGroup.alpha = Mathf.MoveTowards(arrivalBannerGroup.alpha, 1f, Time.deltaTime * 3f);
}
else
{
arrivalBannerGroup.alpha = Mathf.MoveTowards(arrivalBannerGroup.alpha, 0f, Time.deltaTime * 2f);
if (arrivalBannerGroup.alpha <= 0.01f)
arrivalBanner.SetActive(false);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 473faba97f2d6ef43a5dd40b38123be0
@@ -0,0 +1,164 @@
using UnityEngine;
/// <summary>
/// Генератор приятных процедурных звуковых эффектов для смартфона (разблокировка, клики, уведомления от продавца).
/// Не требует внешних .wav файлов.
/// </summary>
public class PhoneAudioFeedback : MonoBehaviour
{
private static PhoneAudioFeedback instance;
public static PhoneAudioFeedback Instance
{
get
{
if (instance == null)
{
GameObject obj = new GameObject("PhoneAudioFeedback");
instance = obj.AddComponent<PhoneAudioFeedback>();
if (Application.isPlaying) DontDestroyOnLoad(obj);
}
return instance;
}
}
private AudioSource audioSource;
private AudioClip tapClip;
private AudioClip unlockClip;
private AudioClip notificationClip;
private AudioClip arrivalClip;
private void Awake()
{
if (instance == null) instance = this;
else if (instance != this)
{
Destroy(gameObject);
return;
}
audioSource = gameObject.AddComponent<AudioSource>();
audioSource.playOnAwake = false;
audioSource.spatialBlend = 0f; // 2D UI sound
GenerateClips();
}
private void GenerateClips()
{
tapClip = CreateTone(1400f, 0.035f, 0.25f, true);
unlockClip = CreateUnlockJingle();
notificationClip = CreateNotificationDing();
arrivalClip = CreateArrivalChord();
}
public void PlayTap()
{
if (tapClip != null && audioSource != null)
audioSource.PlayOneShot(tapClip, 0.35f);
}
public void PlayUnlock()
{
if (unlockClip != null && audioSource != null)
audioSource.PlayOneShot(unlockClip, 0.45f);
}
public void PlayNotification()
{
if (notificationClip != null && audioSource != null)
audioSource.PlayOneShot(notificationClip, 0.6f);
}
public void PlayArrival()
{
if (arrivalClip != null && audioSource != null)
audioSource.PlayOneShot(arrivalClip, 0.7f);
}
private AudioClip CreateTone(float frequency, float duration, float volume, bool decay)
{
int sampleRate = 44100;
int sampleCount = Mathf.CeilToInt(sampleRate * duration);
float[] samples = new float[sampleCount];
for (int i = 0; i < sampleCount; i++)
{
float t = (float)i / sampleRate;
float env = decay ? Mathf.Exp(-t * 12f / duration) : 1f;
samples[i] = Mathf.Sin(2f * Mathf.PI * frequency * t) * volume * env;
}
AudioClip clip = AudioClip.Create("Phone_Tone", sampleCount, 1, sampleRate, false);
clip.SetData(samples, 0);
return clip;
}
private AudioClip CreateUnlockJingle()
{
int sampleRate = 44100;
float duration = 0.18f;
int sampleCount = Mathf.CeilToInt(sampleRate * duration);
float[] samples = new float[sampleCount];
for (int i = 0; i < sampleCount; i++)
{
float t = (float)i / sampleRate;
float freq = Mathf.Lerp(480f, 820f, t / duration);
float env = Mathf.Sin((t / duration) * Mathf.PI);
samples[i] = Mathf.Sin(2f * Mathf.PI * freq * t) * 0.35f * env;
}
AudioClip clip = AudioClip.Create("Phone_Unlock", sampleCount, 1, sampleRate, false);
clip.SetData(samples, 0);
return clip;
}
private AudioClip CreateNotificationDing()
{
int sampleRate = 44100;
float duration = 0.35f;
int sampleCount = Mathf.CeilToInt(sampleRate * duration);
float[] samples = new float[sampleCount];
for (int i = 0; i < sampleCount; i++)
{
float t = (float)i / sampleRate;
// Двухтональный звонок (880 Гц -> 1320 Гц)
float freq = (t < 0.1f) ? 880f : 1320f;
float subT = (t < 0.1f) ? t : (t - 0.1f);
float env = Mathf.Exp(-subT * 7f);
samples[i] = Mathf.Sin(2f * Mathf.PI * freq * t) * 0.45f * env;
}
AudioClip clip = AudioClip.Create("Phone_Notification", sampleCount, 1, sampleRate, false);
clip.SetData(samples, 0);
return clip;
}
private AudioClip CreateArrivalChord()
{
int sampleRate = 44100;
float duration = 0.65f;
int sampleCount = Mathf.CeilToInt(sampleRate * duration);
float[] samples = new float[sampleCount];
// Мажорный аккорд: C5 (523Hz), E5 (659Hz), G5 (784Hz)
float[] freqs = new float[] { 523.25f, 659.25f, 783.99f };
for (int i = 0; i < sampleCount; i++)
{
float t = (float)i / sampleRate;
float env = Mathf.Exp(-t * 4.5f);
float s = 0f;
for (int f = 0; f < freqs.Length; f++)
{
s += Mathf.Sin(2f * Mathf.PI * freqs[f] * t);
}
samples[i] = (s / freqs.Length) * 0.5f * env;
}
AudioClip clip = AudioClip.Create("Waypoint_Arrival", sampleCount, 1, sampleRate, false);
clip.SetData(samples, 0);
return clip;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 040f8559420527c4e97c0735d735a886
@@ -0,0 +1,501 @@
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Процедурный генератор высококачественных сглаженных спрайтов для смартфона и интерфейса.
/// Позволяет создавать ультра-четкий современный UI без внешних тяжелых текстур.
/// </summary>
public static class ProceduralUISprites
{
private static readonly Dictionary<string, Sprite> spriteCache = new Dictionary<string, Sprite>();
/// <summary>
/// Создает 9-sliced скругленный прямоугольник с настраиваемым радиусом и рамкой.
/// </summary>
public static Sprite GetSlicedRoundedRect(Color fillColor, Color? borderColor = null, float borderWidth = 0f, int cornerRadius = 18)
{
int size = Mathf.Max(64, cornerRadius * 2 + 16);
string key = $"s_rr_{size}_{cornerRadius}_{fillColor}_{borderColor}_{borderWidth}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
Color border = borderColor ?? fillColor;
float half = size * 0.5f;
float r = cornerRadius;
float innerBoxHalf = half - r;
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
float px = x + 0.5f - half;
float py = y + 0.5f - half;
float qx = Mathf.Max(0f, Mathf.Abs(px) - innerBoxHalf);
float qy = Mathf.Max(0f, Mathf.Abs(py) - innerBoxHalf);
float dist = Mathf.Sqrt(qx * qx + qy * qy);
float outerAlpha = Mathf.Clamp01(r - dist + 0.6f);
if (outerAlpha <= 0.001f)
{
tex.SetPixel(x, y, Color.clear);
continue;
}
if (borderWidth > 0f)
{
float borderT = Mathf.Clamp01((r - borderWidth - dist + 0.6f));
Color pixelColor = Color.Lerp(border, fillColor, borderT);
pixelColor.a *= outerAlpha;
tex.SetPixel(x, y, pixelColor);
}
else
{
Color pixelColor = fillColor;
pixelColor.a *= outerAlpha;
tex.SetPixel(x, y, pixelColor);
}
}
}
tex.Apply();
Vector4 borderSlice = new Vector4(cornerRadius + 2, cornerRadius + 2, cornerRadius + 2, cornerRadius + 2);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f), 100f, 0, SpriteMeshType.FullRect, borderSlice);
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает гладкий круг с опциональной обводкой.
/// </summary>
public static Sprite GetCircle(int size, Color fillColor, Color? borderColor = null, float borderWidth = 0f)
{
string key = $"circle_{size}_{fillColor}_{borderColor}_{borderWidth}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
Color border = borderColor ?? fillColor;
float center = (size - 1) * 0.5f;
float radius = size * 0.5f - 1f;
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
float dist = Vector2.Distance(new Vector2(x, y), new Vector2(center, center));
float alpha = Mathf.Clamp01(radius - dist + 0.6f);
if (alpha <= 0.001f)
{
tex.SetPixel(x, y, Color.clear);
continue;
}
if (borderWidth > 0f)
{
float borderT = Mathf.Clamp01(radius - borderWidth - dist + 0.6f);
Color col = Color.Lerp(border, fillColor, borderT);
col.a *= alpha;
tex.SetPixel(x, y, col);
}
else
{
Color col = fillColor;
col.a *= alpha;
tex.SetPixel(x, y, col);
}
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает стильный вертикальный градиент (например, для обоев рабочего стола телефона).
/// </summary>
public static Sprite GetGradient(int width, int height, Color topColor, Color bottomColor)
{
string key = $"grad_{width}_{height}_{topColor}_{bottomColor}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
for (int y = 0; y < height; y++)
{
float t = (float)y / Mathf.Max(1, height - 1);
Color col = Color.Lerp(bottomColor, topColor, t);
for (int x = 0; x < width; x++)
{
tex.SetPixel(x, y, col);
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает иконку Wi-Fi.
/// </summary>
public static Sprite GetWifiIcon(int size, Color color)
{
string key = $"wifi_{size}_{color}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
Vector2 center = new Vector2((size - 1) * 0.5f, size * 0.2f);
float[] radii = new float[] { size * 0.65f, size * 0.45f, size * 0.25f };
float arcHalfAngle = 42f;
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
Vector2 pos = new Vector2(x, y);
float dist = Vector2.Distance(pos, center);
Vector2 dir = pos - center;
float angle = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg;
float alpha = 0f;
// Базовая точка внизу
if (dist <= size * 0.1f)
{
alpha = Mathf.Clamp01(size * 0.1f - dist + 0.6f);
}
else if (Mathf.Abs(angle) <= arcHalfAngle && dir.y > 0)
{
float angleFade = Mathf.Clamp01((arcHalfAngle - Mathf.Abs(angle)) / 6f);
foreach (float r in radii)
{
float ringDist = Mathf.Abs(dist - r);
float ringThickness = size * 0.05f;
if (ringDist <= ringThickness)
{
float ringAlpha = Mathf.Clamp01(ringThickness - ringDist + 0.5f) * angleFade;
alpha = Mathf.Max(alpha, ringAlpha);
}
}
}
Color c = color;
c.a *= alpha;
tex.SetPixel(x, y, c);
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает иконку полос мобильной сети (Cellular Signal Bars).
/// </summary>
public static Sprite GetSignalBarsIcon(int width, int height, Color activeColor, int activeBars = 4)
{
string key = $"bars_{width}_{height}_{activeColor}_{activeBars}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Point,
wrapMode = TextureWrapMode.Clamp
};
// Заполняем прозрачным
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
tex.SetPixel(x, y, Color.clear);
int totalBars = 4;
float barWidth = (width - (totalBars - 1) * 2f) / totalBars;
for (int b = 0; b < totalBars; b++)
{
float barHeight = height * ((b + 1f) / totalBars);
float startX = b * (barWidth + 2f);
Color barCol = (b < activeBars) ? activeColor : new Color(activeColor.r, activeColor.g, activeColor.b, 0.25f);
for (int y = 0; y < Mathf.RoundToInt(barHeight); y++)
{
for (int x = Mathf.RoundToInt(startX); x < Mathf.RoundToInt(startX + barWidth); x++)
{
if (x < width && y < height)
tex.SetPixel(x, y, barCol);
}
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает иконку батареи с уровнем заряда.
/// </summary>
public static Sprite GetBatteryIcon(int width, int height, Color bodyColor, Color levelColor, float percentage = 0.85f)
{
string key = $"batt_{width}_{height}_{bodyColor}_{levelColor}_{percentage:F2}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
tex.SetPixel(x, y, Color.clear);
int tipW = 3;
int mainW = width - tipW - 1;
int tipH = Mathf.RoundToInt(height * 0.45f);
int tipYStart = (height - tipH) / 2;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// Пипка справа
if (x >= mainW && x < width && y >= tipYStart && y < tipYStart + tipH)
{
tex.SetPixel(x, y, bodyColor);
continue;
}
// Корпус батарейки
if (x < mainW)
{
bool isBorder = (x == 0 || x == mainW - 1 || y == 0 || y == height - 1);
if (isBorder)
{
tex.SetPixel(x, y, bodyColor);
}
else
{
// Заполнение уровня заряда внутри (с отступом 2 пикселя)
float innerFillW = (mainW - 4) * Mathf.Clamp01(percentage);
if (x >= 2 && x < 2 + innerFillW && y >= 2 && y < height - 2)
{
tex.SetPixel(x, y, levelColor);
}
}
}
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает стилизованную векторную иконку автомобиля для приложения АвтоБазар.
/// </summary>
public static Sprite GetCarIcon(int size, Color color)
{
string key = $"car_ico_{size}_{color}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
tex.SetPixel(x, y, Color.clear);
// Рисуем силуэт автомобиля в профиль
float s = size;
for (int y = 0; y < size; y++)
{
float ny = y / s;
for (int x = 0; x < size; x++)
{
float nx = x / s;
bool isBody = false;
// Нижний кузов (от nx=0.1 до 0.9, ny=0.35 до 0.55)
if (nx >= 0.12f && nx <= 0.88f && ny >= 0.35f && ny <= 0.52f)
isBody = true;
// Кабина / крыша (от nx=0.28 до 0.72, ny=0.50 до 0.70)
if (ny >= 0.50f && ny <= 0.68f)
{
float roofMin = Mathf.Lerp(0.20f, 0.34f, (ny - 0.50f) / 0.18f);
float roofMax = Mathf.Lerp(0.85f, 0.68f, (ny - 0.50f) / 0.18f);
if (nx >= roofMin && nx <= roofMax)
isBody = true;
}
// Вырезы под колеса
float distWheel1 = Vector2.Distance(new Vector2(nx, ny), new Vector2(0.28f, 0.35f));
float distWheel2 = Vector2.Distance(new Vector2(nx, ny), new Vector2(0.72f, 0.35f));
if (distWheel1 < 0.11f || distWheel2 < 0.11f)
isBody = false;
// Сами колеса (шины)
if (distWheel1 < 0.09f || distWheel2 < 0.09f)
isBody = true;
if (isBody)
tex.SetPixel(x, y, color);
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает векторную иконку геометки / пина навигатора.
/// </summary>
public static Sprite GetMapPinIcon(int size, Color color)
{
string key = $"pin_ico_{size}_{color}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
tex.SetPixel(x, y, Color.clear);
Vector2 headCenter = new Vector2(size * 0.5f, size * 0.65f);
float headRadius = size * 0.28f;
Vector2 tip = new Vector2(size * 0.5f, size * 0.12f);
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
Vector2 pos = new Vector2(x, y);
float distHead = Vector2.Distance(pos, headCenter);
float alpha = 0f;
// Верхняя округлая часть пина
if (distHead <= headRadius)
{
alpha = Mathf.Clamp01(headRadius - distHead + 0.6f);
// Отверстие в центре пина
float holeRadius = headRadius * 0.42f;
if (distHead < holeRadius)
{
alpha = Mathf.Clamp01(distHead - holeRadius + 0.6f);
}
}
// Нижний конусообразный хвостик
else if (y < headCenter.y && y >= tip.y)
{
float progress = (headCenter.y - y) / (headCenter.y - tip.y);
float coneWidth = Mathf.Lerp(headRadius * 0.95f, 2f, progress);
float dx = Mathf.Abs(x - tip.x);
if (dx <= coneWidth)
{
alpha = Mathf.Clamp01(coneWidth - dx + 0.6f);
}
}
Color c = color;
c.a *= alpha;
tex.SetPixel(x, y, c);
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
/// <summary>
/// Создает стрелку указателя направления (для указания на машину вне экрана).
/// </summary>
public static Sprite GetPointerArrow(int size, Color color)
{
string key = $"arrow_{size}_{color}";
if (spriteCache.TryGetValue(key, out Sprite cached) && cached != null)
return cached;
Texture2D tex = new Texture2D(size, size, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
tex.SetPixel(x, y, Color.clear);
float center = (size - 1) * 0.5f;
for (int y = 0; y < size; y++)
{
float ny = (float)y / size; // 0..1 (вверх)
float halfW = Mathf.Lerp(0f, size * 0.45f, 1f - ny);
for (int x = 0; x < size; x++)
{
float dx = Mathf.Abs(x - center);
if (dx <= halfW)
{
float a = Mathf.Clamp01(halfW - dx + 0.6f);
Color c = color;
c.a *= a;
tex.SetPixel(x, y, c);
}
}
}
tex.Apply();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f));
spriteCache[key] = sprite;
return sprite;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: dd21cf2efce2fc84a98a88b3940f0708
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 137929786778a74448ac28bb19488fa6
+354
View File
@@ -0,0 +1,354 @@
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
[DisallowMultipleComponent]
public class RestorationHUD : MonoBehaviour
{
public static RestorationHUD Instance { get; private set; }
[Header("Настройки анимации и расположения")]
[SerializeField] private Vector2 hudAnchoredPosition = new Vector2(0f, -140f);
[SerializeField] private float fadeSpeed = 12f;
private CanvasGroup canvasGroup;
private RectTransform rootCard;
private TextMeshProUGUI titleText;
private TextMeshProUGUI stageBadgeText;
private Image stageBadgeBg;
private Image progressFill;
private TextMeshProUGUI progressPercentText;
private TextMeshProUGUI hintText;
// Секция залива жидкостей
private GameObject fluidSection;
private Image fluidGaugeFill;
private TextMeshProUGUI fluidLitersText;
private TextMeshProUGUI fluidHintText;
private float targetAlpha = 0f;
private float hideTimer = 0f;
private float currentFillAmount = 0f;
private void Awake()
{
if (Instance == null) Instance = this;
else if (Instance != this) { Destroy(gameObject); return; }
EnsureUIElementsCreated();
}
private void EnsureUIElementsCreated()
{
canvasGroup = GetComponent<CanvasGroup>();
if (canvasGroup == null) canvasGroup = gameObject.AddComponent<CanvasGroup>();
canvasGroup.alpha = 0f;
canvasGroup.blocksRaycasts = false;
canvasGroup.interactable = false;
RectTransform myRect = GetComponent<RectTransform>();
if (myRect == null) myRect = gameObject.AddComponent<RectTransform>();
// Если элементы еще не созданы в иерархии — собираем стильную стеклянную карточку
if (titleText == null)
{
BuildModernHUD(myRect);
}
}
private void BuildModernHUD(RectTransform parent)
{
parent.anchorMin = new Vector2(0.5f, 0.5f);
parent.anchorMax = new Vector2(0.5f, 0.5f);
parent.pivot = new Vector2(0.5f, 0.5f);
parent.anchoredPosition = hudAnchoredPosition;
parent.sizeDelta = new Vector2(420f, 130f);
// 1. Фоновая плашка с эффектом темного стекла и мягкой обводкой
Image cardBg = gameObject.GetComponent<Image>();
if (cardBg == null) cardBg = gameObject.AddComponent<Image>();
cardBg.sprite = ProceduralUISprites.GetSlicedRoundedRect(
new Color(0.08f, 0.10f, 0.14f, 0.88f),
new Color(0.28f, 0.35f, 0.45f, 0.45f),
1.5f, 16);
cardBg.type = Image.Type.Sliced;
cardBg.raycastTarget = false;
// 2. Верхняя строка: Заголовок детали + Бейдж этапа
GameObject topRow = new GameObject("TopRow");
topRow.transform.SetParent(transform, false);
RectTransform trRt = topRow.AddComponent<RectTransform>();
trRt.anchorMin = new Vector2(0f, 1f);
trRt.anchorMax = new Vector2(1f, 1f);
trRt.pivot = new Vector2(0.5f, 1f);
trRt.anchoredPosition = new Vector2(0f, -12f);
trRt.sizeDelta = new Vector2(-24f, 26f);
// Название детали
GameObject titleObj = new GameObject("TitleText");
titleObj.transform.SetParent(topRow.transform, false);
RectTransform titleRt = titleObj.AddComponent<RectTransform>();
titleRt.anchorMin = new Vector2(0f, 0f);
titleRt.anchorMax = new Vector2(0.65f, 1f);
titleRt.pivot = new Vector2(0f, 0.5f);
titleRt.anchoredPosition = Vector2.zero;
titleRt.sizeDelta = Vector2.zero;
titleText = titleObj.AddComponent<TextMeshProUGUI>();
titleText.fontSize = 15f;
titleText.fontStyle = FontStyles.Bold;
titleText.color = new Color(0.95f, 0.96f, 0.98f);
titleText.alignment = TextAlignmentOptions.MidlineLeft;
titleText.text = "Передняя левая дверь";
// Бейдж этапа
GameObject badgeObj = new GameObject("StageBadge");
badgeObj.transform.SetParent(topRow.transform, false);
RectTransform badgeRt = badgeObj.AddComponent<RectTransform>();
badgeRt.anchorMin = new Vector2(0.65f, 0f);
badgeRt.anchorMax = new Vector2(1f, 1f);
badgeRt.pivot = new Vector2(1f, 0.5f);
badgeRt.anchoredPosition = Vector2.zero;
badgeRt.sizeDelta = Vector2.zero;
stageBadgeBg = badgeObj.AddComponent<Image>();
stageBadgeBg.sprite = ProceduralUISprites.GetSlicedRoundedRect(
new Color(0.85f, 0.35f, 0.12f, 0.9f), null, 0f, 8);
stageBadgeBg.type = Image.Type.Sliced;
GameObject badgeTextObj = new GameObject("BadgeText");
badgeTextObj.transform.SetParent(badgeObj.transform, false);
RectTransform btRt = badgeTextObj.AddComponent<RectTransform>();
btRt.anchorMin = Vector2.zero;
btRt.anchorMax = Vector2.one;
btRt.sizeDelta = Vector2.zero;
stageBadgeText = badgeTextObj.AddComponent<TextMeshProUGUI>();
stageBadgeText.fontSize = 12f;
stageBadgeText.fontStyle = FontStyles.Bold;
stageBadgeText.color = Color.white;
stageBadgeText.alignment = TextAlignmentOptions.Center;
stageBadgeText.text = "Ржавчина";
// 3. Полоса прогресса
GameObject progressTrack = new GameObject("ProgressTrack");
progressTrack.transform.SetParent(transform, false);
RectTransform ptRt = progressTrack.AddComponent<RectTransform>();
ptRt.anchorMin = new Vector2(0f, 0.5f);
ptRt.anchorMax = new Vector2(1f, 0.5f);
ptRt.pivot = new Vector2(0.5f, 0.5f);
ptRt.anchoredPosition = new Vector2(0f, 2f);
ptRt.sizeDelta = new Vector2(-24f, 16f);
Image trackBg = progressTrack.AddComponent<Image>();
trackBg.sprite = ProceduralUISprites.GetSlicedRoundedRect(
new Color(0.12f, 0.15f, 0.20f, 0.95f),
new Color(0.22f, 0.26f, 0.35f, 0.5f), 1f, 8);
trackBg.type = Image.Type.Sliced;
GameObject fillObj = new GameObject("ProgressFill");
fillObj.transform.SetParent(progressTrack.transform, false);
RectTransform fillRt = fillObj.AddComponent<RectTransform>();
fillRt.anchorMin = Vector2.zero;
fillRt.anchorMax = Vector2.one;
fillRt.sizeDelta = new Vector2(-4f, -4f);
progressFill = fillObj.AddComponent<Image>();
progressFill.sprite = ProceduralUISprites.GetSlicedRoundedRect(
new Color(0.20f, 0.65f, 0.95f, 0.95f), null, 0f, 6);
progressFill.type = Image.Type.Filled;
progressFill.fillMethod = Image.FillMethod.Horizontal;
progressFill.fillOrigin = 0;
progressFill.fillAmount = 0.5f;
GameObject pctObj = new GameObject("PercentText");
pctObj.transform.SetParent(progressTrack.transform, false);
RectTransform pctRt = pctObj.AddComponent<RectTransform>();
pctRt.anchorMin = Vector2.zero;
pctRt.anchorMax = Vector2.one;
pctRt.sizeDelta = Vector2.zero;
progressPercentText = pctObj.AddComponent<TextMeshProUGUI>();
progressPercentText.fontSize = 11f;
progressPercentText.fontStyle = FontStyles.Bold;
progressPercentText.color = Color.white;
progressPercentText.alignment = TextAlignmentOptions.Center;
progressPercentText.text = "50%";
// 4. Нижняя подсказка / контекстное действие
GameObject hintObj = new GameObject("HintText");
hintObj.transform.SetParent(transform, false);
RectTransform hintRt = hintObj.AddComponent<RectTransform>();
hintRt.anchorMin = new Vector2(0f, 0f);
hintRt.anchorMax = new Vector2(1f, 0f);
hintRt.pivot = new Vector2(0.5f, 0f);
hintRt.anchoredPosition = new Vector2(0f, 10f);
hintRt.sizeDelta = new Vector2(-24f, 32f);
hintText = hintObj.AddComponent<TextMeshProUGUI>();
hintText.fontSize = 12.5f;
hintText.color = new Color(0.82f, 0.86f, 0.92f);
hintText.alignment = TextAlignmentOptions.Center;
hintText.text = "[Удерж. ЛКМ] Водите инструментом по детали";
// 5. Секция жидкостей (по умолчанию скрыта)
fluidSection = new GameObject("FluidSection");
fluidSection.transform.SetParent(transform, false);
RectTransform fsRt = fluidSection.AddComponent<RectTransform>();
fsRt.anchorMin = Vector2.zero;
fsRt.anchorMax = Vector2.one;
fsRt.sizeDelta = Vector2.zero;
fluidSection.SetActive(false);
}
private void Update()
{
if (hideTimer > 0f)
{
hideTimer -= Time.deltaTime;
if (hideTimer <= 0f) targetAlpha = 0f;
}
if (canvasGroup != null)
{
canvasGroup.alpha = Mathf.Lerp(canvasGroup.alpha, targetAlpha, Time.deltaTime * fadeSpeed);
}
if (progressFill != null)
{
progressFill.fillAmount = Mathf.Lerp(progressFill.fillAmount, currentFillAmount, Time.deltaTime * 15f);
}
}
public void ShowRestorationProgress(
string partName,
RepairStage stage,
float progress01,
string contextualHint,
bool isCorrectTool)
{
EnsureUIElementsCreated();
targetAlpha = 1f;
hideTimer = 0.25f;
if (titleText != null) titleText.text = partName;
currentFillAmount = Mathf.Clamp01(progress01);
int percent = Mathf.RoundToInt(currentFillAmount * 100f);
if (progressPercentText != null)
{
if (stage == RepairStage.Healthy || stage == RepairStage.Repaired)
progressPercentText.text = "100%";
else
progressPercentText.text = $"{percent}%";
}
// Обновляем бейдж этапа и цвета
SetupStageBadge(stage);
if (hintText != null)
{
hintText.text = contextualHint;
hintText.color = isCorrectTool ? new Color(0.85f, 0.92f, 1.0f) : new Color(1.0f, 0.65f, 0.35f);
}
}
private void SetupStageBadge(RepairStage stage)
{
if (stageBadgeText == null || stageBadgeBg == null) return;
Color badgeColor;
string badgeName;
switch (stage)
{
case RepairStage.Healthy:
badgeName = "Заводская";
badgeColor = new Color(0.18f, 0.72f, 0.38f);
break;
case RepairStage.Rusted:
badgeName = "Ржавчина";
badgeColor = new Color(0.92f, 0.38f, 0.12f);
break;
case RepairStage.Cleaned:
badgeName = "Зачищено";
badgeColor = new Color(0.55f, 0.62f, 0.70f);
break;
case RepairStage.Puttied:
badgeName = "Шпаклёвка";
badgeColor = new Color(0.82f, 0.70f, 0.35f);
break;
case RepairStage.Sanded:
badgeName = "Шлифовка";
badgeColor = new Color(0.20f, 0.68f, 0.42f);
break;
default:
badgeName = "Восстановлено";
badgeColor = new Color(0.15f, 0.75f, 0.95f);
break;
}
stageBadgeText.text = badgeName;
stageBadgeBg.color = badgeColor;
if (progressFill != null) progressFill.color = badgeColor;
}
public void ShowFluidPouringHUD(
string tankTitle,
FluidType type,
float currentLiters,
float maxLiters,
float canisterRemainingLiters,
Color fluidColor)
{
EnsureUIElementsCreated();
targetAlpha = 1f;
hideTimer = 0.25f;
float fill01 = Mathf.Clamp01(currentLiters / Mathf.Max(maxLiters, 0.01f));
currentFillAmount = fill01;
int percent = Mathf.RoundToInt(fill01 * 100f);
if (titleText != null) titleText.text = tankTitle;
if (stageBadgeText != null)
{
stageBadgeText.text = "Залив жидкости";
stageBadgeBg.color = fluidColor;
}
if (progressFill != null)
{
progressFill.color = fluidColor;
}
if (progressPercentText != null)
{
progressPercentText.text = $"{currentLiters:F1} / {maxLiters:F1} л ({percent}%)";
}
if (hintText != null)
{
hintText.text = $"[Удерж. ЛКМ] Залить жидкость | В канистре: {canisterRemainingLiters:F1} л";
hintText.color = Color.white;
}
}
public void ShowCustomMessage(string message)
{
EnsureUIElementsCreated();
targetAlpha = 1f;
hideTimer = 0.25f;
if (hintText != null)
{
hintText.text = message;
hintText.color = new Color(1.0f, 0.85f, 0.45f);
}
}
public void Hide()
{
targetAlpha = 0f;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8d81869a3a4e89b46a8a0e93171ef056
+246
View File
@@ -0,0 +1,246 @@
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Покупка и торг с продавцом [B]: найденные игроком дефекты (кузов, колеса, подкапотное пространство,
/// ошибки OBD, скрытый перекрас) становятся аргументами и снижают цену на 10–25%.
/// Можно сразу заказать эвакуатор до гаража, если машина не на ходу.
/// </summary>
public class SellerBargainUI : MonoBehaviour
{
[SerializeField] private KeyCode openKey = KeyCode.B;
[SerializeField] private float interactDistance = 7f;
[SerializeField] private float maxDiscountPercent = 25f;
[SerializeField] private float towTruckPrice = 60f;
private CarOwnership target;
private List<CarInspection.Defect> defects = new List<CarInspection.Defect>();
private readonly HashSet<string> usedArguments = new HashSet<string>();
private float discountPercent;
private string sellerReply;
private bool isOpen;
private Vector2 scroll;
private Transform player;
private static readonly string[] AgreeReplies =
{
"Ну да, есть такое... Ладно, скину немного.",
"Эх, глазастый попался. Давай уступлю.",
"Это мелочи, но так и быть — минус.",
"Хорошо, хорошо, торг уместен.",
"Ты прав, придется вложиться. Сбавлю."
};
private void Update()
{
if (isOpen)
{
if (Input.GetKeyDown(KeyCode.Escape) || target == null) Close();
return;
}
if (GameInputLock.IsLocked || VehicleInteraction.Current != null) return;
MainMenuAndBootManager menu = MainMenuAndBootManager.Instance;
if (menu != null && !menu.IsPlaying) return;
if (player == null)
{
PlayerMovement pm = FindAnyObjectByType<PlayerMovement>();
if (pm != null) player = pm.transform;
}
if (player == null || !player.gameObject.activeInHierarchy) return;
CarOwnership near = CarOwnership.FindNearestNotOwned(player.position, interactDistance);
if (near == null) return;
GameHUD.SetContextHint($"{near.carTitle} — продавец {near.sellerName} ждет: [B] Оформить сделку / Торговаться");
if (Input.GetKeyDown(openKey)) Open(near);
}
private void Open(CarOwnership car)
{
target = car;
defects = CarInspection.CollectDefects(car);
usedArguments.Clear();
discountPercent = 0f;
sellerReply = $"Здравствуйте! Машина {car.carTitle}, {car.year} г. Прошу {GameUI.Money(car.askingPrice)}. Смотрите, проверяйте.";
isOpen = true;
GameInputLock.Lock(this);
ProceduralAudioManager.Instance?.Play(SfxId.Notification);
}
private void Close()
{
isOpen = false;
target = null;
GameInputLock.Unlock(this);
}
private float CurrentPrice => target == null ? 0f : Mathf.Round(target.askingPrice * (1f - discountPercent / 100f) / 10f) * 10f;
private bool CarIsDrivable()
{
if (target == null) return false;
EngineBayManager bay = target.GetComponent<EngineBayManager>();
EnginePart bat = bay != null ? bay.GetPart(EnginePartType.Battery) : null;
bool engineOk = bay == null || (bat != null && bat.charge >= 20f && bay.GetPart(EnginePartType.SparkPlugs) != null);
int wheels = 0;
foreach (WheelCollider wc in target.GetComponentsInChildren<WheelCollider>()) if (wc.enabled) wheels++;
return engineOk && wheels >= 4;
}
private void UseArgument(CarInspection.Defect d)
{
if (usedArguments.Contains(d.text)) return;
usedArguments.Add(d.text);
if (discountPercent >= maxDiscountPercent - 0.01f)
{
sellerReply = "Всё, ниже не опущу! Это и так последняя цена.";
ProceduralAudioManager.Instance?.Play(SfxId.Error);
return;
}
float add = d.discountPercent * Random.Range(0.85f, 1.25f);
discountPercent = Mathf.Min(maxDiscountPercent, discountPercent + add);
sellerReply = AgreeReplies[Random.Range(0, AgreeReplies.Length)] + $" Скидка уже {discountPercent:F0}%.";
ProceduralAudioManager.Instance?.Play(SfxId.Ui, null, 1f, 1.2f);
}
private void Buy(bool withTowTruck)
{
GameEconomyManager eco = GameEconomyManager.Instance;
float price = CurrentPrice;
float total = price + (withTowTruck ? towTruckPrice : 0f);
if (eco != null && !eco.CanAfford(total))
{
sellerReply = "Денег не хватает? Приходите, когда соберете нужную сумму.";
ProceduralAudioManager.Instance?.Play(SfxId.Error);
return;
}
CarOwnership car = target;
car.isOwned = true;
car.purchasePrice = price;
car.expenses = 0f;
if (eco != null)
{
eco.TrySpend(price, $"Покупка {car.carTitle}", null, false);
if (withTowTruck) eco.TrySpend(towTruckPrice, "Эвакуатор до гаража", car);
}
CarMarketManager market = FindAnyObjectByType<CarMarketManager>();
if (market != null && car.Listing != null) market.MarkListingSold(car.Listing);
if (withTowTruck) TowToGarage(car);
GameHUD.Notify($"Куплено: {car.carTitle} за {GameUI.Money(price)}" + (discountPercent > 0.5f ? $" (скидка {discountPercent:F0}%)" : ""), GameUI.Green);
Close();
}
public static void TowToGarage(CarOwnership car)
{
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco == null || eco.garageCarSpot == null || car == null) return;
Vector3 pos = eco.garageCarSpot.position;
// Если место в боксе занято — ставим во дворе рядом
foreach (CarOwnership other in CarOwnership.All)
{
if (other == null || other == car) continue;
if (Vector3.Distance(other.transform.position, pos) < 3.5f)
{
pos = eco.garageCarSpot.position + eco.garageCarSpot.forward * 11f + eco.garageCarSpot.right * 4.5f;
break;
}
}
// Старые кирпичи (и их физический якорь) убираем — в гараже поставим новые под пустую ступицу
foreach (WheelBrickSupport b in FindObjectsByType<WheelBrickSupport>(FindObjectsSortMode.None))
if (Vector3.Distance(b.transform.position, car.transform.position) < 4f) b.RemoveBricks();
Rigidbody rb = car.GetComponent<Rigidbody>();
Vector3 target = pos + Vector3.up * 0.35f;
car.transform.SetPositionAndRotation(target, eco.garageCarSpot.rotation);
if (rb != null)
{
rb.position = target;
rb.rotation = eco.garageCarSpot.rotation;
rb.linearVelocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
}
Physics.SyncTransforms();
foreach (CarPart wheel in car.GetComponentsInChildren<CarPart>(true))
{
if (wheel.LinkedWheelCollider == null || wheel.gameObject.activeSelf || wheel.State == PartState.Installed) continue;
WheelBrickSupport.CreateUnderWheel(wheel);
}
GameHUD.Notify($"Эвакуатор доставил {car.carTitle} в гараж", GameUI.Blue);
}
private void OnGUI()
{
if (!isOpen || target == null) 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));
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), $"СДЕЛКА: {target.carTitle}", GameUI.Header);
GUI.Label(new Rect(r.x + 30, r.y + 62, r.width - 60, 30),
$"{target.year} г. • пробег {target.mileageKm:N0} км • продавец: {target.sellerName} • цена в объявлении: {GameUI.Money(target.askingPrice)}", GameUI.Small);
Rect reply = new Rect(r.x + 30, r.y + 104, r.width - 60, 64);
GUI.Box(reply, GUIContent.none, GameUI.Panel);
GUI.Label(new Rect(reply.x + 16, reply.y + 8, reply.width - 32, reply.height - 16), $"<color=#9AA0A6>Продавец:</color> «{sellerReply}»", GameUI.Label);
GUI.Label(new Rect(r.x + 30, r.y + 186, r.width - 60, 30), "<b>Найденные дефекты — аргументы для снижения цены:</b>", GameUI.Label);
Rect listView = new Rect(r.x + 30, r.y + 222, r.width - 60, 400);
int hidden = 0;
float rowH = 54f;
List<CarInspection.Defect> shown = new List<CarInspection.Defect>();
foreach (var d in defects) { if (d.revealed) shown.Add(d); else hidden++; }
scroll = GUI.BeginScrollView(listView, scroll, new Rect(0, 0, listView.width - 24, Mathf.Max(listView.height, shown.Count * rowH + 10)));
float y = 0;
if (shown.Count == 0)
GUI.Label(new Rect(0, 0, listView.width - 30, 60), "Явных дефектов не видно. Осмотрите машину внимательнее: капот, OBD-сканер, толщиномер ЛКП.", GameUI.Small);
foreach (var d in shown)
{
bool used = usedArguments.Contains(d.text);
GUI.Label(new Rect(4, y + 12, listView.width - 290, 34), $"• {d.text}", GameUI.Label);
if (used)
GUI.Label(new Rect(listView.width - 270, y + 12, 240, 34), "<color=#4CD07D>учтено</color>", GameUI.LabelCenter);
else if (GameUI.Btn(new Rect(listView.width - 270, y + 6, 240, 44), "Указать продавцу"))
UseArgument(d);
y += rowH;
}
GUI.EndScrollView();
if (hidden > 0)
GUI.Label(new Rect(r.x + 30, r.y + 628, r.width - 60, 30),
$"<color=#F2A93B>Возможны скрытые дефекты ({hidden}).</color> Проверьте: открыть капот и щуп, OBD-сканер [Tab], толщиномер ЛКП [Tab].", GameUI.Small);
GUI.Label(new Rect(r.x + 30, r.y + 666, 760, 50),
$"Итоговая цена: <b><color=#4CD07D>{GameUI.Money(CurrentPrice)}</color></b> (скидка {discountPercent:F0}%)", new GUIStyle(GameUI.Label) { fontSize = 24 });
GameEconomyManager eco = GameEconomyManager.Instance;
string balance = eco == null ? "" : (eco.Unlimited ? "Свободный режим: деньги не ограничены" : $"На счету: {eco.FormatMoney(eco.Money)}");
GUI.Label(new Rect(r.x + 30, r.y + 708, r.width - 60, 30), balance, GameUI.Small);
bool drivable = CarIsDrivable();
float by = r.yMax - 92;
if (GameUI.Btn(new Rect(r.x + 30, by, 330, 62), "КУПИТЬ\n<size=15>своим ходом</size>", GameUI.ButtonAccent))
Buy(false);
if (GameUI.Btn(new Rect(r.x + 380, by, 400, 62), $"КУПИТЬ + ЭВАКУАТОР В ГАРАЖ\n<size=15>+{GameUI.Money(towTruckPrice)}{(drivable ? "" : " — машина не на ходу!")}</size>"))
Buy(true);
if (GameUI.Btn(new Rect(r.xMax - 300, by, 270, 62), "ОТКАЗАТЬСЯ", GameUI.ButtonDanger))
Close();
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0bbee6839f740db4f9a0b092f17a55e4
+159
View File
@@ -0,0 +1,159 @@
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class UIManager : MonoBehaviour
{
[Header("UI Elements")]
[SerializeField] private TextMeshProUGUI interactText;
[SerializeField] private TextMeshProUGUI speedText;
[Header("Смещение подсказки от центрального прицела")]
[Tooltip("На сколько пикселей ниже точки прицела располагается текст подсказки")]
[SerializeField] private Vector2 promptOffsetFromCenter = new Vector2(0f, -120f);
[Header("Прицел (Точка по центру экрана)")]
[SerializeField] private Image crosshairDot;
[SerializeField] private Color normalDotColor = new Color(1f, 1f, 1f, 0.8f);
[SerializeField] private Color activeDotColor = new Color(0.2f, 1f, 0.35f, 1f);
[SerializeField] private float normalDotSize = 6f;
[SerializeField] private float activeDotSize = 10f;
private RectTransform dotRect;
// Резервный интерфейс OnGUI: работает, даже если в Инспекторе не назначены тексты
private string fallbackPrompt;
private bool fallbackPromptVisible;
private bool dashboardActive;
private float fallbackSpeed;
private void Awake()
{
EnsureCrosshairExists();
PositionPromptBelowCrosshair();
}
private void Start()
{
HidePrompt();
ToggleDashboard(false);
}
private void PositionPromptBelowCrosshair()
{
if (interactText == null) return;
RectTransform rt = interactText.rectTransform;
rt.anchorMin = new Vector2(0.5f, 0.5f);
rt.anchorMax = new Vector2(0.5f, 0.5f);
rt.pivot = new Vector2(0.5f, 0.5f);
rt.anchoredPosition = promptOffsetFromCenter;
rt.sizeDelta = new Vector2(Mathf.Max(rt.sizeDelta.x, 1200f), Mathf.Max(rt.sizeDelta.y, 130f));
interactText.alignment = TextAlignmentOptions.Center;
interactText.raycastTarget = false;
}
private void EnsureCrosshairExists()
{
if (crosshairDot == null)
{
Canvas canvas = GetComponentInChildren<Canvas>() ?? FindAnyObjectByType<Canvas>();
if (canvas != null)
{
GameObject dotObj = new GameObject("CrosshairDot");
dotObj.transform.SetParent(canvas.transform, false);
crosshairDot = dotObj.AddComponent<Image>();
crosshairDot.raycastTarget = false;
int res = 32;
Texture2D tex = new Texture2D(res, res, TextureFormat.RGBA32, false);
Vector2 center = new Vector2(res * 0.5f, res * 0.5f);
for (int y = 0; y < res; y++)
{
for (int x = 0; x < res; x++)
{
float dist = Vector2.Distance(new Vector2(x, y), center);
float alpha = Mathf.Clamp01((res * 0.45f - dist) * 0.8f);
tex.SetPixel(x, y, new Color(1f, 1f, 1f, alpha));
}
}
tex.Apply();
crosshairDot.sprite = Sprite.Create(tex, new Rect(0, 0, res, res), new Vector2(0.5f, 0.5f));
}
}
if (crosshairDot != null)
{
dotRect = crosshairDot.GetComponent<RectTransform>();
dotRect.anchorMin = new Vector2(0.5f, 0.5f);
dotRect.anchorMax = new Vector2(0.5f, 0.5f);
dotRect.pivot = new Vector2(0.5f, 0.5f);
dotRect.anchoredPosition = Vector2.zero;
SetCrosshairHighlight(false);
}
}
public void SetCrosshairHighlight(bool isHighlighted)
{
if (crosshairDot == null || dotRect == null) return;
crosshairDot.color = isHighlighted ? activeDotColor : normalDotColor;
float s = isHighlighted ? activeDotSize : normalDotSize;
dotRect.sizeDelta = new Vector2(s, s);
}
public void ToggleDashboard(bool isActive)
{
dashboardActive = isActive;
if (speedText != null)
speedText.gameObject.SetActive(isActive);
if (crosshairDot != null)
crosshairDot.gameObject.SetActive(!isActive);
}
public void UpdateSpeed(float currentSpeed)
{
fallbackSpeed = currentSpeed;
if (speedText != null)
speedText.text = $"{currentSpeed:F0} км/ч";
}
public void ShowPrompt(string message)
{
fallbackPrompt = message;
fallbackPromptVisible = true;
if (interactText != null)
{
interactText.text = message;
interactText.gameObject.SetActive(true);
}
SetCrosshairHighlight(true);
}
public void HidePrompt()
{
fallbackPromptVisible = false;
if (interactText != null)
interactText.gameObject.SetActive(false);
SetCrosshairHighlight(false);
}
private void OnGUI()
{
if (interactText != null && (speedText != null || !dashboardActive) && crosshairDot != null) return;
GameUI.Begin(5);
float cx = GameUI.VirtualWidth * 0.5f;
float cy = GameUI.VirtualHeight * 0.5f;
if (crosshairDot == null && !dashboardActive)
GameUI.DrawRect(new Rect(cx - 3, cy - 3, 6, 6), fallbackPromptVisible ? activeDotColor : normalDotColor);
if (interactText == null && fallbackPromptVisible && !string.IsNullOrEmpty(fallbackPrompt))
{
Rect r = new Rect(cx - 450, cy - promptOffsetFromCenter.y - 30, 900, 90);
GUI.Label(r, fallbackPrompt, GameUI.LabelCenter);
}
if (speedText == null && dashboardActive)
GUI.Label(new Rect(GameUI.VirtualWidth - 260, GameUI.VirtualHeight - 80, 240, 60), $"{fallbackSpeed:F0} км/ч", GameUI.Header);
}
}
+3
View File
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2942b1ecd944412c924c1cb70b3a2902
timeCreated: 1789844366
+39
View File
@@ -0,0 +1,39 @@
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Подпись над объектом в мире (полка с канистрами, ноутбук, домкрат, мойка, площадка продажи).
/// Показывается GuideSystem, когда игрок рядом: что это и какой клавишей пользоваться.
/// </summary>
public class WorldLabel : MonoBehaviour
{
public static readonly List<WorldLabel> All = new List<WorldLabel>();
[TextArea] public string title = "Объект";
[TextArea] public string hint = "";
public Vector3 offset = new Vector3(0f, 1.2f, 0f);
public float showDistance = 9f;
[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);
public Vector3 WorldPoint => transform.position + offset;
public static WorldLabel Add(GameObject go, string title, string hint, Vector3 offset, float distance = 9f)
{
WorldLabel l = go.GetComponent<WorldLabel>();
if (l == null) l = go.AddComponent<WorldLabel>();
l.title = title;
l.hint = hint;
l.offset = offset;
l.showDistance = distance;
return l;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9de524ea97b047b418d6cd98d5ee986f