Добавил скрипты для более реалистичной физики, но они шляпа полная.
This commit is contained in:
1 parent
f9eb14868d
commit
5f25a8eab4
32 files changed
+490
-1643
No files matched your search
@@ -0,0 +1,200 @@
|
||||
using UnityEngine;
|
||||
|
||||
public enum PartState { Installed, InHand, Dropped }
|
||||
|
||||
public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
|
||||
{
|
||||
[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 CarPartAnimator partAnimator;
|
||||
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>();
|
||||
partAnimator = GetComponent<CarPartAnimator>();
|
||||
|
||||
originalParent = transform.parent;
|
||||
originalLocalPos = transform.localPosition;
|
||||
originalLocalRot = transform.localRotation;
|
||||
originalLocalScale = transform.localScale;
|
||||
|
||||
|
||||
}
|
||||
|
||||
public string GetPrompt()
|
||||
{
|
||||
if (partData == null) return "Деталь (E)";
|
||||
|
||||
if (currentState == PartState.Installed)
|
||||
{
|
||||
// Если на детали есть аниматор — выводим подсказку с открытием
|
||||
if (partAnimator != null)
|
||||
{
|
||||
string action = partAnimator.IsOpen ? "Закрыть" : "Открыть";
|
||||
return $"[E] {action} {partData.partName} | [R] Снять";
|
||||
}
|
||||
|
||||
return $"Снять {partData.partName} (E)";
|
||||
}
|
||||
|
||||
if (currentState == PartState.Dropped)
|
||||
{
|
||||
return $"Взять {partData.partName} (E)";
|
||||
}
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
public void Interact(GameObject interactor)
|
||||
{
|
||||
if (currentState == PartState.Installed)
|
||||
{
|
||||
if (partAnimator != null)
|
||||
{
|
||||
// Нажали E — открываем или закрываем
|
||||
partAnimator.TogglePart();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Обычная деталь (бампер) сразу снимается
|
||||
TakeToHands(interactor);
|
||||
}
|
||||
}
|
||||
else if (currentState == PartState.Dropped)
|
||||
{
|
||||
TakeToHands(interactor);
|
||||
}
|
||||
}
|
||||
|
||||
// Вызывается при нажатии R (вторичное действие)
|
||||
public void SecondaryInteract(GameObject interactor)
|
||||
{
|
||||
if (currentState == PartState.Installed)
|
||||
{
|
||||
TakeToHands(interactor);
|
||||
}
|
||||
}
|
||||
|
||||
// Вынесенный общий метод взятия в руки
|
||||
private void TakeToHands(GameObject interactor)
|
||||
{
|
||||
PlayerHands hands = interactor.GetComponent<PlayerHands>();
|
||||
if (hands == null) hands = interactor.GetComponentInParent<PlayerHands>();
|
||||
|
||||
if (hands == null) return;
|
||||
|
||||
if (currentState == PartState.Installed)
|
||||
{
|
||||
if (partAnimator != null) partAnimator.ResetToClosed();
|
||||
CreateMountZone();
|
||||
}
|
||||
|
||||
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,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d1396ff771764dc2bcb7e90faac08815
|
||||
timeCreated: 1791809673
|
||||
@@ -0,0 +1,13 @@
|
||||
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;
|
||||
|
||||
[Header("Коррозия и материалы")]
|
||||
public bool canRust = true;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0cd31d9fac3d42f78a28531811779ce9
|
||||
timeCreated: 1790289694
|
||||
Reference in new issue
Block a user