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

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

@@ -3,19 +3,18 @@ using UnityEngine;
public class VehicleInteraction : MonoBehaviour, IInteractable
{
[Header("Setup")]
[SerializeField] private Transform exitPoint;
[SerializeField] private Transform exitPoint;
[SerializeField] private UIManager uiManager;
private CarOrbitCamera globalCarCamera; // Ссылка на глобальную камеру
private CarOrbitCamera globalCarCamera;
private CarController carController;
private GameObject playerInstance;
public bool isPlayerInside = false;
[HideInInspector] public bool isPlayerInside;
private void Awake()
{
carController = GetComponent<CarController>();
// Автоматически находим камеру на сцене, даже если она выключена
carController = GetComponent<CarController>() ?? GetComponentInChildren<CarController>() ?? GetComponentInParent<CarController>();
if (uiManager == null) uiManager = FindAnyObjectByType<UIManager>();
globalCarCamera = FindAnyObjectByType<CarOrbitCamera>(FindObjectsInactive.Include);
}
@@ -24,48 +23,50 @@ public class VehicleInteraction : MonoBehaviour, IInteractable
if (!isPlayerInside) EnterVehicle(interactor);
}
public string GetPrompt()
{
return "Сесть в машину (E)";
}
public string GetPrompt() => "[F] Сесть в машину";
private void EnterVehicle(GameObject player)
{
isPlayerInside = true;
playerInstance = player;
playerInstance.SetActive(false);
// Передаем этой машине фокус и включаем камеру
if (globalCarCamera != null)
{
globalCarCamera.SetTarget(transform);
globalCarCamera.gameObject.SetActive(true);
}
if (uiManager != null) uiManager.ToggleDashboard(true);
if (uiManager != null)
{
uiManager.HidePrompt();
uiManager.ToggleDashboard(true);
}
}
private void ExitVehicle()
{
isPlayerInside = false;
carController.ProcessInput(0f, 0f, true);
// Отвязываем цель и выключаем камеру авто
if (carController != null) carController.ProcessInput(0f, 0f, true);
if (globalCarCamera != null)
{
globalCarCamera.SetTarget(null);
globalCarCamera.gameObject.SetActive(false);
}
if (uiManager != null) uiManager.ToggleDashboard(false);
CharacterController charController = playerInstance.GetComponent<CharacterController>();
if (charController != null) charController.enabled = false;
playerInstance.transform.position = exitPoint.position;
if (exitPoint != null)
playerInstance.transform.position = exitPoint.position;
else
playerInstance.transform.position = transform.position - transform.right * 1.8f + Vector3.up * 0.5f;
if (charController != null) charController.enabled = true;
playerInstance.SetActive(true);
playerInstance = null;
}
@@ -74,14 +75,17 @@ public class VehicleInteraction : MonoBehaviour, IInteractable
{
if (!isPlayerInside) return;
float vertical = Input.GetAxis("Vertical");
float horizontal = Input.GetAxis("Horizontal");
bool isBraking = Input.GetKey(KeyCode.Space);
if (carController != null)
{
float vertical = Input.GetAxis("Vertical");
float horizontal = Input.GetAxis("Horizontal");
bool isBraking = Input.GetKey(KeyCode.Space);
carController.ProcessInput(vertical, horizontal, isBraking);
carController.ProcessInput(vertical, horizontal, isBraking);
if (uiManager != null) uiManager.UpdateSpeed(carController.SpeedKmH);
}
if (uiManager != null) uiManager.UpdateSpeed(carController.SpeedKmH);
if (Input.GetKeyDown(KeyCode.E)) ExitVehicle();
if (Input.GetKeyDown(KeyCode.F) || Input.GetKeyDown(KeyCode.E))
ExitVehicle();
}
}
+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;
}
}
}
+37 -29
View File
@@ -17,41 +17,51 @@ public class CarPartMountZone : MonoBehaviour, IInteractable
gameObject.layer = part.gameObject.layer;
cachedHands = FindAnyObjectByType<PlayerHands>();
// Проверяем, есть ли у детали собственные физические болты (например, у колеса)
hasSeparateBolts = part.GetComponentsInChildren<WheelBolt>(true).Length > 0;
if (part.Data != null && part.Data.boltDuration > 0f)
mountDuration = part.Data.boltDuration;
// 1. Копируем коллайдер детали
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
MeshFilter sourceFilter = part.GetComponentInChildren<MeshFilter>();
// Для колеса создаем удобную широкую сферу вокруг ступицы, чтобы луч всегда попадал с первого раза
if (hasSeparateBolts)
{
SphereCollider sphere = gameObject.AddComponent<SphereCollider>();
sphere.radius = 0.6f;
if (sourceFilter != null && sourceFilter.sharedMesh != null)
sphere.center = sourceFilter.sharedMesh.bounds.center;
sphere.radius = 0.48f;
sphere.isTrigger = true;
zoneCollider = sphere;
}
else
{
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;
}
}
// 2. Создаем 3D-силуэт (Ghost) места установки из CarPartData
MeshFilter sourceFilter = part.GetComponentInChildren<MeshFilter>();
if (sourceFilter != null && sourceFilter.sharedMesh != null)
{
MeshFilter mf = gameObject.AddComponent<MeshFilter>();
@@ -106,18 +116,17 @@ public class CarPartMountZone : MonoBehaviour, IInteractable
string partTitle = targetPart.Data != null ? targetPart.Data.partName : "Деталь";
// Если у детали есть отдельные болты (колесо) — ставим на ступицу сразу по нажатию E
// Колесо надевается на ступицу сразу при нажатии E или ЛКМ
if (hasSeparateBolts)
{
if (Input.GetKeyDown(KeyCode.E))
if (Input.GetKeyDown(KeyCode.E) || Input.GetMouseButtonDown(0))
{
CompleteInstall();
return string.Empty;
}
return $"[E] Надеть {partTitle} на ступицу";
return $"[E / ЛКМ] Надеть {partTitle} на ступицу";
}
// Для остальных деталей (бамперы, крылья, капот) — закручиваем болты удержанием E
if (Input.GetKey(KeyCode.E))
{
currentMountProgress += Time.deltaTime;
@@ -140,7 +149,6 @@ public class CarPartMountZone : MonoBehaviour, IInteractable
public void Interact(GameObject interactor)
{
// Если PlayerInteractor вызвал одиночный клик для колеса — сразу надеваем его
if (hasSeparateBolts && cachedHands != null && cachedHands.IsHolding && cachedHands.CurrentPart == targetPart)
{
CompleteInstall();
@@ -1,170 +0,0 @@
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class AdvancedCarController : MonoBehaviour
{
public float SpeedKmH => rb.linearVelocity.magnitude * 3.6f;
[Header("Данные авто")]
[SerializeField] private CarPhysicsData data;
[Header("Колеса (WheelColliders)")]
[SerializeField] private WheelCollider[] frontWheels;
[SerializeField] private WheelCollider[] rearWheels;
[Header("Состояние деталей (Для диплома)")]
[Range(0.1f, 1f)] public float engineCondition = 1f; // 1 - новое, 0.1 - убитое (не тянет)
[Range(0.1f, 1f)] public float tiresCondition = 1f; // Влияет на держак резины
// Состояние авто
public float CurrentSpeedKmH => rb.linearVelocity.magnitude * 3.6f;
public float EngineRPM { get; private set; }
public int CurrentGear { get; private set; }
private Rigidbody rb;
private float currentSteerAngle;
private WheelFrictionCurve originalRearSidewaysFriction;
// Ввод
private float moveInput, steerInput;
private bool isBraking, isHandbrake;
private void Awake()
{
rb = GetComponent<Rigidbody>();
rb.centerOfMass = data.centerOfMassOffset; // Понижаем центр масс для стабильности
// Запоминаем оригинальное трение для ручника
if (rearWheels.Length > 0)
originalRearSidewaysFriction = rearWheels[0].sidewaysFriction;
}
private void Update()
{
// Чтение инпута (можно заменить на новый Input System)
moveInput = Input.GetAxis("Vertical");
steerInput = Input.GetAxis("Horizontal");
isBraking = Input.GetKey(KeyCode.Space) || (moveInput < 0 && CurrentSpeedKmH > 5f);
isHandbrake = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.Space);
}
private void FixedUpdate()
{
ApplySteering();
ProcessEngineAndGears();
ApplyAntiRollBar();
ProcessHandbrake();
}
public void ProcessInput(float vertical, float horizontal, bool handbrake)
{
moveInput = vertical;
steerInput = horizontal;
isHandbrake = handbrake;
}
private void ApplySteering()
{
// 1. Угол зависит от скорости (на 100 км/ч руль не вывернется на 35 градусов)
float speedMultiplier = data.steerAngleBySpeed.Evaluate(CurrentSpeedKmH);
float targetSteer = steerInput * data.maxSteerAngle * speedMultiplier;
// 2. Сглаживание поворота (руль не дергается мгновенно)
currentSteerAngle = Mathf.Lerp(currentSteerAngle, targetSteer, Time.fixedDeltaTime * data.steerSmoothing);
foreach (var wheel in frontWheels)
{
wheel.steerAngle = currentSteerAngle;
}
}
private void ProcessEngineAndGears()
{
// Считаем средние обороты ведущих колес (допустим, задний привод)
float wheelRPM = 0;
foreach (var w in rearWheels) wheelRPM += Mathf.Abs(w.rpm);
wheelRPM /= rearWheels.Length;
// Вычисляем обороты двигателя через передаточные числа
float gearRatio = data.gearRatios[CurrentGear];
EngineRPM = Mathf.Clamp(wheelRPM * gearRatio * data.finalDrive, data.minRPM, data.maxRPM);
// Автоматическая коробка передач
if (EngineRPM > data.shiftUpRPM && CurrentGear < data.gearRatios.Length - 1)
CurrentGear++;
else if (EngineRPM < data.shiftDownRPM && CurrentGear > 0)
CurrentGear--;
// Получаем крутящий момент по графику и умножаем на состояние двигателя!
float motorTorque = data.torqueCurve.Evaluate(EngineRPM) * gearRatio * data.finalDrive;
float finalTorque = moveInput * motorTorque * engineCondition;
// Применяем газ или тормоз
foreach (var wheel in rearWheels)
{
if (isBraking)
{
wheel.motorTorque = 0;
wheel.brakeTorque = data.brakeForce;
}
else
{
wheel.motorTorque = finalTorque / rearWheels.Length;
wheel.brakeTorque = 0;
}
}
}
private void ProcessHandbrake()
{
foreach (var wheel in rearWheels)
{
if (isHandbrake)
{
wheel.brakeTorque = data.brakeForce;
// ДРИФТ: Уменьшаем боковое сцепление, умножая на износ шин
WheelFrictionCurve fc = wheel.sidewaysFriction;
fc.stiffness = originalRearSidewaysFriction.stiffness * data.handbrakeFrictionMultiplier * tiresCondition;
wheel.sidewaysFriction = fc;
}
else if (!isBraking)
{
wheel.brakeTorque = 0;
// Возвращаем обычное сцепление с поправкой на убитость шин
WheelFrictionCurve fc = wheel.sidewaysFriction;
fc.stiffness = originalRearSidewaysFriction.stiffness * tiresCondition;
wheel.sidewaysFriction = fc;
}
}
}
private void ApplyAntiRollBar()
{
// Стабилизатор поперечной устойчивости для передней и задней оси
ApplyAxleAntiRoll(frontWheels[0], frontWheels[1]);
ApplyAxleAntiRoll(rearWheels[0], rearWheels[1]);
}
private void ApplyAxleAntiRoll(WheelCollider left, WheelCollider right)
{
float travelL = 1.0f;
float travelR = 1.0f;
bool groundedL = left.GetGroundHit(out WheelHit hitL);
if (groundedL) travelL = (-left.transform.InverseTransformPoint(hitL.point).y - left.radius) / left.suspensionDistance;
bool groundedR = right.GetGroundHit(out WheelHit hitR);
if (groundedR) travelR = (-right.transform.InverseTransformPoint(hitR.point).y - right.radius) / right.suspensionDistance;
// Разница сжатия подвески
float antiRollVal = (travelL - travelR) * data.antiRollForce;
// Применяем противодействующую силу (прижимаем поднявшееся колесо)
if (groundedL) rb.AddForceAtPosition(left.transform.up * -antiRollVal, left.transform.position);
if (groundedR) rb.AddForceAtPosition(right.transform.up * antiRollVal, right.transform.position);
}
}
@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: c02b03f912164de9ae5c7659d886fae9
timeCreated: 1791809782
+162 -117
View File
@@ -2,29 +2,29 @@ using UnityEngine;
public enum DriveType { FWD, RWD, AWD }
[RequireComponent(typeof(Rigidbody))]
public class CarController : MonoBehaviour
{
public float SpeedKmH => rb.linearVelocity.magnitude * 3.6f;
[Header("Drive Settings")]
public float SpeedKmH => rb != null ? rb.linearVelocity.magnitude * 3.6f : 0f;
[Header("Аркадные настройки движения")]
public DriveType driveType = DriveType.AWD;
[SerializeField] private float motorForce = 1500f;
[SerializeField] private float brakeForce = 3000f;
[SerializeField] private float maxSteerAngle = 30f;
[SerializeField] private float motorForce = 2200f;
[SerializeField] private float maxSpeedKmH = 160f;
[SerializeField] private float brakeForce = 4500f;
[Header("Grip Settings (Friction Stiffness)")]
[Tooltip("Сцепление для переднего привода (FWD)")]
[SerializeField] private float fwdFrontGrip = 1.2f;
[SerializeField] private float fwdRearGrip = 2.0f;
[Header("Рулевое управление")]
[SerializeField] private float maxSteerAngle = 32f;
[SerializeField] private float steerSpeed = 8f;
[Tooltip("Во сколько раз уменьшается выворот руля на максимальной скорости")]
[SerializeField] private float highSpeedSteerFactor = 0.35f;
[Tooltip("Сцепление для заднего привода (RWD)")]
[SerializeField] private float rwdFrontGrip = 2.0f;
[SerializeField] private float rwdRearGrip = 1.2f;
[Header("Устойчивость и Дрифт")]
[SerializeField] private Vector3 centerOfMassOffset = new Vector3(0f, -0.45f, 0f);
[SerializeField] private float antiRollForce = 8000f;
[SerializeField] private float normalGrip = 2.2f;
[SerializeField] private float handbrakeRearGrip = 0.65f;
[Tooltip("Сцепление для полного привода (AWD)")]
[SerializeField] private float awdFrontGrip = 2.5f;
[SerializeField] private float awdRearGrip = 2.5f;
[Header("Wheel Colliders")]
[SerializeField] private WheelCollider frontLeftCollider;
[SerializeField] private WheelCollider frontRightCollider;
@@ -38,15 +38,41 @@ public class CarController : MonoBehaviour
[SerializeField] private Transform rearRightMesh;
private Rigidbody rb;
// Входящие данные от игрока
private float inputVertical;
private float inputHorizontal;
private bool inputHandbrake;
private float currentSteerAngle;
private void Start()
private void Awake()
{
rb = GetComponent<Rigidbody>();
rb.centerOfMass = centerOfMassOffset;
rb.angularDamping = 1.5f;
SetupArcadeWheel(frontLeftCollider);
SetupArcadeWheel(frontRightCollider);
SetupArcadeWheel(rearLeftCollider);
SetupArcadeWheel(rearRightCollider);
}
private void SetupArcadeWheel(WheelCollider wc)
{
if (wc == null) return;
JointSpring spring = wc.suspensionSpring;
spring.spring = 35000f;
spring.damper = 4500f;
spring.targetPosition = 0.5f;
wc.suspensionSpring = spring;
wc.suspensionDistance = 0.18f;
WheelFrictionCurve fwd = wc.forwardFriction;
fwd.stiffness = 2.0f;
wc.forwardFriction = fwd;
WheelFrictionCurve side = wc.sidewaysFriction;
side.stiffness = normalGrip;
wc.sidewaysFriction = side;
}
public void ProcessInput(float vertical, float horizontal, bool handbrake)
@@ -60,117 +86,138 @@ public class CarController : MonoBehaviour
{
HandleSteering();
HandleMotorAndBrakes();
ApplyAntiRoll(frontLeftCollider, frontRightCollider);
ApplyAntiRoll(rearLeftCollider, rearRightCollider);
UpdateWheelPoses();
}
private void HandleSteering()
{
float steerAngle = maxSteerAngle * inputHorizontal;
frontLeftCollider.steerAngle = steerAngle;
frontRightCollider.steerAngle = steerAngle;
float speedFactor = Mathf.Lerp(1f, highSpeedSteerFactor, SpeedKmH / maxSpeedKmH);
float targetSteer = inputHorizontal * maxSteerAngle * speedFactor;
currentSteerAngle = Mathf.Lerp(currentSteerAngle, targetSteer, Time.fixedDeltaTime * steerSpeed);
if (frontLeftCollider != null) frontLeftCollider.steerAngle = currentSteerAngle;
if (frontRightCollider != null) frontRightCollider.steerAngle = currentSteerAngle;
}
private void HandleMotorAndBrakes()
{
float currentMotorTorque = 0f;
float currentBrakeTorque = 0f;
float localVelZ = transform.InverseTransformDirection(rb.linearVelocity).z;
float motor = 0f;
float brake = 0f;
// Определяем, куда физически движется машина (вперед или назад)
float localVelocityZ = transform.InverseTransformDirection(rb.linearVelocity).z;
// ЛОГИКА ГАЗА (W)
if (inputVertical > 0)
if (inputVertical > 0.01f)
{
if (localVelocityZ < -1f) // Если катимся назад, а жмем W -> Тормозим
currentBrakeTorque = brakeForce;
else // Иначе едем вперед
currentMotorTorque = inputVertical * motorForce;
if (localVelZ < -1.5f)
brake = brakeForce;
else if (SpeedKmH < maxSpeedKmH)
motor = inputVertical * motorForce;
}
// ЛОГИКА ТОРМОЗА И ЗАДНЕГО ХОДА (S)
else if (inputVertical < 0)
else if (inputVertical < -0.01f)
{
if (localVelocityZ > 1f) // Если едем вперед, а жмем S -> Тормозим
currentBrakeTorque = brakeForce;
else // Иначе сдаем назад (inputVertical отрицательный, поэтому момент тоже отрицательный)
currentMotorTorque = inputVertical * motorForce;
}
// ЛОГИКА РУЧНИКА (Пробел)
if (inputHandbrake)
{
currentMotorTorque = 0f; // Глушим газ
currentBrakeTorque = brakeForce * 2f; // Ручник хватает сильнее обычного тормоза
}
ApplyBrakes(currentBrakeTorque, inputHandbrake);
ApplyMotor(currentMotorTorque);
}
private void ApplyMotor(float torque)
{
// Получаем базовые настройки трения
WheelFrictionCurve frontFriction = frontLeftCollider.sidewaysFriction;
WheelFrictionCurve rearFriction = rearLeftCollider.sidewaysFriction;
switch (driveType)
{
case DriveType.FWD:
frontLeftCollider.motorTorque = torque;
frontRightCollider.motorTorque = torque;
rearLeftCollider.motorTorque = 0;
rearRightCollider.motorTorque = 0;
frontFriction.stiffness = fwdFrontGrip;
rearFriction.stiffness = fwdRearGrip;
break;
case DriveType.RWD:
frontLeftCollider.motorTorque = 0;
frontRightCollider.motorTorque = 0;
rearLeftCollider.motorTorque = torque;
rearRightCollider.motorTorque = torque;
frontFriction.stiffness = rwdFrontGrip;
rearFriction.stiffness = rwdRearGrip;
break;
case DriveType.AWD:
float halfTorque = torque / 2f;
frontLeftCollider.motorTorque = halfTorque;
frontRightCollider.motorTorque = halfTorque;
rearLeftCollider.motorTorque = halfTorque;
rearRightCollider.motorTorque = halfTorque;
frontFriction.stiffness = awdFrontGrip;
rearFriction.stiffness = awdRearGrip;
break;
}
// Применяем измененное трение к колесам
frontLeftCollider.sidewaysFriction = frontFriction;
frontRightCollider.sidewaysFriction = frontFriction;
rearLeftCollider.sidewaysFriction = rearFriction;
rearRightCollider.sidewaysFriction = rearFriction;
}
private void ApplyBrakes(float brake, bool isHandbrake)
{
if (isHandbrake)
{
// Ручник блокирует только задние колеса (эффект заноса)
frontLeftCollider.brakeTorque = 0;
frontRightCollider.brakeTorque = 0;
rearLeftCollider.brakeTorque = brake;
rearRightCollider.brakeTorque = brake;
if (localVelZ > 1.5f)
brake = brakeForce;
else if (SpeedKmH < 45f)
motor = inputVertical * motorForce * 0.7f;
}
else
{
// Обычный тормоз (S) срабатывает на все колеса, передок сильнее
frontLeftCollider.brakeTorque = brake;
frontRightCollider.brakeTorque = brake;
rearLeftCollider.brakeTorque = brake * 0.5f;
rearRightCollider.brakeTorque = brake * 0.5f;
// Плавное торможение двигателем, когда газ отпущен
brake = 150f;
}
if (inputHandbrake)
{
motor = 0f;
brake = brakeForce * 1.5f;
}
ApplyDriveTorque(motor);
ApplyBrakesAndDrift(brake, inputHandbrake);
}
private void ApplyDriveTorque(float torque)
{
if (driveType == DriveType.FWD)
{
SetMotor(frontLeftCollider, torque);
SetMotor(frontRightCollider, torque);
SetMotor(rearLeftCollider, 0f);
SetMotor(rearRightCollider, 0f);
}
else if (driveType == DriveType.RWD)
{
SetMotor(frontLeftCollider, 0f);
SetMotor(frontRightCollider, 0f);
SetMotor(rearLeftCollider, torque);
SetMotor(rearRightCollider, torque);
}
else
{
float half = torque * 0.55f;
SetMotor(frontLeftCollider, half);
SetMotor(frontRightCollider, half);
SetMotor(rearLeftCollider, half);
SetMotor(rearRightCollider, half);
}
}
private void SetMotor(WheelCollider wc, float val)
{
if (wc != null && wc.enabled) wc.motorTorque = val;
}
private void ApplyBrakesAndDrift(float brake, bool handbrake)
{
float targetRearStiffness = handbrake ? handbrakeRearGrip : normalGrip;
SetRearGrip(rearLeftCollider, targetRearStiffness);
SetRearGrip(rearRightCollider, targetRearStiffness);
if (handbrake)
{
if (frontLeftCollider != null) frontLeftCollider.brakeTorque = 0f;
if (frontRightCollider != null) frontRightCollider.brakeTorque = 0f;
if (rearLeftCollider != null) rearLeftCollider.brakeTorque = brake;
if (rearRightCollider != null) rearRightCollider.brakeTorque = brake;
}
else
{
if (frontLeftCollider != null) frontLeftCollider.brakeTorque = brake;
if (frontRightCollider != null) frontRightCollider.brakeTorque = brake;
if (rearLeftCollider != null) rearLeftCollider.brakeTorque = brake * 0.6f;
if (rearRightCollider != null) rearRightCollider.brakeTorque = brake * 0.6f;
}
}
private void SetRearGrip(WheelCollider wc, float targetStiff)
{
if (wc == null) return;
WheelFrictionCurve side = wc.sidewaysFriction;
side.stiffness = Mathf.Lerp(side.stiffness, targetStiff, Time.fixedDeltaTime * 10f);
wc.sidewaysFriction = side;
}
private void ApplyAntiRoll(WheelCollider left, WheelCollider right)
{
if (left == null || right == null || !left.enabled || !right.enabled) return;
float travelL = 1f;
float travelR = 1f;
bool groundedL = left.GetGroundHit(out WheelHit hitL);
if (groundedL)
travelL = (-left.transform.InverseTransformPoint(hitL.point).y - left.radius) / left.suspensionDistance;
bool groundedR = right.GetGroundHit(out WheelHit hitR);
if (groundedR)
travelR = (-right.transform.InverseTransformPoint(hitR.point).y - right.radius) / right.suspensionDistance;
float force = (travelL - travelR) * antiRollForce;
if (groundedL) rb.AddForceAtPosition(left.transform.up * -force, left.transform.position);
if (groundedR) rb.AddForceAtPosition(right.transform.up * force, right.transform.position);
}
private void UpdateWheelPoses()
@@ -183,9 +230,7 @@ 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);
@@ -1,28 +0,0 @@
using UnityEngine;
[CreateAssetMenu(fileName = "NewCarPhysics", menuName = "Car System/Physics Data")]
public class CarPhysicsData : ScriptableObject
{
[Header("Двигатель и КПП")]
public AnimationCurve torqueCurve; // Кривая: X - обороты (RPM), Y - крутящий момент (Nm)
public float maxRPM = 7000f;
public float minRPM = 800f;
public float shiftUpRPM = 6000f;
public float shiftDownRPM = 2500f;
public float[] gearRatios = { 3.1f, 2.2f, 1.6f, 1.2f, 0.9f, 0.7f };
public float finalDrive = 3.4f;
[Header("Рулевое управление")]
public float maxSteerAngle = 35f;
public float steerSmoothing = 10f; // Скорость поворота руля
[Tooltip("Как сильно режется угол поворота на высокой скорости")]
public AnimationCurve steerAngleBySpeed; // X - скорость (км/ч), Y - множитель угла (0..1)
[Header("Подвеска и физика")]
public Vector3 centerOfMassOffset = new Vector3(0, -0.2f, 0); // Пониженный центр масс
public float antiRollForce = 5000f; // Стабилизатор поперечной устойчивости
public float brakeForce = 3000f;
[Header("Дрифт (Ручник)")]
public float handbrakeFrictionMultiplier = 0.3f; // Насколько скользкой становится задняя ось
}
@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 396086e692304e97aab2b9b09066d2b5
timeCreated: 1791809619
@@ -1,56 +0,0 @@
using UnityEngine;
[ExecuteInEditMode]
public class EasySuspension : MonoBehaviour
{
[Range(0.1f, 20f)] public float naturalFrequency = 10f;
[Range(0.1f, 3f)] public float dampingRatio = 0.8f;
[Range(-1f, 1f)] public float forceShift = 0.03f;
public bool setSuspensionDistance = true;
private WheelCollider[] wheelColliders;
private Rigidbody rb;
private void Awake()
{
CacheComponents();
}
private void CacheComponents()
{
wheelColliders = GetComponentsInChildren<WheelCollider>(true);
rb = GetComponent<Rigidbody>();
}
private void Update()
{
if (wheelColliders == null || rb == null)
{
CacheComponents();
if (wheelColliders == null || rb == null) return;
}
foreach (WheelCollider wc in wheelColliders)
{
// ЗАЩИТА: если колесо снято (выключено) или не несет нагрузки — пропускаем, чтобы не делить на 0!
if (wc == null || !wc.enabled || wc.sprungMass <= 0.01f) continue;
JointSpring spring = wc.suspensionSpring;
spring.spring = Mathf.Pow(Mathf.Sqrt(wc.sprungMass) * naturalFrequency, 2);
spring.damper = 2f * 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.001f && spring.spring > 0.001f && setSuspensionDistance)
{
wc.suspensionDistance = wc.sprungMass * Physics.gravity.magnitude / (spring.targetPosition * spring.spring);
}
}
}
}
@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 4d9eeaad380562f42bac8b304778252c
@@ -1,29 +0,0 @@
using UnityEngine;
public class WheelVisuals : MonoBehaviour
{
[System.Serializable]
public struct WheelPair
{
public WheelCollider collider;
public Transform mesh;
}
[Header("Привязка колес")]
public WheelPair[] wheels;
private void Update()
{
foreach (var w in wheels)
{
if (w.collider == null || w.mesh == null) continue;
// Получаем физическую позицию колеса
w.collider.GetWorldPose(out Vector3 pos, out Quaternion rot);
// Применяем к 3D-модели
w.mesh.position = pos;
w.mesh.rotation = rot;
}
}
}
@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: ce1b65bf09494194a68749d417b0e17a
timeCreated: 1791809850
+253 -214
View File
@@ -13,17 +13,10 @@ public class CarJack : MonoBehaviour, IInteractable
[SerializeField] private Transform screw;
[SerializeField] private Transform topPlate;
[Header("Настройки анимации ромба")]
[Tooltip("Локальная ось вращения лап: (0,0,1), (0,1,0) или (1,0,0)")]
[SerializeField] private Vector3 armRotationAxis = Vector3.forward;
[Tooltip("Локальная ось вращения винта")]
[SerializeField] private Vector3 screwSpinAxis = Vector3.right;
[SerializeField] private float maxFoldAngle = 24f;
[SerializeField] private float liftDuration = 2.5f;
[Header("Настройки подъема авто")]
[Tooltip("На сколько метров поднимается порог после касания домкрата (0.08 = 8 см)")]
[SerializeField] private float carLiftHeight = 0.08f;
[Header("Настройки подъема")]
[SerializeField] private float liftDuration = 2.0f;
[Tooltip("На сколько метров поднимается порог (0.28 = 28 см, чтобы колесо легко вставало на место)")]
[SerializeField] private float carLiftHeight = 0.28f;
[Header("Позиционирование и материалы")]
[SerializeField] private Material ghostMaterial;
@@ -35,33 +28,32 @@ public class CarJack : MonoBehaviour, IInteractable
private JackState currentState = JackState.OnFloor;
private BoxCollider mainCollider;
private Collider[] allJackColliders;
private Rigidbody jackRb;
private Transform holderCamera;
private Transform playerRoot;
private UIManager uiManager;
private int stateChangeFrame = -1;
private Quaternion bArmL_OpenRot, bArmR_OpenRot;
private Quaternion tArmL_OpenRot, tArmR_OpenRot;
private float foldSignL = 1f;
private float foldSignR = -1f;
private float screwSpinAngle = 0f;
private Vector3 originalLocalScale;
private Transform diamondPivot;
private Vector3 topPlateInitLocalPos;
private Vector3 screwInitLocalPos;
private Quaternion screwInitLocalRot;
private Vector3 originalRootScale;
private float modelFullHeight = 0.32f;
private MeshRenderer[] renderers;
private Material[] originalMaterials;
private bool isShowingGhost = false;
// Привязка к автомобилю
// Физический подъемник на базе ConfigurableJoint (дает 100% плавный подъем без дрожи!)
private Rigidbody targetCarRb;
private CarPart targetWheelPart;
private WheelCollider targetWheelCollider;
private WheelCollider[] allCarWheels;
private Vector3 carLocalLiftPoint;
private GameObject supportAnchorObj;
private Rigidbody supportAnchorRb;
private ConfigurableJoint liftJoint;
private float initialSillWorldY;
// Превью установки
private bool canPlaceUnderCar = false;
private Vector3 previewWorldPos;
private Quaternion previewWorldRot;
@@ -72,22 +64,18 @@ public class CarJack : MonoBehaviour, IInteractable
private bool isHoveredThisFrame = false;
public static CarJack ActiveJackInHand { get; private set; }
public JackState State => currentState;
public bool IsLifted => currentState == JackState.PlacedUnderCar && liftProgress >= 0.85f;
public bool IsLifted => currentState == JackState.PlacedUnderCar && liftProgress >= 0.70f;
public static bool IsWheelLifted(Transform wheelTransform)
{
if (wheelTransform == null) return false;
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) < 1.8f)
if (Vector3.Distance(jack.transform.position, wheelTransform.position) < 2.0f)
return true;
}
return false;
@@ -96,49 +84,107 @@ public class CarJack : MonoBehaviour, IInteractable
private void Awake()
{
uiManager = FindAnyObjectByType<UIManager>();
originalLocalScale = transform.localScale;
originalRootScale = transform.localScale;
mainCollider = GetComponent<BoxCollider>();
allJackColliders = GetComponentsInChildren<Collider>(true);
// Отключаем лишние дочерние коллайдеры на лапах, оставляя один главный BoxCollider на базе
foreach (var c in allJackColliders)
{
foreach (var c in GetComponentsInChildren<Collider>(true))
if (c != mainCollider) c.enabled = false;
}
renderers = GetComponentsInChildren<MeshRenderer>(true);
originalMaterials = new Material[renderers.Length];
for (int i = 0; i < renderers.Length; i++)
originalMaterials[i] = renderers[i].sharedMaterial;
if (bottomArmL != null && topArmL != null && topArmL.parent != bottomArmL)
topArmL.SetParent(bottomArmL, true);
if (bottomArmR != null && topArmR != null && topArmR.parent != bottomArmR)
topArmR.SetParent(bottomArmR, true);
// Автоматически выравниваем BoxCollider по реальным габаритам модели,
// чтобы его дно не торчало ниже подошвы домкрата
FitColliderToRenderers();
if (bottomArmL != null) bArmL_OpenRot = bottomArmL.localRotation;
if (bottomArmR != null) bArmR_OpenRot = bottomArmR.localRotation;
if (topArmL != null) tArmL_OpenRot = topArmL.localRotation;
if (topArmR != null) tArmR_OpenRot = topArmR.localRotation;
AutoDetectFoldDirections();
SetupUnifiedDiamondRig();
UpdateJackPose();
}
private void AutoDetectFoldDirections()
private void FitColliderToRenderers()
{
if (bottomArmL == null || topArmL == null || bottomArmR == null || topArmR == null) return;
if (mainCollider == null || renderers == null || renderers.Length == 0) return;
float openYL = topArmL.position.y;
bottomArmL.localRotation = bArmL_OpenRot * Quaternion.Euler(armRotationAxis * 5f);
foldSignL = (topArmL.position.y < openYL) ? 1f : -1f;
bottomArmL.localRotation = bArmL_OpenRot;
Quaternion savedRot = transform.rotation;
transform.rotation = Quaternion.identity;
float openYR = topArmR.position.y;
bottomArmR.localRotation = bArmR_OpenRot * Quaternion.Euler(armRotationAxis * 5f);
foldSignR = (topArmR.position.y < openYR) ? 1f : -1f;
bottomArmR.localRotation = bArmR_OpenRot;
Bounds worldBounds = new Bounds(transform.position, Vector3.zero);
bool hasBounds = false;
foreach (var r in renderers)
{
if (r == null) continue;
if (!hasBounds) { worldBounds = r.bounds; hasBounds = true; }
else worldBounds.Encapsulate(r.bounds);
}
if (hasBounds)
{
Vector3 localCenter = transform.InverseTransformPoint(worldBounds.center);
Vector3 localSize = new Vector3(
worldBounds.size.x / Mathf.Max(0.001f, transform.lossyScale.x),
worldBounds.size.y / Mathf.Max(0.001f, transform.lossyScale.y),
worldBounds.size.z / Mathf.Max(0.001f, transform.lossyScale.z)
);
// Задаем минимальную толщину, чтобы физика надежно держала домкрат на асфальте
localSize.x = Mathf.Max(localSize.x, 0.25f);
localSize.y = Mathf.Max(localSize.y, 0.20f);
localSize.z = Mathf.Max(localSize.z, 0.35f);
// Дно коллайдера никогда не опускается ниже 0 (подошвы домкрата)
localCenter.y = Mathf.Max(localCenter.y, localSize.y * 0.5f);
mainCollider.center = localCenter;
mainCollider.size = localSize;
}
transform.rotation = savedRot;
}
private void OnDestroy()
{
DestroyLiftJoint();
}
private void SetupUnifiedDiamondRig()
{
Bounds b = new Bounds(transform.position, Vector3.zero);
bool hasBounds = false;
foreach (var r in renderers)
{
if (r == null) continue;
if (!hasBounds) { b = r.bounds; hasBounds = true; }
else b.Encapsulate(r.bounds);
}
modelFullHeight = hasBounds ? Mathf.Max(0.15f, b.size.y / transform.lossyScale.y) : 0.32f;
GameObject pivotObj = new GameObject("DiamondRigPivot");
diamondPivot = pivotObj.transform;
diamondPivot.SetParent(transform, false);
diamondPivot.localPosition = Vector3.zero;
diamondPivot.localRotation = Quaternion.identity;
diamondPivot.localScale = Vector3.one;
if (bottomArmL != null) bottomArmL.SetParent(diamondPivot, true);
if (bottomArmR != null) bottomArmR.SetParent(diamondPivot, true);
if (topArmL != null) topArmL.SetParent(diamondPivot, true);
if (topArmR != null) topArmR.SetParent(diamondPivot, true);
if (topPlate != null)
{
topPlate.SetParent(transform, true);
topPlateInitLocalPos = topPlate.localPosition;
}
if (screw != null)
{
screw.SetParent(transform, true);
screwInitLocalPos = screw.localPosition;
screwInitLocalRot = screw.localRotation;
}
}
private void Update()
@@ -146,42 +192,30 @@ public class CarJack : MonoBehaviour, IInteractable
if (currentState != JackState.InHand) return;
UpdateInHandPreview();
if (Time.frameCount <= stateChangeFrame) return;
if (canPlaceUnderCar && (Input.GetKeyDown(KeyCode.E) || Input.GetMouseButtonDown(0)))
{
PlaceUnderCar();
}
else if (Input.GetKeyDown(KeyCode.G))
{
DropToFloor();
}
}
private void LateUpdate()
{
if (currentState == JackState.InHand)
{
if (uiManager != null)
uiManager.ShowPrompt(GetPlacementPrompt());
if (uiManager != null) uiManager.ShowPrompt(GetPlacementPrompt());
return;
}
if (currentState == JackState.PlacedUnderCar && isHoveredThisFrame && Time.frameCount > stateChangeFrame)
{
if (Input.GetKey(KeyCode.E))
{
ChangeLift(Time.deltaTime / liftDuration);
}
else if (Input.GetKey(KeyCode.R) && CanLowerSafely())
{
ChangeLift(-Time.deltaTime / liftDuration);
}
else if (liftProgress <= 0.01f && Input.GetKeyDown(KeyCode.G))
{
PickUpToHand(holderCamera, playerRoot);
}
}
isHoveredThisFrame = false;
@@ -189,48 +223,69 @@ public class CarJack : MonoBehaviour, IInteractable
private void FixedUpdate()
{
if (currentState != JackState.PlacedUnderCar || targetCarRb == null) return;
if (currentState != JackState.PlacedUnderCar || targetCarRb == null || supportAnchorRb == null) return;
// До 25% домкрат просто поднимает лапы до касания с порогом (машина стоит на месте!)
if (liftProgress <= 0.25f) return;
// Плавно перемещаем кинематическую точку опоры вверх-вниз вместе с верхушкой домкрата
float targetY = initialSillWorldY + liftProgress * carLiftHeight;
Vector3 targetAnchorPos = new Vector3(transform.position.x, targetY, transform.position.z);
supportAnchorRb.MovePosition(targetAnchorPos);
// Зажимаем тормоза на остальных колесах, чтобы машина не катилась на домкрате
if (allCarWheels != null)
if (liftProgress > 0.01f)
targetCarRb.WakeUp();
}
private void CreateLiftJoint(Vector3 contactWorld)
{
DestroyLiftJoint();
if (targetCarRb == null) return;
supportAnchorObj = new GameObject("JackPhysicsSupport");
supportAnchorObj.transform.position = contactWorld;
supportAnchorRb = supportAnchorObj.AddComponent<Rigidbody>();
supportAnchorRb.isKinematic = true;
supportAnchorRb.interpolation = RigidbodyInterpolation.Interpolate;
liftJoint = supportAnchorObj.AddComponent<ConfigurableJoint>();
liftJoint.connectedBody = targetCarRb;
liftJoint.autoConfigureConnectedAnchor = false;
liftJoint.anchor = Vector3.zero;
liftJoint.connectedAnchor = targetCarRb.transform.InverseTransformPoint(contactWorld);
// Разрешаем свободный наклон кузова, но плавно и жестко держим высоту точки опоры
liftJoint.xMotion = ConfigurableJointMotion.Free;
liftJoint.yMotion = ConfigurableJointMotion.Free;
liftJoint.zMotion = ConfigurableJointMotion.Free;
liftJoint.angularXMotion = ConfigurableJointMotion.Free;
liftJoint.angularYMotion = ConfigurableJointMotion.Free;
liftJoint.angularZMotion = ConfigurableJointMotion.Free;
JointDrive verticalDrive = new JointDrive
{
foreach (var wc in allCarWheels)
{
if (wc != null && wc.enabled) wc.brakeTorque = 4000f;
}
}
positionSpring = targetCarRb.mass * 180f,
positionDamper = targetCarRb.mass * 28f,
maximumForce = targetCarRb.mass * 60f
};
// Вычисляем плавный подъем порога строго вместе с верхней площадкой домкрата (topPlate)
float contactFactor = Mathf.InverseLerp(0.25f, 1f, liftProgress);
float targetSillY = topPlate != null
? topPlate.position.y
: (initialSillWorldY + contactFactor * carLiftHeight);
Vector3 currentSillWorld = targetCarRb.transform.TransformPoint(carLocalLiftPoint);
float heightError = targetSillY - currentSillWorld.y;
if (heightError > -0.01f)
JointDrive horizontalDrive = new JointDrive
{
float pointVelY = targetCarRb.GetPointVelocity(currentSillWorld).y;
float gravity = Physics.gravity.magnitude;
positionSpring = targetCarRb.mass * 25f,
positionDamper = targetCarRb.mass * 8f,
maximumForce = targetCarRb.mass * 20f
};
// Ограничиваем максимальную силу весом одного угла машины (42% от общей массы),
// чтобы домкрат физически не мог перевернуть или подбросить автомобиль!
float maxCornerWeight = targetCarRb.mass * gravity * 0.42f;
float springForce = heightError * (targetCarRb.mass * 85f);
float damperForce = pointVelY * (targetCarRb.mass * 16f);
liftJoint.yDrive = verticalDrive;
liftJoint.xDrive = horizontalDrive;
liftJoint.zDrive = horizontalDrive;
}
float upwardForce = Mathf.Clamp(springForce - damperForce, 0f, maxCornerWeight);
targetCarRb.AddForceAtPosition(Vector3.up * upwardForce, currentSillWorld, ForceMode.Force);
// Гасим паразитное раскачивание и сползание кузова
targetCarRb.angularVelocity *= 0.85f;
Vector3 horizVel = new Vector3(targetCarRb.linearVelocity.x, 0f, targetCarRb.linearVelocity.z);
targetCarRb.AddForce(-horizVel * (targetCarRb.mass * 8f), ForceMode.Force);
}
private void DestroyLiftJoint()
{
if (supportAnchorObj != null)
Destroy(supportAnchorObj);
supportAnchorObj = null;
supportAnchorRb = null;
liftJoint = null;
}
private bool CanLowerSafely()
@@ -252,25 +307,22 @@ public class CarJack : MonoBehaviour, IInteractable
if (currentState == JackState.PlacedUnderCar)
{
int percent = Mathf.RoundToInt(liftProgress * 100f);
if (!CanLowerSafely())
return $"Домкрат поднят ({percent}%)\n<color=yellow>Установите колесо и закрутите болты перед спуском!</color>";
return $"Домкрат поднят ({percent}%)\n<color=yellow>Наденьте колесо и закрутите болты перед спуском!</color>";
if (liftProgress <= 0.01f)
return "[Удерж. E] Поднимать авто | [G] Забрать домкрат";
return $"Домкрат ({percent}%)\n[Удерж. E] Поднять | [Удерж. R] Опустить";
}
return string.Empty;
}
public string GetPlacementPrompt()
{
if (canPlaceUnderCar)
return "[E / ЛКМ] Установить домкрат под порог | [G] Выбросить";
return "Наведите на колесо или под порог авто | [G] Выбросить домкрат";
return "[E / ЛКМ] Поставить домкрат под порог | [G] Выбросить";
return "Наведите на колесо или порог авто | [G] Выбросить домкрат";
}
public void Interact(GameObject interactor)
@@ -283,9 +335,7 @@ public class CarJack : MonoBehaviour, IInteractable
Camera cam = interactor.GetComponentInChildren<Camera>();
Transform camTr = cam != null ? cam.transform : FindAnyObjectByType<PlayerInteractor>()?.transform;
if (camTr != null)
{
PickUpToHand(camTr, interactor.transform.root);
}
}
}
@@ -294,6 +344,8 @@ public class CarJack : MonoBehaviour, IInteractable
if (camTransform == null) return;
if (ActiveJackInHand != null && ActiveJackInHand != this) return;
DestroyLiftJoint();
holderCamera = camTransform;
playerRoot = rootTransform;
ActiveJackInHand = this;
@@ -303,14 +355,13 @@ public class CarJack : MonoBehaviour, IInteractable
targetCarRb = null;
targetWheelPart = null;
targetWheelCollider = null;
allCarWheels = null;
liftProgress = 0f;
if (jackRb != null) Destroy(jackRb);
mainCollider.enabled = false;
transform.SetParent(holderCamera);
transform.localScale = originalLocalScale;
transform.localScale = originalRootScale;
transform.localPosition = inHandOffset;
transform.localRotation = Quaternion.Euler(inHandRotation);
UpdateJackPose();
@@ -364,19 +415,18 @@ public class CarJack : MonoBehaviour, IInteractable
if (carRb != null)
{
Transform carTr = carRb.transform;
Vector3 localWheel = carTr.InverseTransformPoint(closestWheel.transform.position);
float zOffset = -Mathf.Sign(localWheel.z) * 0.48f;
float sideSign = Mathf.Sign(localWheel.x);
if (sideSign == 0f) sideSign = 1f;
Vector3 localSill = new Vector3(localWheel.x * 0.92f, localWheel.y, localWheel.z + zOffset);
Vector3 localSill = new Vector3(localWheel.x * 0.94f, localWheel.y, localWheel.z + zOffset);
Vector3 worldSill = carTr.TransformPoint(localSill);
Vector3 groundPoint = worldSill;
groundPoint.y = closestWheel.transform.position.y - closestWheel.radius;
RaycastHit[] groundHits = Physics.RaycastAll(worldSill + Vector3.up * 0.5f, Vector3.down, 2.0f, ~0, QueryTriggerInteraction.Ignore);
RaycastHit[] groundHits = Physics.RaycastAll(worldSill + Vector3.up * 0.4f, Vector3.down, 2.0f, ~0, QueryTriggerInteraction.Ignore);
foreach (var gh in groundHits)
{
if (gh.collider.transform.IsChildOf(carTr)) continue;
@@ -416,9 +466,7 @@ public class CarJack : MonoBehaviour, IInteractable
private CarPart FindMatchingWheelPart(Transform carRoot, string wheelName)
{
foreach (CarPart p in carRoot.GetComponentsInChildren<CarPart>(true))
{
if (p.name == wheelName) return p;
}
return null;
}
@@ -430,79 +478,98 @@ public class CarJack : MonoBehaviour, IInteractable
SetGhostVisual(false);
transform.SetParent(null);
transform.localScale = originalLocalScale;
transform.position = previewWorldPos;
transform.rotation = previewWorldRot;
// ВАЖНО: делаем коллайдер ТРИГГЕРОМ, чтобы он не подбрасывал кузов машины!
mainCollider.enabled = true;
mainCollider.isTrigger = true;
targetCarRb = previewCarRb;
targetWheelPart = previewWheelPart;
targetWheelCollider = previewWheelCol;
allCarWheels = targetCarRb.GetComponentsInChildren<WheelCollider>(true);
// Находим точную высоту нижней кромки порога прямо над домкратом
float sillY = FindCarBottomYAboveJack(targetCarRb.transform);
initialSillWorldY = sillY;
float sillClearance = 0.16f;
if (targetWheelCollider != null)
{
float wheelBottomY = previewWorldPos.y;
float hubY = targetWheelCollider.transform.position.y;
sillClearance = Mathf.Clamp((hubY - wheelBottomY) * 0.58f, 0.12f, 0.22f);
}
Vector3 contactWorld = new Vector3(transform.position.x, sillY, transform.position.z);
carLocalLiftPoint = targetCarRb.transform.InverseTransformPoint(contactWorld);
initialSillWorldY = transform.position.y + sillClearance;
float maxTargetJackHeight = sillClearance + carLiftHeight;
float requiredScaleY = maxTargetJackHeight / Mathf.Max(0.1f, modelFullHeight);
transform.localScale = new Vector3(originalRootScale.x, requiredScaleY, originalRootScale.z);
Vector3 contactWorld = new Vector3(transform.position.x, initialSillWorldY, transform.position.z);
CreateLiftJoint(contactWorld);
liftProgress = 0f;
UpdateJackPose();
}
private float FindCarBottomYAboveJack(Transform carTr)
{
// Стреляем лучом снизу вверх из земли в порог машины, чтобы узнать точную высоту днища
Vector3 origin = transform.position + Vector3.down * 0.05f;
RaycastHit[] upHits = Physics.RaycastAll(origin, Vector3.up, 1.0f, ~0, QueryTriggerInteraction.Ignore);
float lowestCarY = float.MaxValue;
foreach (var h in upHits)
{
if (h.collider.transform.IsChildOf(carTr) && !(h.collider is WheelCollider))
{
if (h.point.y < lowestCarY)
lowestCarY = h.point.y;
}
}
if (lowestCarY < float.MaxValue)
return lowestCarY;
// Если на пороге нет коллайдера — берем уровень ступицы колеса минус 6 см
if (targetWheelCollider != null)
return targetWheelCollider.transform.position.y - 0.06f;
return transform.position.y + 0.16f;
}
private void DropToFloor()
{
ActiveJackInHand = null;
currentState = JackState.OnFloor;
stateChangeFrame = Time.frameCount;
SetGhostVisual(false);
{
DestroyLiftJoint();
ActiveJackInHand = null;
currentState = JackState.OnFloor;
stateChangeFrame = Time.frameCount;
SetGhostVisual(false);
transform.SetParent(null);
transform.localScale = originalLocalScale;
if (holderCamera != null)
transform.SetParent(null);
transform.localScale = originalRootScale;
if (holderCamera != null)
{
// 1. Вычисляем горизонтальную точку перед игроком (независимо от наклона камеры вниз)
Vector3 flatForward = Vector3.ProjectOnPlane(holderCamera.forward, Vector3.up).normalized;
if (flatForward.sqrMagnitude < 0.01f) flatForward = holderCamera.up;
Vector3 dropPos = holderCamera.position + flatForward * 1.1f;
// 2. Ищем уровень пола лучом сверху вниз, чтобы НИКОГДА не заспавнить домкрат под асфальтом
Vector3 rayStart = new Vector3(dropPos.x, holderCamera.position.y + 0.5f, dropPos.z);
RaycastHit[] hits = Physics.RaycastAll(rayStart, Vector3.down, 5.0f, ~0, QueryTriggerInteraction.Ignore);
float highestGroundY = float.MinValue;
foreach (var h in hits)
{
transform.position = holderCamera.position + holderCamera.forward * 1.2f;
transform.rotation = Quaternion.Euler(0f, holderCamera.eulerAngles.y, 0f);
if (h.collider.transform.IsChildOf(transform)) continue;
if (playerRoot != null && h.collider.transform.IsChildOf(playerRoot)) continue;
if (h.point.y > highestGroundY)
highestGroundY = h.point.y;
}
// На полу вне машины коллайдер твердый, чтобы домкрат лежал на асфальте
mainCollider.enabled = true;
mainCollider.isTrigger = false;
if (highestGroundY > float.MinValue)
{
// Ставим на 8 см выше найденного асфальта, чтобы домкрат мягко упал на него сверху
dropPos.y = highestGroundY + 0.08f;
}
else
{
dropPos.y = holderCamera.position.y - 0.3f;
}
jackRb = gameObject.AddComponent<Rigidbody>();
jackRb.mass = 8f;
transform.position = dropPos;
transform.rotation = Quaternion.Euler(0f, holderCamera.eulerAngles.y, 0f);
}
mainCollider.enabled = true;
mainCollider.isTrigger = false;
if (jackRb == null) jackRb = gameObject.GetComponent<Rigidbody>();
if (jackRb == null) jackRb = gameObject.AddComponent<Rigidbody>();
jackRb.mass = 8f;
jackRb.interpolation = RigidbodyInterpolation.Interpolate;
// Continuous защищает от пролета сквозь тонкий MeshCollider дороги
jackRb.collisionDetectionMode = CollisionDetectionMode.Continuous;
jackRb.linearVelocity = Vector3.zero;
jackRb.angularVelocity = Vector3.zero;
}
private void SetGhostVisual(bool isGhost)
{
if (isShowingGhost == isGhost) return;
@@ -511,10 +578,7 @@ public class CarJack : MonoBehaviour, IInteractable
for (int i = 0; i < renderers.Length; i++)
{
if (renderers[i] == null) continue;
if (isGhost && ghostMaterial != null)
renderers[i].sharedMaterial = ghostMaterial;
else
renderers[i].sharedMaterial = originalMaterials[i];
renderers[i].sharedMaterial = (isGhost && ghostMaterial != null) ? ghostMaterial : originalMaterials[i];
}
}
@@ -524,59 +588,34 @@ public class CarJack : MonoBehaviour, IInteractable
liftProgress = Mathf.Clamp01(liftProgress + delta);
if (Mathf.Abs(liftProgress - prev) > 0.0001f)
{
screwSpinAngle += delta * 2160f;
UpdateJackPose();
}
}
private void UpdateJackPose()
{
float fold = (1f - liftProgress) * maxFoldAngle;
float heightRatio = Mathf.Lerp(0.45f, 1.0f, liftProgress);
float widthRatio = Mathf.Lerp(1.14f, 1.0f, liftProgress);
if (bottomArmL != null)
bottomArmL.localRotation = bArmL_OpenRot * Quaternion.Euler(armRotationAxis * (fold * foldSignL));
if (bottomArmR != null)
bottomArmR.localRotation = bArmR_OpenRot * Quaternion.Euler(armRotationAxis * (fold * foldSignR));
if (diamondPivot != null)
diamondPivot.localScale = new Vector3(widthRatio, heightRatio, widthRatio);
if (topArmL != null)
topArmL.localRotation = tArmL_OpenRot * Quaternion.Euler(armRotationAxis * (-fold * foldSignL * 2f));
if (topArmR != null)
topArmR.localRotation = tArmR_OpenRot * Quaternion.Euler(armRotationAxis * (-fold * foldSignR * 2f));
if (screw != null && topArmL != null && topArmR != null)
if (topPlate != null)
{
Vector3 sPos = screw.position;
sPos.y = (topArmL.position.y + topArmR.position.y) * 0.5f;
screw.position = sPos;
screw.localRotation = Quaternion.Euler(screwSpinAxis * screwSpinAngle);
topPlate.localPosition = new Vector3(
topPlateInitLocalPos.x,
topPlateInitLocalPos.y * heightRatio,
topPlateInitLocalPos.z
);
}
if (topPlate != null && topArmL != null)
if (screw != null)
{
float baseY = transform.position.y;
float jointOffset = topArmL.position.y - baseY;
Vector3 pPos = topPlate.position;
// Если домкрат стоит под машиной, привязываем высоту площадки к реальному порогу,
// чтобы площадка вплотную упиралась в днище без зазора и левитации!
if (currentState == JackState.PlacedUnderCar && targetCarRb != null)
{
float foldedY = initialSillWorldY - 0.04f;
float contactY = initialSillWorldY;
float maxLiftedY = initialSillWorldY + carLiftHeight;
if (liftProgress <= 0.25f)
pPos.y = Mathf.Lerp(foldedY, contactY, liftProgress / 0.25f);
else
pPos.y = Mathf.Lerp(contactY, maxLiftedY, (liftProgress - 0.25f) / 0.75f);
}
else
{
pPos.y = baseY + jointOffset * 2f;
}
topPlate.position = pPos;
screw.localPosition = new Vector3(
screwInitLocalPos.x,
screwInitLocalPos.y * heightRatio,
screwInitLocalPos.z
);
screw.localRotation = screwInitLocalRot;
}
}
}
+28 -53
View File
@@ -4,9 +4,8 @@ using UnityEngine;
public class WheelBolt : MonoBehaviour, IInteractable
{
[Header("Настройки вылета и скорости")]
[Tooltip("На сколько метров болт выдвигается наружу при откручивании")]
[SerializeField] private float pullOutDistance = 0.06f;
[SerializeField] private float workDuration = 0.6f; // Время на 1 болт (сек)
[SerializeField] private float workDuration = 0.5f;
private CarPart parentWheel;
private MeshRenderer meshRenderer;
@@ -17,19 +16,20 @@ public class WheelBolt : MonoBehaviour, IInteractable
private Vector3 tightenedLocalPos;
private Quaternion tightenedLocalRot;
private Vector3 baseLocalScale;
// Реальный геометрический центр меша болта и направление наружу (на игрока)
private Vector3 localMeshCenter;
private Vector3 boltCenterInParent;
private Vector3 parentOutwardDir;
// 1 = полностью закручен, 0 = полностью выкручен
private float tightness = 1f;
private bool isTightened = true;
private bool isHoveredThisFrame = false;
private bool waitForRelease = false;
public bool IsTightened => isTightened;
public bool IsAvailableForAim => parentWheel == null || parentWheel.State == PartState.Installed;
public Vector3 WorldBoltCenter => transform.TransformPoint(localMeshCenter);
private void Awake()
{
@@ -40,23 +40,17 @@ public class WheelBolt : MonoBehaviour, IInteractable
tightenedLocalPos = transform.localPosition;
tightenedLocalRot = transform.localRotation;
baseLocalScale = transform.localScale;
// 1. Находим реальный центр геометрии болта (даже если пивот сбит в центр колеса)
MeshFilter mf = GetComponent<MeshFilter>();
if (mf != null && mf.sharedMesh != null)
{
localMeshCenter = mf.sharedMesh.bounds.center;
}
// Привязываем сферу коллайдера строго к геометрии самого болта
boltCollider.isTrigger = true;
boltCollider.center = localMeshCenter;
boltCollider.radius = 0.065f;
boltCollider.radius = 0.045f;
// Запоминаем позицию центра болта в координатах родителя (колеса)
boltCenterInParent = tightenedLocalPos + tightenedLocalRot * Vector3.Scale(localMeshCenter, transform.localScale);
// 2. Автоматически вычисляем вектор "наружу от машины" (на игрока)
boltCenterInParent = tightenedLocalPos + tightenedLocalRot * Vector3.Scale(localMeshCenter, baseLocalScale);
CalculateOutwardDirection();
if (meshRenderer != null)
@@ -69,8 +63,6 @@ public class WheelBolt : MonoBehaviour, IInteractable
private void CalculateOutwardDirection()
{
Vector3 worldBoltPos = transform.TransformPoint(localMeshCenter);
// Находим корень автомобиля, чтобы понять, с левой или с правой стороны стоит колесо
VehicleInteraction car = GetComponentInParent<VehicleInteraction>();
Transform carRoot = car != null ? car.transform : transform.root;
@@ -78,19 +70,14 @@ public class WheelBolt : MonoBehaviour, IInteractable
float sideSign = Mathf.Sign(Vector3.Dot(fromCarToBolt, carRoot.right));
if (sideSign == 0f) sideSign = 1f;
// Вектор наружу в мировых координатах (влево для левых колес, вправо для правых)
Vector3 worldOutDir = carRoot.right * sideSign;
// Переводим в систему координат родителя болта (Wheel_FL / Wheel_FR)
if (transform.parent != null)
parentOutwardDir = transform.parent.InverseTransformDirection(worldOutDir).normalized;
else
parentOutwardDir = Vector3.right * sideSign;
parentOutwardDir = transform.parent != null
? transform.parent.InverseTransformDirection(worldOutDir).normalized
: Vector3.right * sideSign;
}
private void LateUpdate()
{
// Если само колесо снято с машины — болты полностью скрыты
if (parentWheel != null && parentWheel.State != PartState.Installed)
{
if (meshRenderer != null && meshRenderer.enabled) meshRenderer.enabled = false;
@@ -108,29 +95,27 @@ 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;
UpdateBoltTransform(scaleMult);
if (meshRenderer != null)
{
if (isTightened || isAnimating)
{
// Болт закручен (или сейчас крутится):
// Если в руках КЛЮЧ — подсвечиваем его материалом GhostPart, чтобы игрок видел, что крутить!
// Если ключа нет — показываем обычный металл.
meshRenderer.enabled = true;
if (hasWrench && ghostMaterial != null)
// Подсвечиваем только тот болт, на который сейчас наведен прицел!
if (isHoveredThisFrame && hasWrench && ghostMaterial != null)
meshRenderer.sharedMaterial = ghostMaterial;
else if (originalMaterial != null)
meshRenderer.sharedMaterial = originalMaterial;
}
else
{
// Болт выкручен (исчез):
// Показываем силуэт ТОЛЬКО когда игрок с ключом наводится на отверстие для закрутки
bool showGhostHole = hasWrench && isHoveredThisFrame;
meshRenderer.enabled = showGhostHole;
if (showGhostHole && ghostMaterial != null)
{
// Выкрученный болт: показываем силуэт отверстия при взятом ключе
meshRenderer.enabled = hasWrench && isHoveredThisFrame;
if (meshRenderer.enabled && ghostMaterial != null)
meshRenderer.sharedMaterial = ghostMaterial;
}
}
}
@@ -145,29 +130,25 @@ public class WheelBolt : MonoBehaviour, IInteractable
{
return "Колесо под нагрузкой! Сначала поднимите эту сторону домкратом";
}
bool hasWrench = toolManager != null && toolManager.currentTool == ToolType.Wrench;
bool hasWrench = toolManager != null && toolManager.currentTool == ToolType.Wrench;
if (!hasWrench)
{
waitForRelease = false;
return isTightened
? "Болт (Возьмите баллонный ключ [Tab])"
: "Место под болт (Возьмите ключ [Tab])";
? "Колесный болт (Возьмите баллонный ключ [Tab])"
: "Отверстие под болт (Возьмите ключ [Tab])";
}
bool isHoldingKey = Input.GetMouseButton(0) || Input.GetKey(KeyCode.E);
// Снимаем блокировку только когда игрок отпустил кнопку мыши/клавиатуры
if (!isHoldingKey)
{
waitForRelease = false;
tightness = isTightened ? 1f : 0f;
UpdateBoltTransform();
}
else if (!waitForRelease)
{
// Крутим болт, только если действие не заблокировано после прошлого завершения
ProcessWrench(Time.deltaTime);
}
@@ -186,43 +167,37 @@ public class WheelBolt : MonoBehaviour, IInteractable
if (isTightened)
{
tightness -= step;
UpdateBoltTransform();
if (tightness <= 0f)
{
tightness = 0f;
isTightened = false;
waitForRelease = true; // Ждем отпускания кнопки, чтобы не закрутить обратно!
waitForRelease = true;
}
}
else
{
tightness += step;
UpdateBoltTransform();
if (tightness >= 1f)
{
tightness = 1f;
isTightened = true;
waitForRelease = true; // Ждем отпускания кнопки, чтобы не открутить обратно!
UpdateBoltTransform();
waitForRelease = true;
}
}
}
private void UpdateBoltTransform()
private void UpdateBoltTransform(float scaleMultiplier = 1f)
{
float outFactor = 1f - Mathf.Clamp01(tightness);
Vector3 currentScale = baseLocalScale * scaleMultiplier;
// Вращаем болт вокруг оси вылета (2 полных оборота = 720 градусов)
Quaternion spinRotation = Quaternion.AngleAxis(outFactor * 720f, parentOutwardDir);
Quaternion newLocalRot = spinRotation * tightenedLocalRot;
// Компенсируем смещенный пивот, чтобы болт крутился строго на месте вокруг своего центра,
// и сдвигаем его наружу к игроку по вектору parentOutwardDir
Vector3 rotatedCenterOffset = newLocalRot * Vector3.Scale(localMeshCenter, transform.localScale);
Vector3 rotatedCenterOffset = newLocalRot * Vector3.Scale(localMeshCenter, currentScale);
Vector3 pullOutOffset = parentOutwardDir * (pullOutDistance * outFactor);
transform.localScale = currentScale;
transform.localRotation = newLocalRot;
transform.localPosition = boltCenterInParent - rotatedCenterOffset + pullOutOffset;
}
@@ -3,10 +3,14 @@ using UnityEngine;
public class CarConditionGenerator : MonoBehaviour
{
[Header("Настройки спавна")]
[Range(0f, 1f)] [SerializeField] private float rustProbability = 0.7f; // Шанс появления ржавчины
[Range(0f, 1f)] [SerializeField] private float rustProbability = 0.7f;
[SerializeField] private float minRustAmount = 0.2f;
[SerializeField] private float maxRustAmount = 0.85f;
[SerializeField] private Color baseCarColor = Color.gray;
[SerializeField] private float maxRustAmount = 0.75f;
[Header("Цвет кузова")]
[Tooltip("Включите, только если хотите принудительно перекрасить машину при старте")]
[SerializeField] private bool overrideMaterialColor = false;
[SerializeField] private Color baseCarColor = Color.blue;
private void Start()
{
@@ -16,29 +20,46 @@ public class CarConditionGenerator : MonoBehaviour
[ContextMenu("Сгенерировать состояние")]
public void GenerateCondition()
{
// 1. Обрабатываем все съемные детали (CarPart)
CarPart[] allParts = GetComponentsInChildren<CarPart>(true);
foreach (CarPart part in allParts)
{
CarPartVisuals visuals = part.GetComponent<CarPartVisuals>();
if (visuals == null) visuals = part.gameObject.AddComponent<CarPartVisuals>();
// 1. Базовый цвет кузова
visuals.SetPaintColor(baseCarColor);
if (overrideMaterialColor)
visuals.SetPaintColor(baseCarColor);
// 2. Пластиковые детали (бампер) не ржавеют
if (part.Data != null && !part.Data.canRust)
{
visuals.SetDamage(0f);
continue;
}
// 3. Для металла - случайное начальное повреждение
float damage = Random.value < rustProbability
? Random.Range(minRustAmount, maxRustAmount)
: 0f;
visuals.SetDamage(damage);
}
// 2. Обрабатываем основной кузов (body), на котором нет CarPart, чтобы он не оставался ржавым из материала
int rustProp = Shader.PropertyToID("_RustAmount");
foreach (Renderer r in GetComponentsInChildren<Renderer>(true))
{
if (r.GetComponentInParent<CarPart>(true) != null) continue;
foreach (Material m in r.sharedMaterials)
{
if (m != null && m.HasProperty(rustProp))
{
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);
break;
}
}
}
}
}
+17 -49
View File
@@ -1,24 +1,11 @@
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Стадии ремонта кузовной детали. Вычисляются из значений прогресса, отдельно хранить не нужно.
/// </summary>
public enum RepairStage
{
Healthy, // деталь целая, ржавчины нет
Rusted, // есть ржавчина - нужна зачистка
Cleaned, // ржавчина счищена, голый металл - нужна шпаклёвка
Puttied, // зашпаклёвано - нужна шлифовка
Sanded, // отшлифовано - нужна покраска
Repaired // покрашено, ремонт завершён
Healthy, Rusted, Cleaned, Puttied, Sanded, Repaired
}
/// <summary>
/// Состояние внешнего вида детали и стадии ремонта. Значения передаются в шейдер CarPaint_Rust
/// через MaterialPropertyBlock, только в те слоты материалов, где этот шейдер есть
/// (стёкла, фары и т.п. на той же детали не затрагиваются).
/// </summary>
[DisallowMultipleComponent]
public class CarPartVisuals : MonoBehaviour
{
@@ -29,13 +16,12 @@ public class CarPartVisuals : MonoBehaviour
private static readonly int SandProp = Shader.PropertyToID("_SandProgress");
private static readonly int PaintProp = Shader.PropertyToID("_PaintProgress");
// Порог, после которого стадия считается завершённой (и значение "защёлкивается" до 100%)
private const float DoneThreshold = 0.98f;
private const float RustCleanThreshold = 0.02f;
[Header("Состояние (можно крутить в инспекторе во время Play)")]
[Range(0f, 1f)] [SerializeField] private float rustInitial; // сколько детали было поражено
[Range(0f, 1f)] [SerializeField] private float rustCurrent; // сколько ржавчины осталось
[Header("Состояние детали")]
[Range(0f, 1f)] [SerializeField] private float rustInitial;
[Range(0f, 1f)] [SerializeField] private float rustCurrent;
[Range(0f, 1f)] [SerializeField] private float putty;
[Range(0f, 1f)] [SerializeField] private float sanding;
[Range(0f, 1f)] [SerializeField] private float paint;
@@ -50,6 +36,7 @@ public class CarPartVisuals : MonoBehaviour
private readonly List<Slot> slots = new List<Slot>();
private MaterialPropertyBlock block;
private bool initialized;
private bool colorInitialized;
public float CurrentRust => rustCurrent;
public float InitialRust => rustInitial;
@@ -68,7 +55,6 @@ public class CarPartVisuals : MonoBehaviour
}
}
/// <summary>Прогресс текущей стадии 0..1 (для подсказок и UI).</summary>
public float StageProgress
{
get
@@ -84,8 +70,6 @@ public class CarPartVisuals : MonoBehaviour
}
}
// ---------- Инициализация ----------
private void EnsureInit()
{
if (initialized) return;
@@ -96,35 +80,33 @@ public class CarPartVisuals : MonoBehaviour
foreach (Renderer r in GetComponentsInChildren<Renderer>(true))
{
// Не трогаем рендереры вложенных деталей (например, зеркало внутри двери)
if (owner != null && r.GetComponentInParent<CarPart>(true) != owner) continue;
Material[] mats = r.sharedMaterials;
for (int i = 0; i < mats.Length; i++)
{
if (mats[i] != null && mats[i].HasProperty(RustAmountProp))
{
// Автоматически запоминаем родной цвет машины из материала (например, синий!)
if (!colorInitialized && mats[i].HasProperty(BaseColorProp))
{
paintColor = mats[i].GetColor(BaseColorProp);
colorInitialized = true;
}
slots.Add(new Slot { renderer = r, materialIndex = i });
}
}
}
if (slots.Count == 0)
{
Debug.LogWarning($"[{name}] Нет материалов с шейдером CarPaint_Rust (свойство _RustAmount). " +
"Ржавчина и ремонт на этой детали не будут видны.", this);
}
}
private void OnValidate()
{
// Позволяет двигать слайдеры в инспекторе и сразу видеть результат
if (Application.isPlaying && initialized) Apply();
}
// ---------- Установка состояния ----------
/// <summary>Задать начальное повреждение детали (0 = целая). Сбрасывает все стадии ремонта.</summary>
public void SetDamage(float amount)
{
EnsureInit();
amount = Mathf.Clamp01(amount);
if (amount <= 0.001f) amount = 0f;
@@ -136,21 +118,17 @@ public class CarPartVisuals : MonoBehaviour
Apply();
}
/// <summary>Задать цвет краски без проверок (для генератора состояния).</summary>
public void SetPaintColor(Color newColor)
{
EnsureInit();
paintColor = newColor;
colorInitialized = true;
Apply();
}
// ---------- Действия инструментов ----------
// amount01 - доля полной работы за этот кадр (deltaTime / время полной обработки).
// Возвращают false, если инструмент сейчас не подходит этой стадии.
public bool CleanRust(float amount01)
{
if (Stage != RepairStage.Rusted) return false;
rustCurrent -= rustInitial * amount01;
if (rustCurrent <= RustCleanThreshold) rustCurrent = 0f;
Apply();
@@ -160,7 +138,6 @@ public class CarPartVisuals : MonoBehaviour
public bool ApplyPutty(float amount01)
{
if (Stage != RepairStage.Cleaned) return false;
putty = Mathf.Min(1f, putty + amount01);
if (putty >= DoneThreshold) putty = 1f;
Apply();
@@ -170,7 +147,6 @@ public class CarPartVisuals : MonoBehaviour
public bool Sand(float amount01)
{
if (Stage != RepairStage.Puttied) return false;
sanding = Mathf.Min(1f, sanding + amount01);
if (sanding >= DoneThreshold) sanding = 1f;
Apply();
@@ -180,34 +156,26 @@ public class CarPartVisuals : MonoBehaviour
public bool PaintRepair(float amount01)
{
if (Stage != RepairStage.Sanded) return false;
paint = Mathf.Min(1f, paint + amount01);
if (paint >= DoneThreshold) paint = 1f;
Apply();
return true;
}
/// <summary>Перекраска целой или уже отремонтированной детали в другой цвет.</summary>
public bool Recolor(Color newColor)
{
RepairStage s = Stage;
if (s != RepairStage.Healthy && s != RepairStage.Repaired) return false;
paintColor = newColor;
Apply();
SetPaintColor(newColor);
return true;
}
// ---------- Передача в шейдер ----------
private void Apply()
{
EnsureInit();
foreach (Slot s in slots)
{
if (s.renderer == null) continue;
s.renderer.GetPropertyBlock(block, s.materialIndex);
block.SetColor(BaseColorProp, paintColor);
block.SetFloat(RustInitialProp, rustInitial);