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 class CarListing { public int id; public CarCatalogItem catalogItem; public int seed; public Color bodyColor; public int year; public int mileageKm; public int price; public DriveType driveType; public string sellerDescription; public Sprite photo; public bool isMeetingArranged; public GameObject spawnedInstance; } 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) // Желтый / Золотистый }; [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 Listings = new List(); public CarListing ActiveMeetingListing { get; private set; } private GameObject photoStudioRoot; private Camera photoCamera; private RenderTexture photoRT; private int lastUsedSpawnPointIndex = -1; private GUIStyle waypointStyle; private Camera mainCam; private void Start() { SetupPhotoStudio(); GenerateListings(); } private void SetupPhotoStudio() { // Создаем изолированную студию глубоко под картой photoStudioRoot = new GameObject("Offscreen_CarPhotoStudio"); photoStudioRoot.transform.position = new Vector3(0f, -500f, 0f); // Подиум/асфальт для приятного фона на фотографиях GameObject floor = GameObject.CreatePrimitive(PrimitiveType.Plane); Destroy(floor.GetComponent()); floor.transform.SetParent(photoStudioRoot.transform, false); floor.transform.localScale = new Vector3(3f, 1f, 3f); Renderer floorRend = floor.GetComponent(); 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(); studioLight.type = LightType.Directional; studioLight.intensity = 1.4f; // Камера для рендера фото объявления GameObject camObj = new GameObject("StudioCamera"); camObj.transform.SetParent(photoStudioRoot.transform, false); photoCamera = camObj.AddComponent(); photoCamera.clearFlags = CameraClearFlags.SolidColor; photoCamera.backgroundColor = new Color(0.52f, 0.65f, 0.78f); 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); Color color = possibleBodyColors.Length > 0 ? possibleBodyColors[UnityEngine.Random.Range(0, possibleBodyColors.Length)] : Color.blue; 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(); if (rb != null) rb.isKinematic = true; CarController ctrl = tempCar.GetComponent(); DriveType drive = ctrl != null ? ctrl.driveType : DriveType.FWD; CarConditionGenerator gen = tempCar.GetComponent(); if (gen == null) gen = tempCar.AddComponent(); // Применяем состояние по 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; CarListing listing = new CarListing { id = i + 1, catalogItem = item, seed = seed, bodyColor = color, year = year, mileageKm = mileage, price = finalPrice, driveType = drive, sellerDescription = BuildSellerDescription(defects, year, mileage), photo = capturedPhoto }; Listings.Add(listing); } } 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 notes = new List(); if (d.rustedPartsCount == 0 && d.missingBodyPartsCount == 0 && d.flatTiresCount == 0 && d.missingWheelsCount == 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.missingWheelsCount > 0) notes.Add("стоит на кирпичах (нет одного колеса, приезжайте со своей запаской)"); else if (d.flatTiresCount > 0) notes.Add($"спущено колесо ({d.flatTiresCount} шт.)"); string details = string.Join(", ", notes); return $"Продаю как есть, под восстановление или перепродажу: {details}. Мотор и коробка живые, хороший торг у капота!"; } /// /// Вызывается при нажатии кнопки "Договориться о встрече" в UI. /// Спавнит машину на карте с её точным состоянием и ставит GPS-метку. /// public void ArrangeMeeting(CarListing listing) { if (listing == null || listing.catalogItem == null || listing.catalogItem.carPrefab == null) return; // Если машина из этого объявления уже заспавнена — просто фокусируем метку на ней if (listing.isMeetingArranged && listing.spawnedInstance != null) { ActiveMeetingListing = 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(); if (gen == null) gen = carObj.AddComponent(); // Применяем ТОТ ЖЕ САМЫЙ Seed, что был на фотографии! gen.ApplyConditionBySeed(listing.seed, listing.bodyColor, false, out _); listing.isMeetingArranged = true; listing.spawnedInstance = carObj; ActiveMeetingListing = listing; } private Transform GetNextMeetingSpawnPoint() { if (meetingSpawnPoints == null || meetingSpawnPoints.Length == 0) return null; lastUsedSpawnPointIndex = (lastUsedSpawnPointIndex + 1) % meetingSpawnPoints.Length; return meetingSpawnPoints[lastUsedSpawnPointIndex]; } // ---------- Отрисовка 3D GPS-метки над машиной встречи ---------- private void OnGUI() { if (ActiveMeetingListing == null || ActiveMeetingListing.spawnedInstance == null) return; // Если игрок уже сел внутрь этой машины — выключаем метку встречи VehicleInteraction vi = ActiveMeetingListing.spawnedInstance.GetComponent(); if (vi != null && vi.isPlayerInside) { ActiveMeetingListing = null; return; } if (mainCam == null || !mainCam.gameObject.activeInHierarchy) mainCam = Camera.main ?? FindAnyObjectByType(); if (mainCam == null) return; Vector3 targetWorldPos = ActiveMeetingListing.spawnedInstance.transform.position + Vector3.up * 2.2f; float distance = Vector3.Distance(mainCam.transform.position, targetWorldPos); Vector3 screenPos = mainCam.WorldToScreenPoint(targetWorldPos); // Если машина за спиной камеры — прижимаем метку к краю экрана if (screenPos.z < 0) { screenPos.x = Screen.width - screenPos.x; screenPos.y = 40f; } screenPos.x = Mathf.Clamp(screenPos.x, 90f, Screen.width - 90f); screenPos.y = Mathf.Clamp(Screen.height - screenPos.y, 40f, Screen.height - 60f); if (waypointStyle == null) { waypointStyle = new GUIStyle(GUI.skin.box) { alignment = TextAnchor.MiddleCenter, fontSize = 15, fontStyle = FontStyle.Bold }; waypointStyle.normal.textColor = new Color(0.2f, 1f, 0.4f); } string label = $"▼ ВСТРЕЧА: {ActiveMeetingListing.catalogItem.carTitle}\n{distance:F0} м"; GUI.Box(new Rect(screenPos.x - 110f, screenPos.y - 25f, 220f, 45f), label, waypointStyle); } }