231 lines
9.8 KiB
C#
231 lines
9.8 KiB
C#
using UnityEngine;
|
|
|
|
[RequireComponent(typeof(SphereCollider))]
|
|
public class WheelBolt : MonoBehaviour, IInteractable
|
|
{
|
|
[Header("Настройки вылета и скорости")]
|
|
[Tooltip("На сколько метров болт выдвигается наружу при откручивании")]
|
|
[SerializeField] private float pullOutDistance = 0.06f;
|
|
[SerializeField] private float workDuration = 0.6f; // Время на 1 болт (сек)
|
|
|
|
private CarPart parentWheel;
|
|
private MeshRenderer meshRenderer;
|
|
private SphereCollider boltCollider;
|
|
private Material originalMaterial;
|
|
private Material ghostMaterial;
|
|
private PlayerToolManager toolManager;
|
|
|
|
private Vector3 tightenedLocalPos;
|
|
private Quaternion tightenedLocalRot;
|
|
|
|
// Реальный геометрический центр меша болта и направление наружу (на игрока)
|
|
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;
|
|
|
|
private void Awake()
|
|
{
|
|
parentWheel = GetComponentInParent<CarPart>();
|
|
meshRenderer = GetComponent<MeshRenderer>();
|
|
boltCollider = GetComponent<SphereCollider>();
|
|
toolManager = FindAnyObjectByType<PlayerToolManager>();
|
|
|
|
tightenedLocalPos = transform.localPosition;
|
|
tightenedLocalRot = transform.localRotation;
|
|
|
|
// 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;
|
|
|
|
// Запоминаем позицию центра болта в координатах родителя (колеса)
|
|
boltCenterInParent = tightenedLocalPos + tightenedLocalRot * Vector3.Scale(localMeshCenter, transform.localScale);
|
|
|
|
// 2. Автоматически вычисляем вектор "наружу от машины" (на игрока)
|
|
CalculateOutwardDirection();
|
|
|
|
if (meshRenderer != null)
|
|
originalMaterial = meshRenderer.sharedMaterial;
|
|
|
|
if (parentWheel != null && parentWheel.Data != null)
|
|
ghostMaterial = parentWheel.Data.ghostMaterial;
|
|
}
|
|
|
|
private void CalculateOutwardDirection()
|
|
{
|
|
Vector3 worldBoltPos = transform.TransformPoint(localMeshCenter);
|
|
|
|
// Находим корень автомобиля, чтобы понять, с левой или с правой стороны стоит колесо
|
|
VehicleInteraction car = GetComponentInParent<VehicleInteraction>();
|
|
Transform carRoot = car != null ? car.transform : transform.root;
|
|
|
|
Vector3 fromCarToBolt = worldBoltPos - carRoot.position;
|
|
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;
|
|
}
|
|
|
|
private void LateUpdate()
|
|
{
|
|
// Если само колесо снято с машины — болты полностью скрыты
|
|
if (parentWheel != null && parentWheel.State != PartState.Installed)
|
|
{
|
|
if (meshRenderer != null && meshRenderer.enabled) meshRenderer.enabled = false;
|
|
if (boltCollider != null && boltCollider.enabled) boltCollider.enabled = false;
|
|
isHoveredThisFrame = false;
|
|
return;
|
|
}
|
|
|
|
if (boltCollider != null && !boltCollider.enabled)
|
|
boltCollider.enabled = true;
|
|
|
|
if (toolManager == null)
|
|
toolManager = FindAnyObjectByType<PlayerToolManager>();
|
|
|
|
bool hasWrench = toolManager != null && toolManager.currentTool == ToolType.Wrench;
|
|
bool isAnimating = tightness > 0.01f && tightness < 0.99f;
|
|
|
|
if (meshRenderer != null)
|
|
{
|
|
if (isTightened || isAnimating)
|
|
{
|
|
// Болт закручен (или сейчас крутится):
|
|
// Если в руках КЛЮЧ — подсвечиваем его материалом GhostPart, чтобы игрок видел, что крутить!
|
|
// Если ключа нет — показываем обычный металл.
|
|
meshRenderer.enabled = true;
|
|
if (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.sharedMaterial = ghostMaterial;
|
|
}
|
|
}
|
|
}
|
|
|
|
isHoveredThisFrame = false;
|
|
}
|
|
|
|
public string GetPrompt()
|
|
{
|
|
isHoveredThisFrame = true;
|
|
|
|
if (isTightened && parentWheel != null && !CarJack.IsWheelLifted(parentWheel.transform))
|
|
{
|
|
return "Колесо под нагрузкой! Сначала поднимите эту сторону домкратом";
|
|
}
|
|
|
|
bool hasWrench = toolManager != null && toolManager.currentTool == ToolType.Wrench;
|
|
|
|
if (!hasWrench)
|
|
{
|
|
waitForRelease = false;
|
|
return isTightened
|
|
? "Болт (Возьмите баллонный ключ [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);
|
|
}
|
|
|
|
int percent = Mathf.RoundToInt((isTightened ? (1f - tightness) : tightness) * 100f);
|
|
|
|
if (isTightened)
|
|
return (percent > 0 && !waitForRelease) ? $"Откручиваем болт... {percent}%" : "[Удерж. ЛКМ / E] Открутить болт";
|
|
else
|
|
return (percent > 0 && !waitForRelease) ? $"Закручиваем болт... {percent}%" : "[Удерж. ЛКМ / E] Закрутить болт";
|
|
}
|
|
|
|
private void ProcessWrench(float dt)
|
|
{
|
|
float step = dt / workDuration;
|
|
|
|
if (isTightened)
|
|
{
|
|
tightness -= step;
|
|
UpdateBoltTransform();
|
|
|
|
if (tightness <= 0f)
|
|
{
|
|
tightness = 0f;
|
|
isTightened = false;
|
|
waitForRelease = true; // Ждем отпускания кнопки, чтобы не закрутить обратно!
|
|
}
|
|
}
|
|
else
|
|
{
|
|
tightness += step;
|
|
UpdateBoltTransform();
|
|
|
|
if (tightness >= 1f)
|
|
{
|
|
tightness = 1f;
|
|
isTightened = true;
|
|
waitForRelease = true; // Ждем отпускания кнопки, чтобы не открутить обратно!
|
|
UpdateBoltTransform();
|
|
}
|
|
}
|
|
}
|
|
|
|
private void UpdateBoltTransform()
|
|
{
|
|
float outFactor = 1f - Mathf.Clamp01(tightness);
|
|
|
|
// Вращаем болт вокруг оси вылета (2 полных оборота = 720 градусов)
|
|
Quaternion spinRotation = Quaternion.AngleAxis(outFactor * 720f, parentOutwardDir);
|
|
Quaternion newLocalRot = spinRotation * tightenedLocalRot;
|
|
|
|
// Компенсируем смещенный пивот, чтобы болт крутился строго на месте вокруг своего центра,
|
|
// и сдвигаем его наружу к игроку по вектору parentOutwardDir
|
|
Vector3 rotatedCenterOffset = newLocalRot * Vector3.Scale(localMeshCenter, transform.localScale);
|
|
Vector3 pullOutOffset = parentOutwardDir * (pullOutDistance * outFactor);
|
|
|
|
transform.localRotation = newLocalRot;
|
|
transform.localPosition = boltCenterInParent - rotatedCenterOffset + pullOutOffset;
|
|
}
|
|
|
|
public void Interact(GameObject interactor) { }
|
|
} |