Добавляю машины и настраиваю их

This commit is contained in:
bybohka committed 2026-09-30 03:22:34 +03:00
1 parent 1c106ea853
commit a8238ab49e
363 files changed
+54820 -687

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6ff65ba155b645f2a1fe611307cc7eca
timeCreated: 1790289676
+161
View File
@@ -0,0 +1,161 @@
using UnityEngine;
public enum PartState { Installed, InHand, Dropped }
[RequireComponent(typeof(Collider))]
public class CarPart : MonoBehaviour, IInteractable
{
[Header("Данные")]
[SerializeField] private CarPartData partData;
[SerializeField] private float mass = 12f;
[Header("Позиционирование в руках")]
[Tooltip("Дополнительное смещение детали в руках, если она перекрывает весь обзор")]
[SerializeField] private Vector3 inHandPositionOffset = Vector3.zero;
[Tooltip("Поворот детали в руках (например, если бампер берется боком)")]
[SerializeField] private Vector3 inHandRotationOffset = Vector3.zero;
private PartState currentState = PartState.Installed;
private Transform originalParent;
private Vector3 originalLocalPos;
private Quaternion originalLocalRot;
private Vector3 originalLocalScale;
private Rigidbody rb;
private Collider partCollider;
private GameObject currentMountZone;
public CarPartData Data => partData;
public PartState State => currentState;
private void Awake()
{
partCollider = GetComponent<Collider>();
originalParent = transform.parent;
originalLocalPos = transform.localPosition;
originalLocalRot = transform.localRotation;
originalLocalScale = transform.localScale;
}
public string GetPrompt()
{
if (partData == null) return "Деталь (E)";
return currentState switch
{
PartState.Installed => $"Снять {partData.partName} (E)",
PartState.Dropped => $"Взять {partData.partName} (E)",
_ => string.Empty
};
}
public void Interact(GameObject interactor)
{
PlayerHands hands = interactor.GetComponent<PlayerHands>();
if (hands == null) hands = interactor.GetComponentInParent<PlayerHands>();
if (hands == null) return;
if (currentState == PartState.Installed)
{
// 1. Создаем зону для обратной установки на машине
CreateMountZone();
// 2. Берем сразу в руки
hands.PickUp(this);
}
else if (currentState == PartState.Dropped)
{
// Подбираем деталь с земли
hands.PickUp(this);
}
}
public void OnPickedUp(Transform holdPoint)
{
currentState = PartState.InHand;
// Отключаем физику и коллайдер
if (rb != null) Destroy(rb);
partCollider.enabled = false;
// 1. Привязываем к рукам и сохраняем оригинальный размер (чтобы не сплющило)
transform.SetParent(holdPoint);
transform.localScale = originalLocalScale;
// 2. Задаем поворот вперед с учетом возможной ручной поправки
transform.localRotation = Quaternion.Euler(inHandRotationOffset);
transform.localPosition = Vector3.zero;
// 3. АВТО-ЦЕНТРИРОВАНИЕ: компенсируем сбитый пивот геометрии
Renderer meshRenderer = GetComponentInChildren<Renderer>();
if (meshRenderer != null)
{
// Находим, где сейчас находится визуальный центр геометрии в мире
Vector3 visualCenterWorld = meshRenderer.bounds.center;
// Вычисляем вектор сдвига, чтобы центр меша совпал с точкой HoldPoint
Vector3 offsetToCenter = holdPoint.position - visualCenterWorld;
// Смещаем деталь так, чтобы её реальный центр оказался в руках
transform.position += offsetToCenter;
// Применяем ручной оффсет, если захотите опустить деталь чуть ниже
transform.localPosition += inHandPositionOffset;
}
}
public void OnDropped(Vector3 throwForce)
{
currentState = PartState.Dropped;
// Отвязываем от игрока
transform.SetParent(null);
transform.localScale = originalLocalScale;
// Включаем коллайдер обратно
partCollider.enabled = true;
if (partCollider is MeshCollider meshCol) meshCol.convex = true;
// Включаем физику
rb = gameObject.AddComponent<Rigidbody>();
rb.mass = mass;
rb.interpolation = RigidbodyInterpolation.Interpolate;
if (throwForce != Vector3.zero)
{
rb.AddForce(throwForce, ForceMode.Impulse);
}
}
public void Install()
{
currentState = PartState.Installed;
if (rb != null) Destroy(rb);
// Возвращаем на исходное место на машине
transform.SetParent(originalParent);
transform.localPosition = originalLocalPos;
transform.localRotation = originalLocalRot;
transform.localScale = originalLocalScale;
partCollider.enabled = true;
}
private void CreateMountZone()
{
if (currentMountZone != null) return;
currentMountZone = new GameObject($"MountZone_{gameObject.name}");
currentMountZone.transform.SetParent(originalParent);
currentMountZone.transform.localPosition = originalLocalPos;
currentMountZone.transform.localRotation = originalLocalRot;
currentMountZone.transform.localScale = originalLocalScale; // Передаем оригинальный масштаб
CarPartMountZone zone = currentMountZone.AddComponent<CarPartMountZone>();
zone.Initialize(this);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 46199851c79547bc8c4f7ac4a0924fa5
timeCreated: 1790289784
@@ -0,0 +1,82 @@
using UnityEngine;
public class CarPartMountZone : MonoBehaviour, IInteractable
{
private CarPart targetPart;
private Collider zoneCollider;
public void Initialize(CarPart part)
{
targetPart = part;
gameObject.layer = part.gameObject.layer;
// В точности копируем параметры оригинального коллайдера детали
Collider sourceCollider = part.GetComponent<Collider>();
if (sourceCollider is BoxCollider sourceBox)
{
BoxCollider box = gameObject.AddComponent<BoxCollider>();
box.center = sourceBox.center;
box.size = sourceBox.size;
box.isTrigger = true;
zoneCollider = box;
}
else if (sourceCollider is MeshCollider sourceMesh)
{
MeshCollider meshCol = gameObject.AddComponent<MeshCollider>();
meshCol.sharedMesh = sourceMesh.sharedMesh;
meshCol.convex = true;
meshCol.isTrigger = true;
zoneCollider = meshCol;
}
else
{
// Универсальный запасной вариант
SphereCollider sphere = gameObject.AddComponent<SphereCollider>();
sphere.radius = 0.6f;
sphere.isTrigger = true;
zoneCollider = sphere;
}
}
public string GetPrompt()
{
PlayerHands hands = FindAnyObjectByType<PlayerHands>();
// Показываем надпись ТОЛЬКО если игрок держит именно эту деталь
if (hands != null && hands.IsHolding && hands.CurrentPart == targetPart)
{
return $"Установить {targetPart.Data.partName} (E)";
}
return string.Empty;
}
public void Interact(GameObject interactor)
{
PlayerHands hands = interactor.GetComponent<PlayerHands>();
if (hands == null) hands = interactor.GetComponentInParent<PlayerHands>();
if (hands != null && hands.IsHolding && hands.CurrentPart == targetPart)
{
hands.ClearHandAfterInstall();
targetPart.Install();
Destroy(gameObject); // Убираем зону после установки
}
}
// Рисует зеленый контур зоны в окне Scene во время игры
private void OnDrawGizmos()
{
Gizmos.color = Color.green;
if (zoneCollider is BoxCollider box)
{
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawWireCube(box.center, box.size);
}
else
{
Gizmos.DrawWireSphere(transform.position, 0.5f);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6974db776d91487fa81d470aa4b97359
timeCreated: 1790290230
@@ -0,0 +1,10 @@
using UnityEngine;
[CreateAssetMenu(fileName = "NewCarPart", menuName = "Car System/Part Data")]
public class CarPartData : ScriptableObject
{
[Header("Данные детали")]
public string partName = "Передний бампер";
public float basePrice = 150f;
[Range(0, 100)] public float condition = 100f; // Состояние детали для оценки авто
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0cd31d9fac3d42f78a28531811779ce9
timeCreated: 1790289694