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

+192
View File
@@ -0,0 +1,192 @@
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Осмотр автомобиля: список дефектов для торга с продавцом и чек-лист состояния для продажи.
/// Скрытые дефекты (под капотом, ошибки ДВС, перекрас) видны только после проверки игроком.
/// </summary>
public static class CarInspection
{
public class Defect
{
public string text;
public float discountPercent;
public bool revealed;
public string howToReveal;
}
public static List<Defect> CollectDefects(CarOwnership car)
{
List<Defect> list = new List<Defect>();
if (car == null) return list;
Transform root = car.transform;
// --- Видно сразу ---
float dirt = 0f;
int dirtN = 0;
int rusted = 0;
foreach (CarPartVisuals v in root.GetComponentsInChildren<CarPartVisuals>())
{
if (!v.HasPaintSlots) continue;
dirt += v.DirtAmount;
dirtN++;
if (v.Stage == RepairStage.Rusted) rusted++;
}
if (dirtN > 0 && dirt / dirtN > 0.3f)
list.Add(new Defect { text = "Кузов сильно загрязнен — не видно реального состояния ЛКП", discountPercent = 2f, revealed = true });
if (rusted > 0)
list.Add(new Defect { text = $"Ржавчина на кузове: {rusted} очаг(а)", discountPercent = Mathf.Min(8f, 2f + rusted * 1.5f), revealed = true });
int missing = 0;
foreach (CarPartMountZone z in root.GetComponentsInChildren<CarPartMountZone>(true))
{
if (z.TargetPart != null && z.TargetPart.GetComponent<EnginePart>() != null) continue;
if (z.TargetPart != null && z.TargetPart.IsWheel) continue;
missing++;
}
if (missing > 0)
list.Add(new Defect { text = $"Некомплект: нет {missing} кузовн. детал(и)", discountPercent = Mathf.Min(9f, 3f * missing), revealed = true });
int flat = 0, wheelsMissing = 0;
foreach (CarWheelCondition w in root.GetComponentsInChildren<CarWheelCondition>(true))
{
CarPart p = w.GetComponent<CarPart>();
if (p != null && (!p.gameObject.activeInHierarchy || p.State != PartState.Installed)) wheelsMissing++;
else if (w.IsFlat) flat++;
}
if (wheelsMissing > 0)
list.Add(new Defect { text = "Стоит на кирпичах — нет колеса", discountPercent = 5f, revealed = true });
if (flat > 0)
list.Add(new Defect { text = $"Спущено колес: {flat}", discountPercent = 2f * flat, revealed = true });
// --- Под капотом (нужно открыть капот) ---
CarFluids fluids = root.GetComponent<CarFluids>();
if (fluids != null)
{
if (fluids.EngineOil.FillPercent < 0.5f || fluids.EngineOil.quality < 0.3f)
list.Add(new Defect { text = "Старое черное масло / низкий уровень", discountPercent = 3f, revealed = car.hoodInspected, howToReveal = "откройте капот / проверьте щуп" });
if (fluids.Coolant.FillPercent < 0.5f)
list.Add(new Defect { text = "Низкий уровень антифриза", discountPercent = 2f, revealed = car.hoodInspected, howToReveal = "откройте капот" });
if (fluids.BrakeFluid.FillPercent < 0.3f)
list.Add(new Defect { text = "Тормозная жидкость ниже минимума", discountPercent = 2f, revealed = car.hoodInspected, howToReveal = "откройте капот" });
}
EngineBayManager bay = root.GetComponent<EngineBayManager>();
if (bay != null)
{
if (bay.GetPart(EnginePartType.Battery) == null)
list.Add(new Defect { text = "Нет аккумулятора", discountPercent = 4f, revealed = car.hoodInspected, howToReveal = "откройте капот" });
// --- Ошибки двигателя (нужен OBD-сканер) ---
foreach (string code in bay.GetObdCodes())
{
if (code.StartsWith("C1241")) continue;
list.Add(new Defect { text = "OBD: " + code, discountPercent = 3f, revealed = car.obdScanned, howToReveal = "OBD-сканер" });
}
}
// --- Скрытый перекрас (нужен толщиномер) ---
int repaint = 0;
foreach (CarPartVisuals v in root.GetComponentsInChildren<CarPartVisuals>())
if (v.HiddenRepaint && v.Stage == RepairStage.Healthy) repaint++;
if (repaint > 0)
list.Add(new Defect { text = $"Скрытый перекрас/шпаклёвка: {repaint} детал(и) (250–450 мкм)", discountPercent = 4f, revealed = car.hiddenRepaintFound, howToReveal = "толщиномер ЛКП" });
return list;
}
public class SaleReport
{
public bool washed, rustFixed, bodyComplete, wheelsOk, engineOk, fluidsOk;
public float score;
public float salePrice;
public float referencePrice;
public readonly List<string> issues = new List<string>();
}
/// <summary>Комплексная оценка автомобиля для перепродажи.</summary>
public static SaleReport EvaluateForSale(CarOwnership car)
{
SaleReport r = new SaleReport();
if (car == null) return r;
Transform root = car.transform;
bool diploma = GameEconomyManager.Instance == null || GameEconomyManager.Instance.DiplomaFeatures;
// 1. Мойка
float dirt = 0f;
int n = 0;
bool rustOk = true;
foreach (CarPartVisuals v in root.GetComponentsInChildren<CarPartVisuals>())
{
if (!v.HasPaintSlots) continue;
dirt += v.DirtAmount;
n++;
RepairStage s = v.Stage;
if (s != RepairStage.Healthy && s != RepairStage.Repaired) rustOk = false;
}
float avgDirt = n > 0 ? dirt / n : 0f;
r.washed = avgDirt <= 0.03f;
if (!r.washed) r.issues.Add($"Кузов не вымыт (грязь {Mathf.RoundToInt(avgDirt * 100f)}%)");
r.rustFixed = rustOk;
if (!rustOk) r.issues.Add("Ржавчина зачищена и покрашена не везде");
// 2. Комплектность кузова
int missing = 0;
foreach (CarPartMountZone z in root.GetComponentsInChildren<CarPartMountZone>(true))
{
if (z.TargetPart != null && (z.TargetPart.IsWheel || z.TargetPart.GetComponent<EnginePart>() != null)) continue;
missing++;
}
r.bodyComplete = missing == 0;
if (!r.bodyComplete) r.issues.Add($"Не установлено кузовных деталей: {missing}");
// 3. Колеса
int wheelsOk = 0, wheelsTotal = 0;
foreach (WheelCollider wc in root.GetComponentsInChildren<WheelCollider>(true))
{
wheelsTotal++;
bool ok = false;
foreach (CarPart p in root.GetComponentsInChildren<CarPart>(false))
{
if (p.LinkedWheelCollider != wc || p.State != PartState.Installed) continue;
CarWheelCondition cond = p.GetComponent<CarWheelCondition>();
bool flat = cond != null && cond.IsFlat;
bool bolted = p.TotalBoltsCount == 0 || p.TightenedBoltsCount >= p.TotalBoltsCount;
ok = !flat && bolted && wc.enabled;
break;
}
if (ok) wheelsOk++;
}
bool bricks = false;
foreach (WheelBrickSupport b in Object.FindObjectsByType<WheelBrickSupport>(FindObjectsSortMode.None))
if (Vector3.Distance(b.transform.position, root.position) < 4f) bricks = true;
r.wheelsOk = wheelsOk >= wheelsTotal && wheelsTotal > 0 && !bricks;
if (!r.wheelsOk) r.issues.Add($"Целых затянутых колес: {wheelsOk}/{wheelsTotal}{(bricks ? ", машина на кирпичах" : "")}");
// 4–5. Подкапотное пространство
EngineBayManager bay = root.GetComponent<EngineBayManager>();
if (diploma && bay != null)
{
r.engineOk = bay.IsReadyForSale(r.issues);
r.fluidsOk = bay.AreFluidsFresh(r.issues);
}
else
{
r.engineOk = true;
r.fluidsOk = true;
}
r.score = (r.washed ? 0.12f : 0f) + (r.rustFixed ? 0.25f : 0f) + (r.bodyComplete ? 0.18f : 0f)
+ (r.wheelsOk ? 0.15f : 0f) + (r.engineOk ? 0.18f : 0f) + (r.fluidsOk ? 0.12f : 0f);
// Цена: при полном восстановлении +45..75% от цены покупки, мойка +8%
float reference = car.purchasePrice > 1f ? car.purchasePrice : car.marketValue * 0.45f;
r.referencePrice = reference;
int seed = Mathf.Abs((car.carTitle + car.year + car.mileageKm).GetHashCode()) % 1000;
float fullBonus = Mathf.Lerp(0.45f, 0.75f, seed / 999f);
float mult = Mathf.Lerp(0.72f, 1f + fullBonus, r.score * r.score);
if (r.washed) mult *= 1.08f;
r.salePrice = Mathf.Round(reference * mult / 10f) * 10f;
return r;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0c87153c12db56942aa79566636f15f8
@@ -0,0 +1,358 @@
using System;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class CarCatalogItem
{
public string carTitle = "Ibishu Covet 1.5";
public GameObject carPrefab;
public float idealPrice = 4500f;
public int minYear = 1992;
public int maxYear = 2005;
public string bodyType = "Хэтчбек";
}
public class CarListing
{
public int id;
public CarCatalogItem catalogItem;
public int seed;
public Color bodyColor;
public string bodyColorName;
public int year;
public int mileageKm;
public int price;
public DriveType driveType;
public string sellerName;
public float sellerRating;
public string sellerPhone;
public string sellerDescription;
public CarDefectsSummary defectsSummary;
public Sprite photo;
public bool isMeetingArranged;
public GameObject spawnedInstance;
public Vector3 spawnPosition;
public bool isSold;
}
public class CarMarketManager : MonoBehaviour
{
[Header("Каталог префабов машин для продажи")]
[SerializeField] private CarCatalogItem[] carCatalog;
[Header("Точки спавна машин для встречи на карте")]
[SerializeField] private Transform[] meetingSpawnPoints;
[Header("Настройки генерации объявлений")]
[SerializeField] private int listingsCount = 6;
[SerializeField] private Color[] possibleBodyColors = new Color[]
{
new Color(0.12f, 0.32f, 0.75f), // Синий
new Color(0.75f, 0.15f, 0.15f), // Красный
new Color(0.85f, 0.85f, 0.88f), // Белый / Серебро
new Color(0.18f, 0.20f, 0.22f), // Темно-серый
new Color(0.15f, 0.48f, 0.25f), // Темно-зеленый
new Color(0.85f, 0.65f, 0.12f) // Желтый / Золотистый
};
private readonly string[] colorNames = new string[]
{
"Синий металлик", "Красный рубин", "Серебристый металлик", "Мокрый асфальт", "Изумрудный перламутр", "Золотистый металлик"
};
private readonly string[] sellerNames = new string[]
{
"Алексей Смирнов", "Сергей (Частник)", "Михаил Ремонт", "Дмитрий В.", "Виктор Авто", "Артем Романов", "Владимир", "Елена (муж попросил)"
};
[Header("Настройки ракурса фотостудии")]
[SerializeField] private Vector3 cameraOffset = new Vector3(-2.6f, 1.35f, 3.4f);
[SerializeField] private Vector3 lookAtOffset = new Vector3(0f, 0.45f, 0f);
[SerializeField] private int photoWidth = 640;
[SerializeField] private int photoHeight = 360;
public readonly List<CarListing> Listings = new List<CarListing>();
public CarListing ActiveMeetingListing { get; private set; }
public event Action<CarListing> OnMeetingArranged;
public event Action OnMeetingCleared;
public event Action OnListingsUpdated;
public CarCatalogItem[] Catalog => carCatalog;
/// <summary>Настройка рынка из Editor-автонастройки.</summary>
public void Configure(CarCatalogItem[] catalog, Transform[] spawnPoints)
{
carCatalog = catalog;
meetingSpawnPoints = spawnPoints;
}
private GameObject photoStudioRoot;
private Camera photoCamera;
private RenderTexture photoRT;
private int lastUsedSpawnPointIndex = -1;
private void Start()
{
EnsureListingsGenerated();
}
public void EnsureListingsGenerated()
{
if (Listings.Count == 0)
{
SetupPhotoStudio();
GenerateListings();
}
}
private void SetupPhotoStudio()
{
if (photoStudioRoot != null) return;
// Создаем изолированную студию глубоко под картой
photoStudioRoot = new GameObject("Offscreen_CarPhotoStudio");
photoStudioRoot.transform.position = new Vector3(0f, -500f, 0f);
// Подиум/асфальт для приятного фона на фотографиях
GameObject floor = GameObject.CreatePrimitive(PrimitiveType.Plane);
Destroy(floor.GetComponent<Collider>());
floor.transform.SetParent(photoStudioRoot.transform, false);
floor.transform.localScale = new Vector3(3f, 1f, 3f);
Renderer floorRend = floor.GetComponent<Renderer>();
Material floorMat = new Material(Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard"));
floorMat.color = new Color(0.22f, 0.24f, 0.27f);
floorRend.sharedMaterial = floorMat;
// Освещение студии
GameObject lightObj = new GameObject("StudioLight");
lightObj.transform.SetParent(photoStudioRoot.transform, false);
lightObj.transform.localPosition = new Vector3(-3f, 5f, 4f);
lightObj.transform.localRotation = Quaternion.Euler(45f, 135f, 0f);
Light studioLight = lightObj.AddComponent<Light>();
studioLight.type = LightType.Directional;
studioLight.intensity = 1.4f;
// Камера для рендера фото объявления
GameObject camObj = new GameObject("StudioCamera");
camObj.transform.SetParent(photoStudioRoot.transform, false);
photoCamera = camObj.AddComponent<Camera>();
photoCamera.clearFlags = CameraClearFlags.SolidColor;
photoCamera.backgroundColor = new Color(0.48f, 0.60f, 0.74f);
photoCamera.fieldOfView = 40f;
photoCamera.enabled = false; // Выключена, рендерит только по команде Render()
photoRT = new RenderTexture(photoWidth, photoHeight, 24, RenderTextureFormat.ARGB32);
photoCamera.targetTexture = photoRT;
}
[ContextMenu("Обновить объявления")]
public void GenerateListings()
{
if (carCatalog == null || carCatalog.Length == 0)
{
Debug.LogWarning("[CarMarketManager] Добавьте хотя бы один префаб машины в Car Catalog!");
return;
}
if (photoStudioRoot == null) SetupPhotoStudio();
Listings.Clear();
for (int i = 0; i < listingsCount; i++)
{
CarCatalogItem item = carCatalog[UnityEngine.Random.Range(0, carCatalog.Length)];
if (item.carPrefab == null) continue;
int seed = UnityEngine.Random.Range(10000, 999999);
int colorIndex = (possibleBodyColors.Length > 0) ? UnityEngine.Random.Range(0, possibleBodyColors.Length) : 0;
Color color = (possibleBodyColors.Length > 0) ? possibleBodyColors[colorIndex] : Color.blue;
string colorName = (colorIndex < colorNames.Length) ? colorNames[colorIndex] : "Заводской окрас";
int year = UnityEngine.Random.Range(item.minYear, item.maxYear + 1);
int mileage = (2026 - year) * UnityEngine.Random.Range(9500, 18000);
// 1. Временно спавним машину в фотостудии для точного снимка
GameObject tempCar = Instantiate(item.carPrefab, photoStudioRoot.transform.position, Quaternion.identity);
// Отключаем гравитацию в фотобоксе, чтобы машина не падала во время кадра
Rigidbody rb = tempCar.GetComponent<Rigidbody>();
if (rb != null) rb.isKinematic = true;
CarController ctrl = tempCar.GetComponent<CarController>();
DriveType drive = ctrl != null ? ctrl.driveType : DriveType.FWD;
CarConditionGenerator gen = tempCar.GetComponent<CarConditionGenerator>();
if (gen == null) gen = tempCar.AddComponent<CarConditionGenerator>();
// Применяем состояние по Seed (точно такое же применится при выезде на встречу!)
gen.ApplyConditionBySeed(seed, color, true, out CarDefectsSummary defects);
// 2. Выставляем камеру фотостудии в 3/4 спереди и делаем снимок
photoCamera.transform.position = tempCar.transform.position + cameraOffset;
photoCamera.transform.LookAt(tempCar.transform.position + lookAtOffset);
Sprite capturedPhoto = CaptureStudioPhoto();
// 3. Сразу удаляем временную машину, чтобы не нагружать сцену!
DestroyImmediate(tempCar);
// 4. Считаем итоговую цену и генерируем живое описание продавца
float rawPrice = item.idealPrice - defects.totalPricePenalty - (mileage / 10000f) * 65f;
int finalPrice = Mathf.RoundToInt(Mathf.Max(item.idealPrice * 0.25f, rawPrice) / 50f) * 50;
string sName = sellerNames[UnityEngine.Random.Range(0, sellerNames.Length)];
float sRating = Mathf.Round(UnityEngine.Random.Range(4.5f, 5.0f) * 10f) / 10f;
string sPhone = $"+375 ({(UnityEngine.Random.value < 0.5f ? 29 : 33)}) {UnityEngine.Random.Range(100, 999)}-{UnityEngine.Random.Range(10, 99)}-{UnityEngine.Random.Range(10, 99)}";
CarListing listing = new CarListing
{
id = i + 1,
catalogItem = item,
seed = seed,
bodyColor = color,
bodyColorName = colorName,
year = year,
mileageKm = mileage,
price = finalPrice,
driveType = drive,
sellerName = sName,
sellerRating = sRating,
sellerPhone = sPhone,
sellerDescription = BuildSellerDescription(defects, year, mileage),
defectsSummary = defects,
photo = capturedPhoto
};
Listings.Add(listing);
}
OnListingsUpdated?.Invoke();
}
private Sprite CaptureStudioPhoto()
{
RenderTexture prev = RenderTexture.active;
RenderTexture.active = photoRT;
photoCamera.Render();
Texture2D tex = new Texture2D(photoWidth, photoHeight, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect(0, 0, photoWidth, photoHeight), 0, 0);
tex.Apply();
RenderTexture.active = prev;
return Sprite.Create(tex, new Rect(0, 0, photoWidth, photoHeight), new Vector2(0.5f, 0.5f));
}
private string BuildSellerDescription(CarDefectsSummary d, int year, int mileage)
{
List<string> notes = new List<string>();
if (d.rustedPartsCount == 0 && d.missingBodyPartsCount == 0 && d.flatTiresCount == 0 && d.missingWheelsCount == 0 && d.lowFluidsCount == 0 && d.engineIssuesCount == 0)
{
return $"Отличное состояние для {year} года! Кузов без рыжиков, вся комплектная, родной пробег {mileage:N0} км. Сел и поехал, без вложений. Юридически чистая, торг минимальный.";
}
if (d.rustedPartsCount > 0)
notes.Add($"по кузову есть возрастные рыжики на кромках ({d.rustedPartsCount} эл.)");
if (d.missingBodyPartsCount > 0)
{
string missingList = string.Join(", ", d.missingPartNames);
notes.Add($"сняты некоторые детали ({missingList})");
}
if (d.lowFluidsCount > 0)
notes.Add("нужно долить технические жидкости под капотом");
if (d.startProblems)
notes.Add("иногда не заводится с первого раза (наверное, аккумулятор подсел)");
if (d.oilProblems)
notes.Add("масло давно не менял");
if (d.overheatProblems)
notes.Add("летом в пробках бывало грелся");
if (d.brakeProblems)
notes.Add("тормоза немного мягкие");
if (d.dirtAmount > 0.7f)
notes.Add("стояла под деревом, давно не мыта");
if (d.missingWheelsCount > 0)
notes.Add("стоит на кирпичах (нет одного колеса, приезжайте со своей запаской)");
else if (d.flatTiresCount > 0)
notes.Add($"спущено колесо ({d.flatTiresCount} шт.)");
string details = string.Join(", ", notes);
return $"Продаю как есть, под восстановление или перепродажу: {details}. Мотор и коробка живые, хороший торг у капота!";
}
/// <summary>
/// Вызывается при нажатии кнопки "Договориться о встрече" в приложении телефона.
/// Спавнит машину на карте с её точным состоянием и активирует GPS навигацию.
/// </summary>
public void ArrangeMeeting(CarListing listing)
{
if (listing == null || listing.catalogItem == null || listing.catalogItem.carPrefab == null)
return;
// Если машина из этого объявления уже заспавнена — просто активируем метку
if (listing.isMeetingArranged && listing.spawnedInstance != null)
{
ActiveMeetingListing = listing;
OnMeetingArranged?.Invoke(listing);
return;
}
Transform spawnPoint = GetNextMeetingSpawnPoint();
Vector3 pos = spawnPoint != null ? spawnPoint.position : (transform.position + transform.forward * 15f);
Quaternion rot = spawnPoint != null ? spawnPoint.rotation : Quaternion.identity;
GameObject carObj = Instantiate(listing.catalogItem.carPrefab, pos, rot);
carObj.name = $"MarketCar_{listing.catalogItem.carTitle}_{listing.id}";
CarConditionGenerator gen = carObj.GetComponent<CarConditionGenerator>();
if (gen == null) gen = carObj.AddComponent<CarConditionGenerator>();
// Применяем ТОТ ЖЕ САМЫЙ Seed, что был на фотографии в объявлении!
gen.ApplyConditionBySeed(listing.seed, listing.bodyColor, false, out _);
CarOwnership own = carObj.GetComponent<CarOwnership>();
if (own == null) own = carObj.AddComponent<CarOwnership>();
own.SetupFromListing(listing);
own.isOwned = false;
listing.isMeetingArranged = true;
listing.spawnedInstance = carObj;
listing.spawnPosition = pos;
ActiveMeetingListing = listing;
OnMeetingArranged?.Invoke(listing);
}
/// <summary>Машина куплена: объявление снимается с рынка.</summary>
public void MarkListingSold(CarListing listing)
{
if (listing == null) return;
listing.isSold = true;
Listings.Remove(listing);
if (ActiveMeetingListing == listing) ClearActiveMeeting();
OnListingsUpdated?.Invoke();
}
public void ClearActiveMeeting()
{
if (ActiveMeetingListing != null)
{
ActiveMeetingListing = null;
OnMeetingCleared?.Invoke();
}
}
private Transform GetNextMeetingSpawnPoint()
{
if (meetingSpawnPoints == null || meetingSpawnPoints.Length == 0) return null;
lastUsedSpawnPointIndex = (lastUsedSpawnPointIndex + 1) % meetingSpawnPoints.Length;
return meetingSpawnPoints[lastUsedSpawnPointIndex];
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: dc01e717989741cca3b70672b43d4fe1
timeCreated: 1792711755
+104
View File
@@ -0,0 +1,104 @@
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Сведения о сделке по конкретной машине: объявление, цена покупки, затраты на ремонт
/// и что игрок уже проверил при осмотре (капот, OBD-сканер, толщиномер).
/// </summary>
[DisallowMultipleComponent]
public class CarOwnership : MonoBehaviour
{
public static readonly List<CarOwnership> All = new List<CarOwnership>();
[Header("Объявление")]
public string carTitle = "Автомобиль";
public int year = 2001;
public int mileageKm = 180000;
public float askingPrice = 2500f;
[Tooltip("Цена идеального экземпляра на рынке")]
public float marketValue = 4500f;
public string sellerName = "Продавец";
[Header("Сделка")]
public bool isOwned;
public bool isStarterCar;
public float purchasePrice;
public float expenses;
public readonly List<string> expenseLog = new List<string>();
[Header("Осмотр перед покупкой")]
public bool hoodInspected;
public bool obdScanned;
public bool thicknessChecked;
public bool hiddenRepaintFound;
public CarListing Listing { get; set; }
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
private static void ResetStatics() => All.Clear();
private void OnEnable()
{
if (!All.Contains(this)) All.Add(this);
}
private void OnDisable()
{
All.Remove(this);
}
private void Update()
{
if (hoodInspected || isOwned) return;
foreach (CarPartAnimator anim in GetComponentsInChildren<CarPartAnimator>())
{
if (anim.IsOpen && anim.name.ToLowerInvariant().Contains("hood"))
{
hoodInspected = true;
GameHUD.Notify("Вы осмотрели подкапотное пространство: уровни жидкостей и АКБ видны", GameUI.Blue);
break;
}
}
}
public void AddExpense(float usd, string reason)
{
expenses += usd;
expenseLog.Add($"{reason}: ${usd:N0}");
}
public void SetupFromListing(CarListing listing)
{
Listing = listing;
if (listing == null) return;
carTitle = listing.catalogItem != null ? listing.catalogItem.carTitle : carTitle;
year = listing.year;
mileageKm = listing.mileageKm;
askingPrice = listing.price;
marketValue = listing.catalogItem != null ? listing.catalogItem.idealPrice : askingPrice * 1.6f;
sellerName = listing.sellerName;
}
public static CarOwnership Get(GameObject anyChild)
{
if (anyChild == null) return null;
return anyChild.GetComponentInParent<CarOwnership>();
}
public static CarOwnership FindNearestNotOwned(Vector3 pos, float maxDist)
{
CarOwnership best = null;
float bestD = maxDist;
foreach (CarOwnership c in All)
{
if (c == null || c.isOwned) continue;
float d = Vector3.Distance(pos, c.transform.position);
if (d < bestD)
{
bestD = d;
best = c;
}
}
return best;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 008312534ed74fa4db6a0bf29f621652
+214
View File
@@ -0,0 +1,214 @@
using UnityEngine;
/// <summary>
/// Площадка оценки и перепродажи восстановленного авто перед гаражом.
/// Чек-лист: мойка, ржавчина, комплектность, 4 целых затянутых колеса, агрегаты > 80%, жидкости > 85%.
/// После продажи выводится финансовый отчет сделки (покупка, затраты, продажа, чистая прибыль).
/// </summary>
[RequireComponent(typeof(BoxCollider))]
public class CarSellZone : MonoBehaviour
{
[SerializeField] private KeyCode sellKeyInCar = KeyCode.Return;
[SerializeField] private KeyCode sellKeyOnFoot = KeyCode.B;
private enum View { None, Evaluation, Report }
private View view = View.None;
private CarOwnership car;
private CarInspection.SaleReport report;
private float soldPrice, soldPurchase, soldExpenses;
private string soldTitle;
private BoxCollider zone;
private Transform player;
private void Awake()
{
zone = GetComponent<BoxCollider>();
zone.isTrigger = true;
gameObject.layer = 2; // Ignore Raycast — не мешает лучу игрока
}
private bool Contains(Vector3 worldPos)
{
Vector3 local = transform.InverseTransformPoint(worldPos) - zone.center;
Vector3 half = zone.size * 0.5f;
return Mathf.Abs(local.x) <= half.x && Mathf.Abs(local.z) <= half.z && local.y > -2f && local.y < 4f;
}
private CarOwnership FindOwnedCarInZone()
{
foreach (CarOwnership c in CarOwnership.All)
if (c != null && c.isOwned && Contains(c.transform.position)) return c;
return null;
}
private void Update()
{
if (view != View.None)
{
if (Input.GetKeyDown(KeyCode.Escape)) Close();
return;
}
if (GameInputLock.IsLocked) return;
MainMenuAndBootManager menu = MainMenuAndBootManager.Instance;
if (menu != null && !menu.IsPlaying) return;
VehicleInteraction current = VehicleInteraction.Current;
if (current != null)
{
CarOwnership own = current.GetComponent<CarOwnership>();
if (own == null || !own.isOwned || !Contains(current.transform.position)) return;
GameHUD.SetContextHint("Площадка продажи: остановитесь и нажмите [Enter] — выставить автомобиль на продажу");
if (Input.GetKeyDown(sellKeyInCar) || Input.GetKeyDown(KeyCode.KeypadEnter))
{
if (current.Controller != null && current.Controller.SpeedKmH > 4f)
GameHUD.Notify("Остановите машину на площадке", GameUI.Accent);
else
Open(own);
}
return;
}
if (player == null)
{
PlayerMovement pm = FindAnyObjectByType<PlayerMovement>();
if (pm != null) player = pm.transform;
}
if (player == null || !player.gameObject.activeInHierarchy || !Contains(player.position)) return;
CarOwnership inZone = FindOwnedCarInZone();
if (inZone == null) return;
GameHUD.SetContextHint($"Площадка продажи: [B] Выставить {inZone.carTitle} на продажу");
if (Input.GetKeyDown(sellKeyOnFoot)) Open(inZone);
}
private void Open(CarOwnership c)
{
car = c;
report = CarInspection.EvaluateForSale(c);
view = View.Evaluation;
GameInputLock.Lock(this);
ProceduralAudioManager.Instance?.Play(SfxId.Notification);
}
private void Close()
{
view = View.None;
car = null;
GameInputLock.Unlock(this);
}
private void Sell()
{
if (car == null || report == null) return;
soldTitle = car.carTitle;
soldPrice = report.salePrice;
soldPurchase = car.purchasePrice;
soldExpenses = car.expenses;
float profit = soldPrice - soldPurchase - soldExpenses;
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco != null)
{
eco.Earn(soldPrice, $"Продажа {soldTitle}");
eco.RegisterDeal(profit);
}
VehicleInteraction vi = car.GetComponent<VehicleInteraction>();
if (vi != null && vi.isPlayerInside) vi.ExitVehicle();
foreach (WheelBrickSupport b in FindObjectsByType<WheelBrickSupport>(FindObjectsSortMode.None))
if (Vector3.Distance(b.transform.position, car.transform.position) < 4f) Destroy(b.gameObject);
Destroy(car.gameObject);
car = null;
view = View.Report;
}
private void OnGUI()
{
if (view == View.None) return;
GameUI.Begin(-10);
float w = GameUI.VirtualWidth;
float h = GameUI.VirtualHeight;
GameUI.DrawRect(new Rect(0, 0, w, h), GameUI.Bg.WithAlpha(0.55f));
if (view == View.Evaluation && car != null && report != null) DrawEvaluation(w, h);
else if (view == View.Report) DrawReport(w, h);
else Close();
}
private void DrawEvaluation(float w, float h)
{
Rect r = new Rect(w * 0.5f - 560, h * 0.5f - 420, 1120, 840);
GUI.Box(r, GUIContent.none, GameUI.PanelSolid);
GUI.Label(new Rect(r.x + 30, r.y + 18, r.width - 60, 44), $"ОЦЕНКА АВТОМОБИЛЯ: {car.carTitle}", GameUI.Header);
float y = r.y + 80;
Line(r, ref y, report.washed, "Кузов вымыт (бонус +8% к цене)");
Line(r, ref y, report.rustFixed, "Ржавчина зачищена и покрашена");
Line(r, ref y, report.bodyComplete, "Все кузовные детали установлены");
Line(r, ref y, report.wheelsOk, "4 целых колеса установлены и прикручены");
Line(r, ref y, report.engineOk, "Подкапотные агрегаты исправны (> 80%)");
Line(r, ref y, report.fluidsOk, "Свежие технические жидкости (> 85%)");
y += 10;
GUI.Label(new Rect(r.x + 40, y, r.width - 80, 30), $"Готовность к продаже: <b>{Mathf.RoundToInt(report.score * 100f)}%</b>", GameUI.Label);
y += 36;
GameUI.ProgressBar(new Rect(r.x + 40, y, r.width - 80, 22), report.score, report.score > 0.95f ? GameUI.Green : GameUI.Accent);
y += 40;
if (report.issues.Count > 0)
{
string issues = string.Join("\n", report.issues.GetRange(0, Mathf.Min(7, report.issues.Count)));
GUI.Label(new Rect(r.x + 40, y, r.width - 80, 200), "<color=#F2A93B>Замечания покупателя:</color>\n" + issues, GameUI.Small);
}
float expenses = car.expenses;
string purchase = car.isStarterCar ? "проектная машина (без затрат на покупку)" : GameUI.Money(car.purchasePrice);
GUI.Label(new Rect(r.x + 40, r.yMax - 190, r.width - 80, 90),
$"Цена покупки: {purchase}\nЗатраты на запчасти и жидкости: {GameUI.Money(expenses)}\n" +
$"Предложение покупателя: <b><color=#4CD07D>{GameUI.Money(report.salePrice)}</color></b>", GameUI.Label);
if (GameUI.Btn(new Rect(r.x + 40, r.yMax - 86, 460, 62), $"ПРОДАТЬ ЗА {GameUI.Money(report.salePrice).Split(' ')[0]}", GameUI.ButtonAccent))
Sell();
if (GameUI.Btn(new Rect(r.xMax - 330, r.yMax - 86, 290, 62), "ДОРАБОТАТЬ МАШИНУ"))
Close();
}
private static void Line(Rect r, ref float y, bool ok, string text)
{
GUI.Label(new Rect(r.x + 40, y, r.width - 80, 34), $"{GameUI.Check(ok)} {text} {(ok ? "<color=#4CD07D>да</color>" : "<color=#E5534B>нет</color>")}", GameUI.Label);
y += 40;
}
private void DrawReport(float w, float h)
{
Rect r = new Rect(w * 0.5f - 460, h * 0.5f - 300, 920, 600);
GUI.Box(r, GUIContent.none, GameUI.PanelSolid);
GUI.Label(new Rect(r.x, r.y + 24, r.width, 56), "ФИНАНСОВЫЙ ОТЧЕТ СДЕЛКИ", GameUI.Title);
GUI.Label(new Rect(r.x, r.y + 84, r.width, 30), soldTitle, GameUI.SmallCenter);
float profit = soldPrice - soldPurchase - soldExpenses;
GUIStyle row = new GUIStyle(GameUI.Label) { fontSize = 24 };
GUIStyle val = new GUIStyle(row) { alignment = TextAnchor.UpperRight };
string[] labels = { "Цена покупки:", "Затраты на запчасти и жидкости:", "Цена продажи:" };
float[] values = { soldPurchase, soldExpenses, soldPrice };
for (int i = 0; i < 3; i++)
{
GUI.Label(new Rect(r.x + 80, r.y + 150 + i * 44, 460, 40), labels[i], row);
GUI.Label(new Rect(r.x + 480, r.y + 150 + i * 44, r.width - 560, 40), GameUI.Money(values[i]), val);
}
GameUI.DrawRect(new Rect(r.x + 80, r.y + 290, r.width - 160, 2), GameUI.Hex("3A3F4A"));
GUI.Label(new Rect(r.x + 80, r.y + 306, 460, 44), "<b>Чистая прибыль:</b>", row);
GUI.Label(new Rect(r.x + 480, r.y + 306, r.width - 560, 44), $"<b><color={(profit >= 0 ? "#4CD07D" : "#E5534B")}>{GameUI.Money(profit)}</color></b>", val);
GameEconomyManager eco = GameEconomyManager.Instance;
if (eco != null && !eco.Unlimited)
GUI.Label(new Rect(r.x + 80, r.y + 420, r.width - 160, 40), $"На счету: {eco.FormatMoney(eco.Money)} • До Автосалона: {eco.FormatShort(Mathf.Max(0f, eco.AutosalonGoal - eco.Money))}", GameUI.Small);
if (GameUI.Btn(new Rect(r.x + r.width * 0.5f - 180, r.yMax - 90, 360, 60), "ОТЛИЧНО!", GameUI.ButtonAccent))
Close();
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6c46266bf79245642b9ae030b4c68645