Снятие колес работает, покраска тоже более менее. Физика просто говно щяс

This commit is contained in:
bybohka committed 2026-10-20 17:54:31 +03:00
1 parent d4c84b10df
commit 2ce853999d
67 files changed
+155919 -1996

No files matched your search

+94 -111
View File
@@ -7,12 +7,11 @@ 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;
@@ -20,39 +19,49 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
private Quaternion originalLocalRot;
private Vector3 originalLocalScale;
private WheelBolt[] wheelBolts;
private Rigidbody rb;
private Collider partCollider;
private GameObject currentMountZone;
private WheelCollider linkedWheelCollider;
private Transform currentHoldPoint;
private Vector3 targetInHandLocalPos;
private Quaternion targetInHandLocalRot;
private float unboltDuration => (partData != null && partData.boltDuration > 0f) ? partData.boltDuration : 1.2f;
private float unboltProgress = 0f;
public float UnboltProgress01 => Mathf.Clamp01(unboltProgress / unboltDuration);
private Rigidbody rb;
private Collider partCollider;
private GameObject currentMountZone;
private float unboltDuration => (partData != null && partData.boltDuration > 0f) ? partData.boltDuration : 1.2f;
private float unboltProgress = 0f;
public float UnboltProgress01 => Mathf.Clamp01(unboltProgress / unboltDuration);
public void ResetUnbolt() => unboltProgress = 0f;
public CarPartData Data => partData;
public PartState State => currentState;
public bool HasAnimator => partAnimator != null;
public int TotalBoltsCount => wheelBolts != null ? wheelBolts.Length : 0;
public int TightenedBoltsCount
{
get
{
if (wheelBolts == null || wheelBolts.Length == 0) return 0;
int count = 0;
foreach (var b in wheelBolts)
if (b != null && b.IsTightened) count++;
return count;
}
}
private void Awake()
{
partCollider = GetComponent<Collider>();
partAnimator = GetComponent<CarPartAnimator>();
wheelBolts = GetComponentsInChildren<WheelBolt>(true);
originalParent = transform.parent;
originalLocalPos = transform.localPosition;
originalLocalRot = transform.localRotation;
originalLocalScale = transform.localScale;
// Если эта деталь — колесо, автоматически находим её физический WheelCollider по имени (например, "Wheel_FL")
VehicleInteraction car = GetComponentInParent<VehicleInteraction>();
if (car != null)
{
@@ -65,6 +74,23 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
}
}
}
// ВАЖНО: Если это колесо, на машине его MeshCollider ДОЛЖЕН быть триггером!
// Иначе он трется об асфальт и крылья машины, мешая WheelCollider'у ехать!
if (linkedWheelCollider != null && partCollider != null)
{
if (partCollider is MeshCollider mc) mc.convex = true;
partCollider.isTrigger = true;
}
}
private void LateUpdate()
{
if (currentState == PartState.InHand && currentHoldPoint != null)
{
transform.localPosition = targetInHandLocalPos;
transform.localRotation = targetInHandLocalRot;
}
}
public string GetPrompt()
@@ -73,36 +99,32 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
if (currentState == PartState.Installed)
{
if (wheelBolts != null && wheelBolts.Length > 0 && !CarJack.IsWheelLifted(transform))
if (wheelBolts != null && wheelBolts.Length > 0)
{
return "Колесо под нагрузкой! Сначала поднимите авто домкратом";
if (!CarJack.IsWheelLifted(transform))
return "Колесо под нагрузкой! Поднимите авто домкратом";
if (TightenedBoltsCount > 0)
return $"Сначала открутите болты ({TightenedBoltsCount}/{wheelBolts.Length})";
return $"[E] Снять {partData.partName}";
}
if (wheelBolts != null && wheelBolts.Length > 0 && TightenedBoltsCount > 0)
{
return $"Сначала открутите болты ({TightenedBoltsCount}/{wheelBolts.Length})";
}
if (unboltProgress > 0f)
{
return $"Откручивание болтов ({partData.partName})... {Mathf.RoundToInt(UnboltProgress01 * 100f)}%";
}
if (partAnimator != null)
{
string action = partAnimator.IsOpen ? "Закрыть" : "Открыть";
return $"[E] {action} {partData.partName} | [R] Снять";
return $"[E] {action} {partData.partName} | [Удерж. R] Снять";
}
return $"Снять {partData.partName} (E)";
return $"[Удерж. E] Снять {partData.partName}";
}
if (currentState == PartState.Dropped)
{
return $"Взять {partData.partName} (E)";
}
return $"[E] Взять {partData.partName}";
return string.Empty;
}
@@ -111,15 +133,9 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
if (currentState == PartState.Installed)
{
if (partAnimator != null)
{
// Нажали E — открываем или закрываем
partAnimator.TogglePart();
}
else
{
// Обычная деталь (бампер) сразу снимается
else if (wheelBolts != null && wheelBolts.Length > 0 && TightenedBoltsCount == 0 && CarJack.IsWheelLifted(transform))
TakeToHands(interactor);
}
}
else if (currentState == PartState.Dropped)
{
@@ -127,22 +143,34 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
}
}
// Вызывается при нажатии R (вторичное действие)
public void SecondaryInteract(GameObject interactor)
public void SecondaryInteract(GameObject interactor) { }
public void ProcessUnbolting(GameObject interactor, float deltaTime)
{
if (currentState == PartState.Installed)
if (currentState != PartState.Installed) return;
if (wheelBolts != null && wheelBolts.Length > 0)
{
if (!CarJack.IsWheelLifted(transform) || TightenedBoltsCount > 0) return;
TakeToHands(interactor);
return;
}
PlayerToolManager toolMgr = interactor.GetComponentInChildren<PlayerToolManager>();
if (toolMgr != null && toolMgr.currentTool != ToolType.Hands) return;
unboltProgress += deltaTime;
if (unboltProgress >= unboltDuration)
{
unboltProgress = 0f;
TakeToHands(interactor);
}
}
// Вынесенный общий метод взятия в руки
private void TakeToHands(GameObject interactor)
{
PlayerHands hands = interactor.GetComponent<PlayerHands>();
if (hands == null) hands = interactor.GetComponentInParent<PlayerHands>();
if (hands == null) return;
PlayerHands hands = interactor.GetComponentInChildren<PlayerHands>() ?? interactor.GetComponentInParent<PlayerHands>();
if (hands == null || hands.IsHolding) return;
if (currentState == PartState.Installed)
{
@@ -152,32 +180,21 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
hands.PickUp(this);
}
private void LateUpdate()
{
// Блокируем попытки скрипта подвески (EasySuspension) вернуть снятое колесо обратно на машину
if (currentState == PartState.InHand && currentHoldPoint != null)
{
transform.localPosition = targetInHandLocalPos;
transform.localRotation = targetInHandLocalRot;
}
}
public void OnPickedUp(Transform holdPoint)
{
currentState = PartState.InHand;
currentHoldPoint = holdPoint;
unboltProgress = 0f;
if (rb != null) Destroy(rb);
if (partCollider != null) partCollider.enabled = false;
// Если сняли колесо — выключаем его физический WheelCollider на машине
if (linkedWheelCollider != null)
linkedWheelCollider.enabled = false;
transform.SetParent(holdPoint);
transform.localScale = originalLocalScale;
transform.localRotation = Quaternion.Euler(inHandRotationOffset);
transform.localPosition = Vector3.zero;
@@ -190,7 +207,6 @@ private void LateUpdate()
transform.localPosition += inHandPositionOffset;
}
// Запоминаем вычисленную позицию в руках для удержания в LateUpdate
targetInHandLocalPos = transform.localPosition;
targetInHandLocalRot = transform.localRotation;
}
@@ -198,12 +214,10 @@ private void LateUpdate()
public void OnDropped(Vector3 throwForce)
{
currentState = PartState.Dropped;
unboltProgress = 0f;
// Гарантируем, что деталь вылетает именно из точки рук перед игроком, а не из арки авто
if (currentHoldPoint != null)
{
transform.position = currentHoldPoint.position + currentHoldPoint.forward * 0.4f;
}
transform.position = currentHoldPoint.position + currentHoldPoint.forward * 0.45f;
currentHoldPoint = null;
transform.SetParent(null);
@@ -211,8 +225,9 @@ private void LateUpdate()
if (partCollider != null)
{
partCollider.enabled = true;
if (partCollider is MeshCollider meshCol) meshCol.convex = true;
partCollider.isTrigger = false; // На земле деталь твердая
partCollider.enabled = true;
}
rb = gameObject.AddComponent<Rigidbody>();
@@ -220,15 +235,14 @@ private void LateUpdate()
rb.interpolation = RigidbodyInterpolation.Interpolate;
if (throwForce != Vector3.zero)
{
rb.AddForce(throwForce, ForceMode.Impulse);
}
}
public void Install()
{
currentState = PartState.Installed;
currentHoldPoint = null;
unboltProgress = 0f;
if (rb != null) Destroy(rb);
@@ -237,13 +251,21 @@ private void LateUpdate()
transform.localRotation = originalLocalRot;
transform.localScale = originalLocalScale;
if (partCollider != null) partCollider.enabled = true;
if (partCollider != null)
{
partCollider.enabled = true;
// Установленное колесо делаем триггером, чтобы оно не мешало физике езды!
if (linkedWheelCollider != null)
partCollider.isTrigger = true;
}
// Включаем обратно физический WheelCollider при установке колеса
if (linkedWheelCollider != null)
{
linkedWheelCollider.enabled = true;
linkedWheelCollider.motorTorque = 0f;
linkedWheelCollider.brakeTorque = 0f;
}
}
private void CreateMountZone()
{
@@ -253,48 +275,9 @@ private void LateUpdate()
currentMountZone.transform.SetParent(originalParent);
currentMountZone.transform.localPosition = originalLocalPos;
currentMountZone.transform.localRotation = originalLocalRot;
currentMountZone.transform.localScale = originalLocalScale; // Передаем оригинальный масштаб
currentMountZone.transform.localScale = originalLocalScale;
CarPartMountZone zone = currentMountZone.AddComponent<CarPartMountZone>();
zone.Initialize(this);
}
public void ProcessUnbolting(GameObject interactor, float deltaTime)
{
if (wheelBolts != null && wheelBolts.Length > 0 && !CarJack.IsWheelLifted(transform)) return;
if (currentState != PartState.Installed) return;
if (wheelBolts != null && wheelBolts.Length > 0 && TightenedBoltsCount > 0) return;
// Если у детали есть отдельные болты и они УЖЕ выкручены — снимаем колесо сразу без повторного таймера!
if (wheelBolts != null && wheelBolts.Length > 0)
{
TakeToHands(interactor);
return;
}
// Не даем снимать детали, если в руках шлифмашинка или баллончик
PlayerToolManager toolMgr = interactor.GetComponentInChildren<PlayerToolManager>();
if (toolMgr != null && toolMgr.currentTool != ToolType.Hands) return;
unboltProgress += deltaTime;
if (unboltProgress >= unboltDuration)
{
unboltProgress = 0f;
TakeToHands(interactor);
}
}
public int TightenedBoltsCount
{
get
{
if (wheelBolts == null || wheelBolts.Length == 0) return 0;
int count = 0;
foreach (var b in wheelBolts)
if (b != null && b.IsTightened) count++;
return count;
}
}
}