using UnityEngine; [RequireComponent(typeof(BoxCollider))] public class CarJack : MonoBehaviour, IInteractable { public enum JackState { OnFloor, InHand, PlacedUnderCar } [Header("Детали домкрата (из Blender)")] [SerializeField] private Transform bottomArmL; [SerializeField] private Transform bottomArmR; [SerializeField] private Transform topArmL; [SerializeField] private Transform topArmR; [SerializeField] private Transform screw; [SerializeField] private Transform topPlate; [Header("Настройки подъема")] [SerializeField] private float liftDuration = 2.0f; [Tooltip("На сколько метров поднимается порог (0.28 = 28 см, чтобы колесо легко вставало на место)")] [SerializeField] private float carLiftHeight = 0.28f; [Header("Позиционирование и материалы")] [SerializeField] private Material ghostMaterial; [SerializeField] private Vector3 inHandOffset = new Vector3(0.25f, -0.25f, 0.65f); [SerializeField] private Vector3 inHandRotation = new Vector3(0f, 90f, 0f); [Header("Состояние подъема")] [Range(0f, 1f)] [SerializeField] private float liftProgress = 0f; private JackState currentState = JackState.OnFloor; private BoxCollider mainCollider; private Rigidbody jackRb; private Transform holderCamera; private Transform playerRoot; private UIManager uiManager; private int stateChangeFrame = -1; 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 GameObject supportAnchorObj; private Rigidbody supportAnchorRb; private ConfigurableJoint liftJoint; private float initialSillWorldY; private bool canPlaceUnderCar = false; private Vector3 previewWorldPos; private Quaternion previewWorldRot; private Rigidbody previewCarRb; private CarPart previewWheelPart; private WheelCollider previewWheelCol; private bool isHoveredThisFrame = false; public static CarJack ActiveJackInHand { get; private set; } public bool IsLifted => currentState == JackState.PlacedUnderCar && liftProgress >= 0.70f; public static bool IsWheelLifted(Transform wheelTransform) { if (wheelTransform == null) return false; CarJack[] allJacks = FindObjectsByType(FindObjectsSortMode.None); foreach (CarJack jack in allJacks) { if (!jack.IsLifted) continue; if (jack.targetWheelPart != null && jack.targetWheelPart.transform == wheelTransform) return true; if (Vector3.Distance(jack.transform.position, wheelTransform.position) < 2.0f) return true; } return false; } private void Awake() { uiManager = FindAnyObjectByType(); originalRootScale = transform.localScale; mainCollider = GetComponent(); foreach (var c in GetComponentsInChildren(true)) if (c != mainCollider) c.enabled = false; renderers = GetComponentsInChildren(true); originalMaterials = new Material[renderers.Length]; for (int i = 0; i < renderers.Length; i++) originalMaterials[i] = renderers[i].sharedMaterial; // Автоматически выравниваем BoxCollider по реальным габаритам модели, // чтобы его дно не торчало ниже подошвы домкрата FitColliderToRenderers(); SetupUnifiedDiamondRig(); UpdateJackPose(); } private void FitColliderToRenderers() { if (mainCollider == null || renderers == null || renderers.Length == 0) return; Quaternion savedRot = transform.rotation; transform.rotation = Quaternion.identity; 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() { 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()); 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; } private void FixedUpdate() { if (currentState != JackState.PlacedUnderCar || targetCarRb == null || supportAnchorRb == null) return; // Плавно перемещаем кинематическую точку опоры вверх-вниз вместе с верхушкой домкрата float targetY = initialSillWorldY + liftProgress * carLiftHeight; Vector3 targetAnchorPos = new Vector3(transform.position.x, targetY, transform.position.z); supportAnchorRb.MovePosition(targetAnchorPos); 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(); supportAnchorRb.isKinematic = true; supportAnchorRb.interpolation = RigidbodyInterpolation.Interpolate; liftJoint = supportAnchorObj.AddComponent(); 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 { positionSpring = targetCarRb.mass * 180f, positionDamper = targetCarRb.mass * 28f, maximumForce = targetCarRb.mass * 60f }; JointDrive horizontalDrive = new JointDrive { positionSpring = targetCarRb.mass * 25f, positionDamper = targetCarRb.mass * 8f, maximumForce = targetCarRb.mass * 20f }; liftJoint.yDrive = verticalDrive; liftJoint.xDrive = horizontalDrive; liftJoint.zDrive = horizontalDrive; } private void DestroyLiftJoint() { if (supportAnchorObj != null) Destroy(supportAnchorObj); supportAnchorObj = null; supportAnchorRb = null; liftJoint = null; } private bool CanLowerSafely() { if (targetWheelPart == null) return true; if (targetWheelPart.State != PartState.Installed) return false; if (targetWheelPart.TotalBoltsCount > 0 && targetWheelPart.TightenedBoltsCount < targetWheelPart.TotalBoltsCount) return false; return true; } public string GetPrompt() { isHoveredThisFrame = true; if (currentState == JackState.OnFloor) return "[E] Взять домкрат"; if (currentState == JackState.PlacedUnderCar) { int percent = Mathf.RoundToInt(liftProgress * 100f); if (!CanLowerSafely()) return $"Домкрат поднят ({percent}%)\nНаденьте колесо и закрутите болты перед спуском!"; 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] Выбросить домкрат"; } public void Interact(GameObject interactor) { if (currentState == JackState.OnFloor) { PlayerHands hands = interactor.GetComponentInChildren() ?? interactor.GetComponentInParent(); if (hands != null && hands.IsHolding) return; Camera cam = interactor.GetComponentInChildren(); Transform camTr = cam != null ? cam.transform : FindAnyObjectByType()?.transform; if (camTr != null) PickUpToHand(camTr, interactor.transform.root); } } private void PickUpToHand(Transform camTransform, Transform rootTransform) { if (camTransform == null) return; if (ActiveJackInHand != null && ActiveJackInHand != this) return; DestroyLiftJoint(); holderCamera = camTransform; playerRoot = rootTransform; ActiveJackInHand = this; currentState = JackState.InHand; stateChangeFrame = Time.frameCount; targetCarRb = null; targetWheelPart = null; targetWheelCollider = null; liftProgress = 0f; if (jackRb != null) Destroy(jackRb); mainCollider.enabled = false; transform.SetParent(holderCamera); transform.localScale = originalRootScale; transform.localPosition = inHandOffset; transform.localRotation = Quaternion.Euler(inHandRotation); UpdateJackPose(); SetGhostVisual(false); } private void UpdateInHandPreview() { canPlaceUnderCar = false; if (holderCamera == null) return; Ray ray = new Ray(holderCamera.position, holderCamera.forward); RaycastHit[] hits = Physics.RaycastAll(ray, 4.0f, ~0, QueryTriggerInteraction.Collide); bool foundSurface = false; RaycastHit validHit = default; float closestHitDist = float.MaxValue; foreach (var h in hits) { if (h.collider.transform.IsChildOf(transform)) continue; if (playerRoot != null && h.collider.transform.IsChildOf(playerRoot)) continue; if (h.distance < closestHitDist) { closestHitDist = h.distance; validHit = h; foundSurface = true; } } if (foundSurface) { WheelCollider[] allWheels = FindObjectsByType(FindObjectsSortMode.None); WheelCollider closestWheel = null; float minWheelDist = 1.8f; foreach (var w in allWheels) { float d = Vector3.Distance(validHit.point, w.transform.position); if (d < minWheelDist) { minWheelDist = d; closestWheel = w; } } if (closestWheel != null) { Rigidbody carRb = closestWheel.GetComponentInParent(); 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.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.4f, Vector3.down, 2.0f, ~0, QueryTriggerInteraction.Ignore); foreach (var gh in groundHits) { if (gh.collider.transform.IsChildOf(carTr)) continue; if (gh.collider.transform.IsChildOf(transform)) continue; if (playerRoot != null && gh.collider.transform.IsChildOf(playerRoot)) continue; groundPoint = gh.point; break; } previewWorldPos = groundPoint; Vector3 outward = carTr.right * sideSign; previewWorldRot = Quaternion.LookRotation(Vector3.Cross(outward, Vector3.up), Vector3.up); previewCarRb = carRb; previewWheelCol = closestWheel; previewWheelPart = FindMatchingWheelPart(carTr, closestWheel.name); canPlaceUnderCar = true; } } } if (canPlaceUnderCar) { transform.position = previewWorldPos; transform.rotation = previewWorldRot; SetGhostVisual(true); } else { transform.localPosition = inHandOffset; transform.localRotation = Quaternion.Euler(inHandRotation); SetGhostVisual(false); } } private CarPart FindMatchingWheelPart(Transform carRoot, string wheelName) { foreach (CarPart p in carRoot.GetComponentsInChildren(true)) if (p.name == wheelName) return p; return null; } private void PlaceUnderCar() { ActiveJackInHand = null; currentState = JackState.PlacedUnderCar; stateChangeFrame = Time.frameCount; SetGhostVisual(false); transform.SetParent(null); transform.position = previewWorldPos; transform.rotation = previewWorldRot; mainCollider.enabled = true; mainCollider.isTrigger = true; targetCarRb = previewCarRb; targetWheelPart = previewWheelPart; targetWheelCollider = previewWheelCol; 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); } 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 void DropToFloor() { DestroyLiftJoint(); ActiveJackInHand = null; currentState = JackState.OnFloor; stateChangeFrame = Time.frameCount; SetGhostVisual(false); 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) { 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; } if (highestGroundY > float.MinValue) { // Ставим на 8 см выше найденного асфальта, чтобы домкрат мягко упал на него сверху dropPos.y = highestGroundY + 0.08f; } else { dropPos.y = holderCamera.position.y - 0.3f; } transform.position = dropPos; transform.rotation = Quaternion.Euler(0f, holderCamera.eulerAngles.y, 0f); } mainCollider.enabled = true; mainCollider.isTrigger = false; if (jackRb == null) jackRb = gameObject.GetComponent(); if (jackRb == null) jackRb = gameObject.AddComponent(); 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; isShowingGhost = isGhost; for (int i = 0; i < renderers.Length; i++) { if (renderers[i] == null) continue; renderers[i].sharedMaterial = (isGhost && ghostMaterial != null) ? ghostMaterial : originalMaterials[i]; } } private void ChangeLift(float delta) { float prev = liftProgress; liftProgress = Mathf.Clamp01(liftProgress + delta); if (Mathf.Abs(liftProgress - prev) > 0.0001f) UpdateJackPose(); } private void UpdateJackPose() { float heightRatio = Mathf.Lerp(0.45f, 1.0f, liftProgress); float widthRatio = Mathf.Lerp(1.14f, 1.0f, liftProgress); if (diamondPivot != null) diamondPivot.localScale = new Vector3(widthRatio, heightRatio, widthRatio); if (topPlate != null) { topPlate.localPosition = new Vector3( topPlateInitLocalPos.x, topPlateInitLocalPos.y * heightRatio, topPlateInitLocalPos.z ); } if (screw != null) { screw.localPosition = new Vector3( screwInitLocalPos.x, screwInitLocalPos.y * heightRatio, screwInitLocalPos.z ); screw.localRotation = screwInitLocalRot; } } }