Система со сменой колес дорабавтываю. Есть задатки системы объявлений и встречи с продавцом
This commit is contained in:
1 parent
2ce853999d
commit
27ad7eac11
25 files changed
+37130
-34404
No files matched your search
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5df59613a0b544e3b32d32cf1c4ea973
|
||||
timeCreated: 1792711737
|
||||
@@ -0,0 +1,314 @@
|
||||
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<CarListing> Listings = new List<CarListing>();
|
||||
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<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.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<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;
|
||||
|
||||
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<string> notes = new List<string>();
|
||||
|
||||
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}. Мотор и коробка живые, хороший торг у капота!";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вызывается при нажатии кнопки "Договориться о встрече" в UI.
|
||||
/// Спавнит машину на карте с её точным состоянием и ставит 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;
|
||||
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 _);
|
||||
|
||||
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<VehicleInteraction>();
|
||||
if (vi != null && vi.isPlayerInside)
|
||||
{
|
||||
ActiveMeetingListing = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (mainCam == null || !mainCam.gameObject.activeInHierarchy)
|
||||
mainCam = Camera.main ?? FindAnyObjectByType<Camera>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: dc01e717989741cca3b70672b43d4fe1
|
||||
timeCreated: 1792711755
|
||||
@@ -25,6 +25,9 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
|
||||
private Vector3 targetInHandLocalPos;
|
||||
private Quaternion targetInHandLocalRot;
|
||||
|
||||
// Родная сторона меша колеса (-1 = левое, +1 = правое)
|
||||
private float nativeWheelSideSign = 0f;
|
||||
|
||||
private Rigidbody rb;
|
||||
private Collider partCollider;
|
||||
private GameObject currentMountZone;
|
||||
@@ -38,6 +41,8 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
|
||||
public PartState State => currentState;
|
||||
public bool HasAnimator => partAnimator != null;
|
||||
public int TotalBoltsCount => wheelBolts != null ? wheelBolts.Length : 0;
|
||||
public WheelCollider LinkedWheelCollider => linkedWheelCollider;
|
||||
public WheelBrickSupport SpawnedBrickSupport { get; private set; }
|
||||
|
||||
public int TightenedBoltsCount
|
||||
{
|
||||
@@ -62,6 +67,9 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
|
||||
originalLocalRot = transform.localRotation;
|
||||
originalLocalScale = transform.localScale;
|
||||
|
||||
// Определяем родную сторону модели колеса по его имени или позиции
|
||||
DetectNativeWheelSide();
|
||||
|
||||
VehicleInteraction car = GetComponentInParent<VehicleInteraction>();
|
||||
if (car != null)
|
||||
{
|
||||
@@ -73,15 +81,68 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (linkedWheelCollider != null && partCollider != null)
|
||||
{
|
||||
if (partCollider is MeshCollider mc) mc.convex = true;
|
||||
partCollider.isTrigger = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
InitializeAsLoosePart();
|
||||
}
|
||||
}
|
||||
|
||||
private void DetectNativeWheelSide()
|
||||
{
|
||||
string n = gameObject.name.ToUpperInvariant();
|
||||
if (n.Contains("_FL") || n.Contains("_RL") || n.Contains("_L"))
|
||||
nativeWheelSideSign = -1f;
|
||||
else if (n.Contains("_FR") || n.Contains("_RR") || n.Contains("_R"))
|
||||
nativeWheelSideSign = 1f;
|
||||
else if (Mathf.Abs(originalLocalPos.x) > 0.1f)
|
||||
nativeWheelSideSign = Mathf.Sign(originalLocalPos.x);
|
||||
else
|
||||
nativeWheelSideSign = -1f;
|
||||
}
|
||||
|
||||
public void InitializeAsLoosePart()
|
||||
{
|
||||
currentState = PartState.Dropped;
|
||||
|
||||
if (wheelBolts != null)
|
||||
{
|
||||
foreach (var b in wheelBolts)
|
||||
{
|
||||
if (b == null) continue;
|
||||
b.SetTightenedImmediate(false);
|
||||
Collider bc = b.GetComponent<Collider>();
|
||||
if (bc != null) bc.enabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ВАЖНО: Если это колесо, на машине его MeshCollider ДОЛЖЕН быть триггером!
|
||||
// Иначе он трется об асфальт и крылья машины, мешая WheelCollider'у ехать!
|
||||
if (linkedWheelCollider != null && partCollider != null)
|
||||
if (partCollider != null)
|
||||
{
|
||||
if (partCollider is MeshCollider mc) mc.convex = true;
|
||||
partCollider.isTrigger = true;
|
||||
partCollider.isTrigger = false;
|
||||
partCollider.enabled = true;
|
||||
}
|
||||
|
||||
SetupDroppedRigidbody();
|
||||
}
|
||||
|
||||
private void SetupDroppedRigidbody()
|
||||
{
|
||||
if (rb == null) rb = GetComponent<Rigidbody>();
|
||||
if (rb == null) rb = gameObject.AddComponent<Rigidbody>();
|
||||
|
||||
rb.mass = mass;
|
||||
rb.interpolation = RigidbodyInterpolation.Interpolate;
|
||||
rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
|
||||
// Демпфирование полностью убирает мелкую дрожь колеса на асфальте
|
||||
rb.linearDamping = 1.2f;
|
||||
rb.angularDamping = 3.0f;
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
@@ -102,7 +163,7 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
|
||||
if (wheelBolts != null && wheelBolts.Length > 0)
|
||||
{
|
||||
if (!CarJack.IsWheelLifted(transform))
|
||||
return "Колесо под нагрузкой! Поднимите авто домкратом";
|
||||
return "Колесо под нагрузкой! Поднимите эту сторону домкратом";
|
||||
|
||||
if (TightenedBoltsCount > 0)
|
||||
return $"Сначала открутите болты ({TightenedBoltsCount}/{wheelBolts.Length})";
|
||||
@@ -190,6 +251,12 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
|
||||
if (rb != null) Destroy(rb);
|
||||
if (partCollider != null) partCollider.enabled = false;
|
||||
|
||||
if (wheelBolts != null)
|
||||
{
|
||||
foreach (var b in wheelBolts)
|
||||
if (b != null && b.TryGetComponent<Collider>(out var bc)) bc.enabled = false;
|
||||
}
|
||||
|
||||
if (linkedWheelCollider != null)
|
||||
linkedWheelCollider.enabled = false;
|
||||
|
||||
@@ -217,22 +284,27 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
|
||||
unboltProgress = 0f;
|
||||
|
||||
if (currentHoldPoint != null)
|
||||
transform.position = currentHoldPoint.position + currentHoldPoint.forward * 0.45f;
|
||||
transform.position = currentHoldPoint.position + currentHoldPoint.forward * 0.5f + Vector3.up * 0.1f;
|
||||
currentHoldPoint = null;
|
||||
|
||||
transform.SetParent(null);
|
||||
transform.localScale = originalLocalScale;
|
||||
|
||||
// Выключаем коллайдеры дочерних болтов, чтобы колесо на земле не дрожало!
|
||||
if (wheelBolts != null)
|
||||
{
|
||||
foreach (var b in wheelBolts)
|
||||
if (b != null && b.TryGetComponent<Collider>(out var bc)) bc.enabled = false;
|
||||
}
|
||||
|
||||
if (partCollider != null)
|
||||
{
|
||||
if (partCollider is MeshCollider meshCol) meshCol.convex = true;
|
||||
partCollider.isTrigger = false; // На земле деталь твердая
|
||||
partCollider.isTrigger = false;
|
||||
partCollider.enabled = true;
|
||||
}
|
||||
|
||||
rb = gameObject.AddComponent<Rigidbody>();
|
||||
rb.mass = mass;
|
||||
rb.interpolation = RigidbodyInterpolation.Interpolate;
|
||||
SetupDroppedRigidbody();
|
||||
|
||||
if (throwForce != Vector3.zero)
|
||||
rb.AddForce(throwForce, ForceMode.Impulse);
|
||||
@@ -254,17 +326,28 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
|
||||
if (partCollider != null)
|
||||
{
|
||||
partCollider.enabled = true;
|
||||
// Установленное колесо делаем триггером, чтобы оно не мешало физике езды!
|
||||
if (linkedWheelCollider != null)
|
||||
partCollider.isTrigger = true;
|
||||
}
|
||||
|
||||
// Сначала обновляем радиус WheelCollider (чтобы хорошее колесо вернуло полный радиус!), и только потом включаем его
|
||||
CarWheelCondition cond = GetComponent<CarWheelCondition>();
|
||||
if (cond != null) cond.UpdateWheelColliderPhysics();
|
||||
|
||||
if (linkedWheelCollider != null)
|
||||
{
|
||||
linkedWheelCollider.enabled = true;
|
||||
linkedWheelCollider.motorTorque = 0f;
|
||||
linkedWheelCollider.brakeTorque = 0f;
|
||||
}
|
||||
|
||||
if (wheelBolts != null)
|
||||
{
|
||||
foreach (var b in wheelBolts)
|
||||
{
|
||||
if (b != null) b.RecalculateOutwardDirection();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void CreateMountZone()
|
||||
@@ -280,4 +363,64 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
|
||||
CarPartMountZone zone = currentMountZone.AddComponent<CarPartMountZone>();
|
||||
zone.Initialize(this);
|
||||
}
|
||||
|
||||
public void MakeMissingAtStart(GameObject customBricksPrefab = null, bool enableBrickPhysics = true)
|
||||
{
|
||||
if (currentState != PartState.Installed) return;
|
||||
|
||||
CreateMountZone();
|
||||
|
||||
// Кирпичи ставим ТОЛЬКО если отсутствующая деталь — это колесо!
|
||||
if (linkedWheelCollider != null)
|
||||
{
|
||||
linkedWheelCollider.enabled = false;
|
||||
if (enableBrickPhysics)
|
||||
SpawnedBrickSupport = WheelBrickSupport.CreateUnderWheel(this, customBricksPrefab);
|
||||
}
|
||||
|
||||
currentState = PartState.Dropped;
|
||||
gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
public void InstallIntoZone(
|
||||
Transform newParent,
|
||||
Vector3 slotLocalPos,
|
||||
Quaternion slotLocalRot,
|
||||
Vector3 slotLocalScale,
|
||||
WheelCollider newWheelCol,
|
||||
string slotWheelName)
|
||||
{
|
||||
originalParent = newParent;
|
||||
originalLocalPos = slotLocalPos;
|
||||
originalLocalScale = slotLocalScale;
|
||||
linkedWheelCollider = newWheelCol;
|
||||
gameObject.name = slotWheelName;
|
||||
|
||||
// Определяем сторону ступицы, куда ставится колесо (-1 = левая, +1 = правая)
|
||||
float targetHubSideSign = slotLocalPos.x < 0f ? -1f : 1f;
|
||||
if (Mathf.Abs(slotLocalPos.x) < 0.05f && newWheelCol != null)
|
||||
targetHubSideSign = newWheelCol.transform.localPosition.x < 0f ? -1f : 1f;
|
||||
|
||||
// Разворачиваем на 180 градусов ТОЛЬКО если левую модель колеса ставят на правую сторону (или наоборот)
|
||||
bool needsFlip = (nativeWheelSideSign * targetHubSideSign) < 0f;
|
||||
originalLocalRot = needsFlip ? (slotLocalRot * Quaternion.Euler(0f, 180f, 0f)) : slotLocalRot;
|
||||
|
||||
Install();
|
||||
|
||||
if (wheelBolts != null)
|
||||
{
|
||||
foreach (var b in wheelBolts)
|
||||
{
|
||||
if (b == null) continue;
|
||||
b.SetTightenedImmediate(false);
|
||||
b.RecalculateOutwardDirection();
|
||||
}
|
||||
}
|
||||
|
||||
CarController controller = GetComponentInParent<CarController>();
|
||||
if (controller != null && linkedWheelCollider != null)
|
||||
{
|
||||
controller.ReplaceWheelMesh(linkedWheelCollider, transform);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,26 @@ public class CarPartMountZone : MonoBehaviour, IInteractable
|
||||
private Collider zoneCollider;
|
||||
private MeshRenderer ghostRenderer;
|
||||
private PlayerHands cachedHands;
|
||||
|
||||
private Transform slotParent;
|
||||
private Vector3 slotLocalPos;
|
||||
private Quaternion slotLocalRot;
|
||||
private Vector3 slotLocalScale;
|
||||
private WheelCollider slotWheelCollider;
|
||||
|
||||
private string slotName;
|
||||
private float mountDuration = 1.2f;
|
||||
private float currentMountProgress = 0f;
|
||||
private bool hasSeparateBolts = false;
|
||||
|
||||
public void Initialize(CarPart part)
|
||||
{
|
||||
slotParent = part.transform.parent;
|
||||
slotLocalPos = part.transform.localPosition;
|
||||
slotLocalRot = part.transform.localRotation;
|
||||
slotLocalScale = part.transform.localScale;
|
||||
slotWheelCollider = part.LinkedWheelCollider;
|
||||
slotName = part.gameObject.name;
|
||||
|
||||
targetPart = part;
|
||||
gameObject.layer = part.gameObject.layer;
|
||||
|
||||
@@ -96,7 +109,7 @@ public class CarPartMountZone : MonoBehaviour, IInteractable
|
||||
if (cachedHands == null)
|
||||
cachedHands = FindAnyObjectByType<PlayerHands>();
|
||||
|
||||
bool isHoldingTarget = cachedHands != null && cachedHands.IsHolding && cachedHands.CurrentPart == targetPart;
|
||||
bool isHoldingTarget = IsHoldingCompatiblePart();
|
||||
|
||||
if (zoneCollider != null && zoneCollider.enabled != isHoldingTarget)
|
||||
zoneCollider.enabled = isHoldingTarget;
|
||||
@@ -111,7 +124,7 @@ public class CarPartMountZone : MonoBehaviour, IInteractable
|
||||
public string GetPrompt()
|
||||
{
|
||||
if (targetPart == null) return string.Empty;
|
||||
if (cachedHands == null || !cachedHands.IsHolding || cachedHands.CurrentPart != targetPart)
|
||||
if (cachedHands == null || !IsHoldingCompatiblePart())
|
||||
return string.Empty;
|
||||
|
||||
string partTitle = targetPart.Data != null ? targetPart.Data.partName : "Деталь";
|
||||
@@ -149,7 +162,7 @@ public class CarPartMountZone : MonoBehaviour, IInteractable
|
||||
|
||||
public void Interact(GameObject interactor)
|
||||
{
|
||||
if (hasSeparateBolts && cachedHands != null && cachedHands.IsHolding && cachedHands.CurrentPart == targetPart)
|
||||
if (hasSeparateBolts && cachedHands != null && IsHoldingCompatiblePart())
|
||||
{
|
||||
CompleteInstall();
|
||||
}
|
||||
@@ -157,10 +170,35 @@ public class CarPartMountZone : MonoBehaviour, IInteractable
|
||||
|
||||
private void CompleteInstall()
|
||||
{
|
||||
if (cachedHands == null || targetPart == null) return;
|
||||
if (cachedHands == null || !IsHoldingCompatiblePart()) return;
|
||||
|
||||
CarPart partToInstall = cachedHands.CurrentPart;
|
||||
cachedHands.ClearHandAfterInstall();
|
||||
targetPart.Install();
|
||||
|
||||
partToInstall.InstallIntoZone(
|
||||
slotParent,
|
||||
slotLocalPos,
|
||||
slotLocalRot,
|
||||
slotLocalScale,
|
||||
slotWheelCollider,
|
||||
slotName
|
||||
);
|
||||
|
||||
Destroy(gameObject);
|
||||
}
|
||||
|
||||
private bool IsHoldingCompatiblePart()
|
||||
{
|
||||
if (cachedHands == null || !cachedHands.IsHolding || cachedHands.CurrentPart == null)
|
||||
return false;
|
||||
|
||||
CarPart held = cachedHands.CurrentPart;
|
||||
if (held == targetPart) return true;
|
||||
|
||||
// Разрешаем установить любое колесо-дубликат с тем же ScriptableObject CarPartData (например, "Wheel")
|
||||
if (hasSeparateBolts && held.Data != null && targetPart != null && held.Data == targetPart.Data)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -230,11 +230,26 @@ public class CarController : MonoBehaviour
|
||||
|
||||
private void UpdateWheelPose(WheelCollider collider, Transform mesh)
|
||||
{
|
||||
if (mesh == null || collider == null || !collider.enabled || !mesh.IsChildOf(transform))
|
||||
if (mesh == null || collider == null || !collider.enabled || !mesh.IsChildOf(transform))
|
||||
return;
|
||||
|
||||
collider.GetWorldPose(out Vector3 pos, out Quaternion rot);
|
||||
mesh.position = pos;
|
||||
mesh.rotation = rot;
|
||||
|
||||
// Если на эту ступицу поставили запасное колесо с противоположной стороны машины (развернутое на 180°),
|
||||
// сохраняем его разворот при вращении колеса!
|
||||
float angleDiff = Quaternion.Angle(mesh.localRotation, Quaternion.Euler(0f, 180f, 0f));
|
||||
if (angleDiff < 60f)
|
||||
mesh.rotation = rot * Quaternion.Euler(0f, 180f, 0f);
|
||||
else
|
||||
mesh.rotation = rot;
|
||||
}
|
||||
|
||||
public void ReplaceWheelMesh(WheelCollider col, Transform newMesh)
|
||||
{
|
||||
if (col == frontLeftCollider) frontLeftMesh = newMesh;
|
||||
else if (col == frontRightCollider) frontRightMesh = newMesh;
|
||||
else if (col == rearLeftCollider) rearLeftMesh = newMesh;
|
||||
else if (col == rearRightCollider) rearRightMesh = newMesh;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using UnityEngine;
|
||||
|
||||
[ExecuteInEditMode()]
|
||||
public class EasySuspension : MonoBehaviour
|
||||
{
|
||||
[Range(0, 20)] public float naturalFrequency = 10;
|
||||
[Range(0, 3)] public float dampingRatio = 0.8f;
|
||||
[Range(-1, 1)] public float forceShift = 0.03f;
|
||||
public bool setSuspensionDistance = true;
|
||||
|
||||
private float playModeTimer = 0f;
|
||||
|
||||
void Update()
|
||||
{
|
||||
// В режиме игры настраиваем подвеску только первые 0.25 сек при спавне авто.
|
||||
// Постоянный пересчет в каждом кадре вызывает вибрацию машины при спущенных шинах и на домкрате!
|
||||
if (Application.isPlaying)
|
||||
{
|
||||
if (playModeTimer > 0.25f) return;
|
||||
playModeTimer += Time.deltaTime;
|
||||
}
|
||||
|
||||
Rigidbody rb = GetComponent<Rigidbody>();
|
||||
if (rb == null) return;
|
||||
|
||||
foreach (WheelCollider wc in GetComponentsInChildren<WheelCollider>())
|
||||
{
|
||||
if (!wc.enabled || wc.sprungMass <= 0.001f) continue;
|
||||
|
||||
JointSpring spring = wc.suspensionSpring;
|
||||
spring.spring = Mathf.Pow(Mathf.Sqrt(wc.sprungMass) * naturalFrequency, 2);
|
||||
spring.damper = 2 * dampingRatio * Mathf.Sqrt(spring.spring * wc.sprungMass);
|
||||
wc.suspensionSpring = spring;
|
||||
|
||||
Vector3 wheelRelativeBody = transform.InverseTransformPoint(wc.transform.position);
|
||||
float distance = rb.centerOfMass.y - wheelRelativeBody.y + wc.radius;
|
||||
wc.forceAppPointDistance = distance - forceShift;
|
||||
|
||||
if (spring.targetPosition > 0 && spring.spring > 0.001f && setSuspensionDistance)
|
||||
wc.suspensionDistance = wc.sprungMass * Physics.gravity.magnitude / (spring.targetPosition * spring.spring);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7a530288782d44949a514cf418363121
|
||||
timeCreated: 1792619015
|
||||
@@ -69,15 +69,26 @@ public class CarJack : MonoBehaviour, IInteractable
|
||||
public static bool IsWheelLifted(Transform wheelTransform)
|
||||
{
|
||||
if (wheelTransform == null) return false;
|
||||
|
||||
// 1. Проверяем домкраты (дистанция строго < 0.95 м, чтобы левый домкрат не задевал правое колесо!)
|
||||
CarJack[] allJacks = FindObjectsByType<CarJack>(FindObjectsSortMode.None);
|
||||
foreach (CarJack jack in allJacks)
|
||||
{
|
||||
if (!jack.IsLifted) continue;
|
||||
if (jack.targetWheelPart != null && jack.targetWheelPart.transform == wheelTransform)
|
||||
return true;
|
||||
if (Vector3.Distance(jack.transform.position, wheelTransform.position) < 2.0f)
|
||||
if (Vector3.Distance(jack.transform.position, wheelTransform.position) < 0.95f)
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2. Проверяем кирпичи (тоже строго < 0.95 м)
|
||||
WheelBrickSupport[] allBricks = FindObjectsByType<WheelBrickSupport>(FindObjectsSortMode.None);
|
||||
foreach (var b in allBricks)
|
||||
{
|
||||
if (Vector3.Distance(b.transform.position, wheelTransform.position) < 0.95f)
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class CarWheelCondition : MonoBehaviour
|
||||
{
|
||||
public enum TireState
|
||||
{
|
||||
Normal, // Целое накачанное колесо
|
||||
Flat, // Спущено (нужно заменить)
|
||||
Missing // Колеса изначально нет на ступице
|
||||
}
|
||||
|
||||
// Хранит истинный начальный радиус каждого WheelCollider, чтобы новое колесо никогда не проваливалось
|
||||
private static readonly Dictionary<WheelCollider, float> trueOriginalRadii = new Dictionary<WheelCollider, float>();
|
||||
|
||||
[Header("Состояние колеса")]
|
||||
public TireState currentState = TireState.Normal;
|
||||
|
||||
[Header("Настройки деформации покрышки (Диск не затрагивается)")]
|
||||
[Range(0.4f, 0.8f)] [SerializeField] private float rimRadiusRatio = 0.62f;
|
||||
[Range(0.02f, 0.12f)] [SerializeField] private float flatSquashAmount = 0.055f;
|
||||
[Range(0f, 0.06f)] [SerializeField] private float sidewallBulge = 0.025f;
|
||||
|
||||
private CarPart carPart;
|
||||
private MeshFilter meshFilter;
|
||||
private Mesh runtimeMesh;
|
||||
private Vector3[] originalVertices;
|
||||
private Vector3[] deformedVertices;
|
||||
private float maxMeshRadius = 0.32f;
|
||||
private Vector3 meshCenter;
|
||||
private Quaternion lastDeformedRot;
|
||||
|
||||
public bool IsFlat => currentState == TireState.Flat;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
carPart = GetComponent<CarPart>();
|
||||
meshFilter = GetComponent<MeshFilter>();
|
||||
|
||||
// Кэшируем истинный радиус всех WheelCollider машины до любых изменений
|
||||
VehicleInteraction car = GetComponentInParent<VehicleInteraction>();
|
||||
if (car != null)
|
||||
{
|
||||
foreach (WheelCollider wc in car.GetComponentsInChildren<WheelCollider>(true))
|
||||
{
|
||||
if (!trueOriginalRadii.ContainsKey(wc))
|
||||
trueOriginalRadii[wc] = wc.radius;
|
||||
}
|
||||
}
|
||||
|
||||
if (meshFilter != null && meshFilter.sharedMesh != null && meshFilter.sharedMesh.isReadable)
|
||||
{
|
||||
runtimeMesh = Instantiate(meshFilter.sharedMesh);
|
||||
meshFilter.mesh = runtimeMesh;
|
||||
originalVertices = runtimeMesh.vertices;
|
||||
deformedVertices = new Vector3[originalVertices.Length];
|
||||
|
||||
Bounds b = runtimeMesh.bounds;
|
||||
meshCenter = b.center;
|
||||
maxMeshRadius = Mathf.Max(b.extents.y, b.extents.z);
|
||||
}
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
ApplyState(currentState);
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
// Обновляем вмятину покрышки только когда машина реально катится (чтобы не вызывать дрожь на месте)
|
||||
if (currentState == TireState.Flat && runtimeMesh != null && carPart != null && carPart.State == PartState.Installed)
|
||||
{
|
||||
if (Quaternion.Angle(transform.rotation, lastDeformedRot) > 8f)
|
||||
{
|
||||
DeformTireMesh();
|
||||
lastDeformedRot = transform.rotation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void ApplyState(TireState newState)
|
||||
{
|
||||
currentState = newState;
|
||||
if (carPart == null) carPart = GetComponent<CarPart>();
|
||||
|
||||
if (currentState == TireState.Missing)
|
||||
{
|
||||
if (carPart != null && carPart.State == PartState.Installed)
|
||||
carPart.MakeMissingAtStart();
|
||||
return;
|
||||
}
|
||||
|
||||
UpdateWheelColliderPhysics();
|
||||
|
||||
if (runtimeMesh != null)
|
||||
{
|
||||
if (currentState == TireState.Flat)
|
||||
{
|
||||
DeformTireMesh();
|
||||
lastDeformedRot = transform.rotation;
|
||||
}
|
||||
else
|
||||
{
|
||||
runtimeMesh.vertices = originalVertices;
|
||||
runtimeMesh.RecalculateBounds();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdateWheelColliderPhysics()
|
||||
{
|
||||
if (carPart == null) carPart = GetComponent<CarPart>();
|
||||
if (carPart == null) return;
|
||||
|
||||
WheelCollider wc = carPart.LinkedWheelCollider;
|
||||
if (wc == null) return;
|
||||
|
||||
if (!trueOriginalRadii.TryGetValue(wc, out float baseRadius))
|
||||
{
|
||||
baseRadius = wc.radius;
|
||||
trueOriginalRadii[wc] = baseRadius;
|
||||
}
|
||||
|
||||
if (currentState == TireState.Flat)
|
||||
{
|
||||
// Мягко занижаем радиус на 10% (без ударов днищем и без раскачки подвески)
|
||||
wc.radius = baseRadius * 0.90f;
|
||||
WheelFrictionCurve side = wc.sidewaysFriction;
|
||||
side.stiffness = 1.0f;
|
||||
wc.sidewaysFriction = side;
|
||||
}
|
||||
else
|
||||
{
|
||||
// ГАРАНТИРОВАННО возвращаем 100% заводской радиус при установке целого колеса!
|
||||
wc.radius = baseRadius;
|
||||
WheelFrictionCurve side = wc.sidewaysFriction;
|
||||
side.stiffness = 2.0f;
|
||||
wc.sidewaysFriction = side;
|
||||
}
|
||||
}
|
||||
|
||||
private void DeformTireMesh()
|
||||
{
|
||||
if (originalVertices == null) return;
|
||||
|
||||
float rimRadius = maxMeshRadius * rimRadiusRatio;
|
||||
Vector3 localDown = (carPart != null && carPart.State == PartState.Installed)
|
||||
? transform.InverseTransformDirection(Vector3.down).normalized
|
||||
: Vector3.down;
|
||||
|
||||
for (int i = 0; i < originalVertices.Length; i++)
|
||||
{
|
||||
Vector3 v = originalVertices[i];
|
||||
Vector3 fromCenter = v - meshCenter;
|
||||
float radialDist = Mathf.Sqrt(fromCenter.y * fromCenter.y + fromCenter.z * fromCenter.z);
|
||||
|
||||
if (radialDist <= rimRadius)
|
||||
{
|
||||
deformedVertices[i] = v;
|
||||
continue;
|
||||
}
|
||||
|
||||
float rubberFactor = Mathf.InverseLerp(rimRadius, maxMeshRadius, radialDist);
|
||||
Vector3 radialDir = new Vector3(0f, fromCenter.y, fromCenter.z).normalized;
|
||||
float bottomDot = Vector3.Dot(radialDir, localDown);
|
||||
|
||||
if (bottomDot > 0.30f)
|
||||
{
|
||||
float bottomFactor = Mathf.InverseLerp(0.30f, 1.0f, bottomDot);
|
||||
float squash = bottomFactor * rubberFactor * flatSquashAmount;
|
||||
|
||||
v -= localDown * squash;
|
||||
float sideSign = Mathf.Sign(fromCenter.x);
|
||||
v.x += sideSign * (bottomFactor * Mathf.Sin(rubberFactor * Mathf.PI) * sidewallBulge);
|
||||
}
|
||||
|
||||
deformedVertices[i] = v;
|
||||
}
|
||||
|
||||
runtimeMesh.vertices = deformedVertices;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9f5711453a0b43ad8d142a54264c4981
|
||||
timeCreated: 1792508527
|
||||
@@ -4,7 +4,7 @@ using UnityEngine;
|
||||
public class WheelBolt : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Header("Настройки вылета и скорости")]
|
||||
[SerializeField] private float pullOutDistance = 0.06f;
|
||||
[SerializeField] private float pullOutDistance = 0.05f;
|
||||
[SerializeField] private float workDuration = 0.5f;
|
||||
|
||||
private CarPart parentWheel;
|
||||
@@ -20,16 +20,23 @@ public class WheelBolt : MonoBehaviour, IInteractable
|
||||
|
||||
private Vector3 localMeshCenter;
|
||||
private Vector3 boltCenterInParent;
|
||||
private Vector3 parentOutwardDir;
|
||||
private Vector3 parentOutwardDir = Vector3.right;
|
||||
|
||||
private float tightness = 1f;
|
||||
private bool isTightened = true;
|
||||
private bool isHoveredThisFrame = false;
|
||||
private bool waitForRelease = false;
|
||||
|
||||
// Глобальная блокировка до отпускания кнопки, чтобы болт НИКОГДА не крутился туда-сюда по кругу
|
||||
private static bool waitForKeyRelease = false;
|
||||
|
||||
public bool IsTightened => isTightened;
|
||||
public bool IsAvailableForAim => parentWheel == null || parentWheel.State == PartState.Installed;
|
||||
public Vector3 WorldBoltCenter => transform.TransformPoint(localMeshCenter);
|
||||
|
||||
// ВАЖНО: Координата для прицела берется от неподвижного гнезда на ступице,
|
||||
// чтобы во время выдвижения болта он не выскакивал из-под прицела!
|
||||
public Vector3 WorldBoltCenter => transform.parent != null
|
||||
? transform.parent.TransformPoint(boltCenterInParent)
|
||||
: transform.TransformPoint(localMeshCenter);
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
@@ -48,21 +55,33 @@ public class WheelBolt : MonoBehaviour, IInteractable
|
||||
|
||||
boltCollider.isTrigger = true;
|
||||
boltCollider.center = localMeshCenter;
|
||||
boltCollider.radius = 0.045f;
|
||||
boltCollider.radius = 0.055f;
|
||||
|
||||
boltCenterInParent = tightenedLocalPos + tightenedLocalRot * Vector3.Scale(localMeshCenter, baseLocalScale);
|
||||
CalculateOutwardDirection();
|
||||
|
||||
if (meshRenderer != null)
|
||||
originalMaterial = meshRenderer.sharedMaterial;
|
||||
|
||||
if (parentWheel != null && parentWheel.Data != null)
|
||||
ghostMaterial = parentWheel.Data.ghostMaterial;
|
||||
|
||||
// Если в CarPartData забыли назначить Ghost Material — создаем запасной полупрозрачный материал
|
||||
if (ghostMaterial == null)
|
||||
{
|
||||
Shader sh = Shader.Find("Universal Render Pipeline/Unlit") ?? Shader.Find("Sprites/Default");
|
||||
if (sh != null)
|
||||
{
|
||||
ghostMaterial = new Material(sh);
|
||||
ghostMaterial.color = new Color(0.2f, 0.95f, 0.35f, 0.5f);
|
||||
}
|
||||
}
|
||||
|
||||
RecalculateOutwardDirection();
|
||||
}
|
||||
|
||||
private void CalculateOutwardDirection()
|
||||
public void RecalculateOutwardDirection()
|
||||
{
|
||||
Vector3 worldBoltPos = transform.TransformPoint(localMeshCenter);
|
||||
Vector3 worldBoltPos = WorldBoltCenter;
|
||||
VehicleInteraction car = GetComponentInParent<VehicleInteraction>();
|
||||
Transform carRoot = car != null ? car.transform : transform.root;
|
||||
|
||||
@@ -74,10 +93,32 @@ public class WheelBolt : MonoBehaviour, IInteractable
|
||||
parentOutwardDir = transform.parent != null
|
||||
? transform.parent.InverseTransformDirection(worldOutDir).normalized
|
||||
: Vector3.right * sideSign;
|
||||
|
||||
UpdateBoltTransform(1f);
|
||||
}
|
||||
|
||||
public void SetTightenedImmediate(bool state)
|
||||
{
|
||||
isTightened = state;
|
||||
tightness = state ? 1f : 0f;
|
||||
UpdateBoltTransform(1f);
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
// Снимаем блокировку сразу, как только игрок отпустил ЛКМ и клавишу E
|
||||
if (waitForKeyRelease && !Input.GetMouseButton(0) && !Input.GetKey(KeyCode.E))
|
||||
{
|
||||
waitForKeyRelease = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
if (parentWheel == null)
|
||||
parentWheel = GetComponentInParent<CarPart>();
|
||||
|
||||
// Пока колесо в руках или лежит на земле — болты полностью скрыты
|
||||
if (parentWheel != null && parentWheel.State != PartState.Installed)
|
||||
{
|
||||
if (meshRenderer != null && meshRenderer.enabled) meshRenderer.enabled = false;
|
||||
@@ -95,16 +136,23 @@ public class WheelBolt : MonoBehaviour, IInteractable
|
||||
bool hasWrench = toolManager != null && toolManager.currentTool == ToolType.Wrench;
|
||||
bool isAnimating = tightness > 0.01f && tightness < 0.99f;
|
||||
|
||||
// Визуально увеличиваем КОНКРЕТНЫЙ выбранный болт под прицелом, чтобы игрок видел, куда навелся
|
||||
float scaleMult = (isHoveredThisFrame && hasWrench) ? 1.25f : 1.0f;
|
||||
// Если игрок отпустил кнопку на полпути или увел взгляд — возвращаем болт в крайнее положение
|
||||
if (!isHoveredThisFrame || (!Input.GetMouseButton(0) && !Input.GetKey(KeyCode.E)))
|
||||
{
|
||||
tightness = isTightened ? 1f : 0f;
|
||||
isAnimating = false;
|
||||
}
|
||||
|
||||
// Болт под прицелом заметно увеличивается (1.35x), чтобы игрок четко видел выбранный болт
|
||||
float scaleMult = (isHoveredThisFrame && hasWrench) ? 1.35f : 1.0f;
|
||||
UpdateBoltTransform(scaleMult);
|
||||
|
||||
if (meshRenderer != null)
|
||||
{
|
||||
if (isTightened || isAnimating)
|
||||
{
|
||||
// Закрученный болт всегда виден; под прицелом с ключом — подсвечивается
|
||||
meshRenderer.enabled = true;
|
||||
// Подсвечиваем только тот болт, на который сейчас наведен прицел!
|
||||
if (isHoveredThisFrame && hasWrench && ghostMaterial != null)
|
||||
meshRenderer.sharedMaterial = ghostMaterial;
|
||||
else if (originalMaterial != null)
|
||||
@@ -112,9 +160,10 @@ public class WheelBolt : MonoBehaviour, IInteractable
|
||||
}
|
||||
else
|
||||
{
|
||||
// Выкрученный болт: показываем силуэт отверстия при взятом ключе
|
||||
meshRenderer.enabled = hasWrench && isHoveredThisFrame;
|
||||
if (meshRenderer.enabled && ghostMaterial != null)
|
||||
// КЛЮЧЕВОЕ ИСПРАВЛЕНИЕ: когда болты выкручены и игрок взял КЛЮЧ (hasWrench),
|
||||
// ВСЕ 4 места под болты сразу подсвечиваются силуэтом, чтобы игрок видел, куда наводиться!
|
||||
meshRenderer.enabled = hasWrench;
|
||||
if (hasWrench && ghostMaterial != null)
|
||||
meshRenderer.sharedMaterial = ghostMaterial;
|
||||
}
|
||||
}
|
||||
@@ -134,20 +183,14 @@ public class WheelBolt : MonoBehaviour, IInteractable
|
||||
bool hasWrench = toolManager != null && toolManager.currentTool == ToolType.Wrench;
|
||||
if (!hasWrench)
|
||||
{
|
||||
waitForRelease = false;
|
||||
return isTightened
|
||||
? "Колесный болт (Возьмите баллонный ключ [Tab])"
|
||||
: "Отверстие под болт (Возьмите ключ [Tab])";
|
||||
: "Место под болт (Возьмите баллонный ключ [Tab])";
|
||||
}
|
||||
|
||||
bool isHoldingKey = Input.GetMouseButton(0) || Input.GetKey(KeyCode.E);
|
||||
|
||||
if (!isHoldingKey)
|
||||
{
|
||||
waitForRelease = false;
|
||||
tightness = isTightened ? 1f : 0f;
|
||||
}
|
||||
else if (!waitForRelease)
|
||||
if (isHoldingKey && !waitForKeyRelease)
|
||||
{
|
||||
ProcessWrench(Time.deltaTime);
|
||||
}
|
||||
@@ -155,9 +198,15 @@ public class WheelBolt : MonoBehaviour, IInteractable
|
||||
int percent = Mathf.RoundToInt((isTightened ? (1f - tightness) : tightness) * 100f);
|
||||
|
||||
if (isTightened)
|
||||
return (percent > 0 && !waitForRelease) ? $"Откручиваем болт... {percent}%" : "[Удерж. ЛКМ / E] Открутить болт";
|
||||
{
|
||||
if (waitForKeyRelease) return "Болт закручен! Отпустите кнопку";
|
||||
return percent > 0 ? $"Откручиваем болт... {percent}%" : "[Удерж. ЛКМ / E] Открутить болт";
|
||||
}
|
||||
else
|
||||
return (percent > 0 && !waitForRelease) ? $"Закручиваем болт... {percent}%" : "[Удерж. ЛКМ / E] Закрутить болт";
|
||||
{
|
||||
if (waitForKeyRelease) return "Болт выкручен! Отпустите кнопку";
|
||||
return percent > 0 ? $"Закручиваем болт... {percent}%" : "[Удерж. ЛКМ / E] Закрутить болт";
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessWrench(float dt)
|
||||
@@ -171,7 +220,7 @@ public class WheelBolt : MonoBehaviour, IInteractable
|
||||
{
|
||||
tightness = 0f;
|
||||
isTightened = false;
|
||||
waitForRelease = true;
|
||||
waitForKeyRelease = true; // Блокируем до отпускания кнопки!
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -181,14 +230,18 @@ public class WheelBolt : MonoBehaviour, IInteractable
|
||||
{
|
||||
tightness = 1f;
|
||||
isTightened = true;
|
||||
waitForRelease = true;
|
||||
waitForKeyRelease = true; // Блокируем до отпускания кнопки!
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateBoltTransform(float scaleMultiplier = 1f)
|
||||
{
|
||||
float outFactor = 1f - Mathf.Clamp01(tightness);
|
||||
// Выкрученный неанимируемый силуэт стоит ровно в гнезде ступицы (outFactor = 0),
|
||||
// чтобы силуэты отверстий не висели в воздухе в 5 см от диска
|
||||
bool isAnimating = tightness > 0.001f && tightness < 0.999f;
|
||||
float outFactor = isAnimating ? (1f - Mathf.Clamp01(tightness)) : 0f;
|
||||
|
||||
Vector3 currentScale = baseLocalScale * scaleMultiplier;
|
||||
|
||||
Quaternion spinRotation = Quaternion.AngleAxis(outFactor * 720f, parentOutwardDir);
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(BoxCollider))]
|
||||
public class WheelBrickSupport : MonoBehaviour, IInteractable
|
||||
{
|
||||
private Rigidbody carRb;
|
||||
private Transform carRoot;
|
||||
private WheelCollider targetWheelCollider;
|
||||
private string targetWheelName;
|
||||
|
||||
private GameObject physicsAnchorObj;
|
||||
private ConfigurableJoint supportJoint;
|
||||
|
||||
public static WheelBrickSupport CreateUnderWheel(CarPart missingWheelPart, GameObject customBricksPrefab = null)
|
||||
{
|
||||
if (missingWheelPart == null) return null;
|
||||
|
||||
Rigidbody rb = missingWheelPart.GetComponentInParent<Rigidbody>();
|
||||
if (rb == null) return null;
|
||||
|
||||
Transform carTr = rb.transform;
|
||||
WheelCollider wc = missingWheelPart.LinkedWheelCollider;
|
||||
Vector3 wheelWorldPos = wc != null ? wc.transform.position : missingWheelPart.transform.position;
|
||||
|
||||
// Находим точку под порогом рядом с колесной аркой (чтобы новое колесо не проходило сквозь кирпичи)
|
||||
Vector3 localWheel = carTr.InverseTransformPoint(wheelWorldPos);
|
||||
float zOffset = -Mathf.Sign(localWheel.z) * 0.42f;
|
||||
float sideSign = Mathf.Sign(localWheel.x);
|
||||
if (sideSign == 0f) sideSign = 1f;
|
||||
|
||||
Vector3 localSupportPoint = new Vector3(localWheel.x * 0.92f, localWheel.y, localWheel.z + zOffset);
|
||||
Vector3 worldSupportPoint = carTr.TransformPoint(localSupportPoint);
|
||||
|
||||
// Ищем высоту асфальта строго под точкой опоры
|
||||
float groundY = wheelWorldPos.y - (wc != null ? wc.radius : 0.32f);
|
||||
RaycastHit[] hits = Physics.RaycastAll(worldSupportPoint + Vector3.up * 0.5f, Vector3.down, 2.0f, ~0, QueryTriggerInteraction.Ignore);
|
||||
foreach (var h in hits)
|
||||
{
|
||||
if (h.collider.transform.IsChildOf(carTr)) continue;
|
||||
groundY = h.point.y;
|
||||
break;
|
||||
}
|
||||
|
||||
// Высота от земли до днища/порога
|
||||
float sillClearance = wc != null ? Mathf.Clamp((wheelWorldPos.y - groundY) * 0.62f, 0.14f, 0.26f) : 0.18f;
|
||||
Vector3 spawnPos = new Vector3(worldSupportPoint.x, groundY, worldSupportPoint.z);
|
||||
|
||||
GameObject supportObj = new GameObject($"BrickSupport_{missingWheelPart.name}");
|
||||
supportObj.layer = missingWheelPart.gameObject.layer;
|
||||
supportObj.transform.position = spawnPos;
|
||||
supportObj.transform.rotation = carTr.rotation;
|
||||
|
||||
WheelBrickSupport support = supportObj.AddComponent<WheelBrickSupport>();
|
||||
support.Initialize(rb, wc, missingWheelPart.name, sillClearance, customBricksPrefab);
|
||||
return support;
|
||||
}
|
||||
|
||||
private void Initialize(Rigidbody rb, WheelCollider wc, string wheelName, float height, GameObject customPrefab)
|
||||
{
|
||||
carRb = rb;
|
||||
carRoot = rb.transform;
|
||||
targetWheelCollider = wc;
|
||||
targetWheelName = wheelName;
|
||||
|
||||
// Настраиваем триггер-коллайдер для луча игрока
|
||||
BoxCollider col = GetComponent<BoxCollider>();
|
||||
col.isTrigger = true;
|
||||
col.size = new Vector3(0.32f, height + 0.06f, 0.38f);
|
||||
col.center = new Vector3(0f, (height + 0.06f) * 0.5f, 0f);
|
||||
|
||||
// Создаем визуал кирпичей (префаб или процедурную кладку)
|
||||
if (customPrefab != null)
|
||||
{
|
||||
GameObject visual = Instantiate(customPrefab, transform);
|
||||
visual.transform.localPosition = Vector3.zero;
|
||||
visual.transform.localRotation = Quaternion.identity;
|
||||
foreach (var c in visual.GetComponentsInChildren<Collider>(true)) c.enabled = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
BuildProceduralBricks(height);
|
||||
}
|
||||
|
||||
// Фиксируем этот угол машины на текущей высоте, чтобы она не кренилась без колеса
|
||||
Vector3 contactWorld = transform.position + Vector3.up * height;
|
||||
CreateSupportJoint(contactWorld);
|
||||
}
|
||||
|
||||
private void BuildProceduralBricks(float totalHeight)
|
||||
{
|
||||
Material brickMat = new Material(Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard"));
|
||||
brickMat.color = new Color(0.68f, 0.28f, 0.18f); // Кирпичный цвет
|
||||
|
||||
int layers = 3;
|
||||
float brickH = totalHeight / layers;
|
||||
float brickW = 0.12f;
|
||||
float brickL = 0.25f;
|
||||
|
||||
for (int row = 0; row < layers; row++)
|
||||
{
|
||||
float yPos = (row + 0.5f) * brickH;
|
||||
bool rotated = (row % 2 == 1);
|
||||
|
||||
for (int i = -1; i <= 1; i += 2)
|
||||
{
|
||||
GameObject brick = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
Destroy(brick.GetComponent<Collider>());
|
||||
brick.transform.SetParent(transform, false);
|
||||
|
||||
float offset = i * (brickW * 0.54f);
|
||||
brick.transform.localPosition = rotated
|
||||
? new Vector3(0f, yPos, offset)
|
||||
: new Vector3(offset, yPos, 0f);
|
||||
|
||||
brick.transform.localRotation = rotated
|
||||
? Quaternion.Euler(0f, 90f, 0f)
|
||||
: Quaternion.identity;
|
||||
|
||||
brick.transform.localScale = new Vector3(brickW, brickH * 0.92f, brickL);
|
||||
brick.GetComponent<Renderer>().sharedMaterial = brickMat;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void CreateSupportJoint(Vector3 contactWorld)
|
||||
{
|
||||
if (carRb == null) return;
|
||||
|
||||
physicsAnchorObj = new GameObject("BricksPhysicsAnchor");
|
||||
physicsAnchorObj.transform.position = contactWorld;
|
||||
|
||||
Rigidbody anchorRb = physicsAnchorObj.AddComponent<Rigidbody>();
|
||||
anchorRb.isKinematic = true;
|
||||
|
||||
supportJoint = physicsAnchorObj.AddComponent<ConfigurableJoint>();
|
||||
supportJoint.connectedBody = carRb;
|
||||
supportJoint.autoConfigureConnectedAnchor = false;
|
||||
supportJoint.anchor = Vector3.zero;
|
||||
supportJoint.connectedAnchor = carRb.transform.InverseTransformPoint(contactWorld);
|
||||
|
||||
JointDrive verticalDrive = new JointDrive
|
||||
{
|
||||
positionSpring = carRb.mass * 220f,
|
||||
positionDamper = carRb.mass * 30f,
|
||||
maximumForce = carRb.mass * 80f
|
||||
};
|
||||
|
||||
JointDrive horizontalDrive = new JointDrive
|
||||
{
|
||||
positionSpring = carRb.mass * 40f,
|
||||
positionDamper = carRb.mass * 10f,
|
||||
maximumForce = carRb.mass * 30f
|
||||
};
|
||||
|
||||
supportJoint.xDrive = horizontalDrive;
|
||||
supportJoint.yDrive = verticalDrive;
|
||||
supportJoint.zDrive = horizontalDrive;
|
||||
}
|
||||
|
||||
private bool IsWheelReadyToHoldCar()
|
||||
{
|
||||
if (carRoot == null) return true;
|
||||
|
||||
// Если эту сторону уже подняли домкратом — кирпичи тоже можно свободно вытащить
|
||||
if (CarJack.IsWheelLifted(transform)) return true;
|
||||
|
||||
// Ищем установленное на эту ступицу колесо и проверяем его болты
|
||||
foreach (CarPart part in carRoot.GetComponentsInChildren<CarPart>(false))
|
||||
{
|
||||
if (part.State != PartState.Installed) continue;
|
||||
|
||||
bool isMatchingHub = (targetWheelCollider != null && part.LinkedWheelCollider == targetWheelCollider)
|
||||
|| part.name == targetWheelName;
|
||||
|
||||
if (isMatchingHub)
|
||||
{
|
||||
return part.TotalBoltsCount == 0 || part.TightenedBoltsCount >= part.TotalBoltsCount;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public string GetPrompt()
|
||||
{
|
||||
if (!IsWheelReadyToHoldCar())
|
||||
{
|
||||
return "Машина стоит на кирпичах\n<color=yellow>Сначала установите колесо и закрутите все болты!</color>";
|
||||
}
|
||||
|
||||
return "[E] Убрать кирпичи";
|
||||
}
|
||||
|
||||
public void Interact(GameObject interactor)
|
||||
{
|
||||
if (!IsWheelReadyToHoldCar()) return;
|
||||
|
||||
RemoveBricks();
|
||||
}
|
||||
|
||||
public void RemoveBricks()
|
||||
{
|
||||
if (physicsAnchorObj != null)
|
||||
Destroy(physicsAnchorObj);
|
||||
|
||||
if (carRb != null)
|
||||
carRb.WakeUp();
|
||||
|
||||
Destroy(gameObject);
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (physicsAnchorObj != null)
|
||||
Destroy(physicsAnchorObj);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f60f5fc826264d8781da1587ba1ec484
|
||||
timeCreated: 1792535337
|
||||
@@ -1,49 +1,131 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public struct CarDefectsSummary
|
||||
{
|
||||
public int rustedPartsCount;
|
||||
public int missingBodyPartsCount;
|
||||
public int flatTiresCount;
|
||||
public int missingWheelsCount;
|
||||
public List<string> missingPartNames;
|
||||
public float totalPricePenalty;
|
||||
}
|
||||
|
||||
public class CarConditionGenerator : MonoBehaviour
|
||||
{
|
||||
[Header("Настройки спавна")]
|
||||
[Range(0f, 1f)] [SerializeField] private float rustProbability = 0.7f;
|
||||
[SerializeField] private float minRustAmount = 0.2f;
|
||||
[SerializeField] private float maxRustAmount = 0.75f;
|
||||
[Header("Настройки ржавчины")]
|
||||
[Range(0f, 1f)] [SerializeField] private float rustProbability = 0.65f;
|
||||
[SerializeField] private float minRustAmount = 0.25f;
|
||||
[SerializeField] private float maxRustAmount = 0.80f;
|
||||
|
||||
[Header("Шанс отсутствия навесных деталей (бамперы, фары, крылья)")]
|
||||
[Range(0f, 0.5f)] [SerializeField] private float missingBodyPartChance = 0.15f;
|
||||
[SerializeField] private int maxMissingBodyParts = 3;
|
||||
|
||||
[Header("Проблемы с колесами")]
|
||||
[Range(0f, 1f)] [SerializeField] private float flatTireChance = 0.25f;
|
||||
[Range(0f, 1f)] [SerializeField] private float missingWheelChance = 0.12f;
|
||||
|
||||
[Header("Цвет кузова")]
|
||||
[Tooltip("Включите, только если хотите принудительно перекрасить машину при старте")]
|
||||
[SerializeField] private bool overrideMaterialColor = false;
|
||||
[SerializeField] private Color baseCarColor = Color.blue;
|
||||
|
||||
private bool configuredExternally = false;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
GenerateCondition();
|
||||
// Если машина уже настроена через CarMarketManager (по Seed) — не перезаписываем её!
|
||||
if (!configuredExternally)
|
||||
{
|
||||
GenerateCondition();
|
||||
}
|
||||
}
|
||||
|
||||
[ContextMenu("Сгенерировать состояние")]
|
||||
[ContextMenu("Сгенерировать случайное состояние")]
|
||||
public void GenerateCondition()
|
||||
{
|
||||
// 1. Обрабатываем все съемные детали (CarPart)
|
||||
int randomSeed = Random.Range(1, 999999);
|
||||
Color col = overrideMaterialColor ? baseCarColor : GetCurrentBodyColor();
|
||||
ApplyConditionBySeed(randomSeed, col, false, out _);
|
||||
}
|
||||
|
||||
public Color GetCurrentBodyColor()
|
||||
{
|
||||
int rustProp = Shader.PropertyToID("_RustAmount");
|
||||
int colorProp = Shader.PropertyToID("_BaseColor");
|
||||
foreach (Renderer r in GetComponentsInChildren<Renderer>(true))
|
||||
{
|
||||
foreach (Material m in r.sharedMaterials)
|
||||
{
|
||||
if (m != null && m.HasProperty(rustProp) && m.HasProperty(colorProp))
|
||||
return m.GetColor(colorProp);
|
||||
}
|
||||
}
|
||||
return baseCarColor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Генерирует 100% одинаковое состояние машины для одного и того же seed (и в фотобоксе, и на карте).
|
||||
/// </summary>
|
||||
public void ApplyConditionBySeed(int seed, Color carColor, bool isPhotoStudio, out CarDefectsSummary summary)
|
||||
{
|
||||
configuredExternally = true;
|
||||
Random.State oldState = Random.state;
|
||||
Random.InitState(seed);
|
||||
|
||||
summary = new CarDefectsSummary
|
||||
{
|
||||
missingPartNames = new List<string>()
|
||||
};
|
||||
|
||||
CarPart[] allParts = GetComponentsInChildren<CarPart>(true);
|
||||
|
||||
// 1. Обрабатываем кузовные и навесные детали (кроме колес)
|
||||
foreach (CarPart part in allParts)
|
||||
{
|
||||
// Пропускаем колеса (у них свой цикл ниже)
|
||||
if (part.GetComponent<CarWheelCondition>() != null || part.TotalBoltsCount > 0)
|
||||
continue;
|
||||
|
||||
CarPartVisuals visuals = part.GetComponent<CarPartVisuals>();
|
||||
if (visuals == null) visuals = part.gameObject.AddComponent<CarPartVisuals>();
|
||||
|
||||
if (overrideMaterialColor)
|
||||
visuals.SetPaintColor(baseCarColor);
|
||||
visuals.SetPaintColor(carColor);
|
||||
|
||||
float partPrice = part.Data != null ? part.Data.basePrice : 150f;
|
||||
string partTitle = part.Data != null ? part.Data.partName : part.name;
|
||||
|
||||
// Проверяем, отсутствует ли эта навесная деталь (бампер, фара, крыло, дверь, зеркало)
|
||||
if (summary.missingBodyPartsCount < maxMissingBodyParts && Random.value < missingBodyPartChance)
|
||||
{
|
||||
summary.missingBodyPartsCount++;
|
||||
summary.missingPartNames.Add(partTitle.ToLower());
|
||||
summary.totalPricePenalty += partPrice * 1.4f;
|
||||
part.MakeMissingAtStart(null, false);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Пластик не ржавеет
|
||||
if (part.Data != null && !part.Data.canRust)
|
||||
{
|
||||
visuals.SetDamage(0f);
|
||||
continue;
|
||||
}
|
||||
|
||||
float damage = Random.value < rustProbability
|
||||
? Random.Range(minRustAmount, maxRustAmount)
|
||||
: 0f;
|
||||
|
||||
visuals.SetDamage(damage);
|
||||
if (Random.value < rustProbability)
|
||||
{
|
||||
float dmg = Random.Range(minRustAmount, maxRustAmount);
|
||||
visuals.SetDamage(dmg);
|
||||
summary.rustedPartsCount++;
|
||||
summary.totalPricePenalty += partPrice * dmg;
|
||||
}
|
||||
else
|
||||
{
|
||||
visuals.SetDamage(0f);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Обрабатываем основной кузов (body), на котором нет CarPart, чтобы он не оставался ржавым из материала
|
||||
// 2. Обрабатываем основной несъемный кузов (body)
|
||||
int rustProp = Shader.PropertyToID("_RustAmount");
|
||||
foreach (Renderer r in GetComponentsInChildren<Renderer>(true))
|
||||
{
|
||||
@@ -55,11 +137,45 @@ public class CarConditionGenerator : MonoBehaviour
|
||||
{
|
||||
CarPartVisuals bodyVis = r.GetComponent<CarPartVisuals>();
|
||||
if (bodyVis == null) bodyVis = r.gameObject.AddComponent<CarPartVisuals>();
|
||||
if (overrideMaterialColor) bodyVis.SetPaintColor(baseCarColor);
|
||||
bodyVis.SetDamage(Random.value < rustProbability ? Random.Range(minRustAmount, maxRustAmount) : 0f);
|
||||
bodyVis.SetPaintColor(carColor);
|
||||
|
||||
float bodyDmg = Random.value < rustProbability ? Random.Range(minRustAmount, maxRustAmount) : 0f;
|
||||
bodyVis.SetDamage(bodyDmg);
|
||||
if (bodyDmg > 0.05f)
|
||||
{
|
||||
summary.rustedPartsCount++;
|
||||
summary.totalPricePenalty += 250f * bodyDmg;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Обрабатываем колеса (Нормальное / Спущенное / Отсутствует)
|
||||
CarWheelCondition[] wheels = GetComponentsInChildren<CarWheelCondition>(true);
|
||||
foreach (CarWheelCondition wheel in wheels)
|
||||
{
|
||||
float roll = Random.value;
|
||||
// В одном объявлении убираем максимум 1 колесо, чтобы машина не висела вся на кирпичах
|
||||
if (roll < missingWheelChance && summary.missingWheelsCount < 1)
|
||||
{
|
||||
summary.missingWheelsCount++;
|
||||
summary.totalPricePenalty += 220f;
|
||||
CarPart wp = wheel.GetComponent<CarPart>();
|
||||
if (wp != null) wp.MakeMissingAtStart(null, !isPhotoStudio);
|
||||
}
|
||||
else if (roll < missingWheelChance + flatTireChance)
|
||||
{
|
||||
summary.flatTiresCount++;
|
||||
summary.totalPricePenalty += 100f;
|
||||
wheel.ApplyState(CarWheelCondition.TireState.Flat);
|
||||
}
|
||||
else
|
||||
{
|
||||
wheel.ApplyState(CarWheelCondition.TireState.Normal);
|
||||
}
|
||||
}
|
||||
|
||||
Random.state = oldState;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user