Снятие колес работает, покраска тоже более менее. Физика просто говно щяс
This commit is contained in:
1 parent
d4c84b10df
commit
2ce853999d
67 files changed
+155919
-1996
No files matched your search
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user