388 lines
16 KiB
C#
388 lines
16 KiB
C#
using UnityEngine;
|
||
|
||
/// <summary>
|
||
/// Луч взаимодействия (3.2 м) с приоритетами:
|
||
/// 1) зоны установки и горловины, если в руках деталь/канистра; 2) колесные болты рядом с лучом;
|
||
/// 3) подкапотные агрегаты, бачки, щуп и сливная пробка; 4) домкрат и кирпичи; 5) детали кузова и посадка в авто [F].
|
||
/// </summary>
|
||
public class PlayerInteractor : MonoBehaviour
|
||
{
|
||
[Header("Настройки луча")]
|
||
[SerializeField] private float interactRange = 3.2f;
|
||
[SerializeField] private LayerMask interactableLayer;
|
||
|
||
[Header("Клавиши управления")]
|
||
[SerializeField] private KeyCode primaryKey = KeyCode.E;
|
||
[SerializeField] private KeyCode secondaryKey = KeyCode.R;
|
||
[SerializeField] private KeyCode enterVehicleKey = KeyCode.F;
|
||
|
||
[Header("Ссылки")]
|
||
[SerializeField] private UIManager uiManager;
|
||
|
||
private CarPart lastHoveredPart;
|
||
private PlayerHands cachedHands;
|
||
|
||
/// <summary>Объект под прицелом в текущем кадре (для диагностики и HUD).</summary>
|
||
public static GameObject CurrentTarget { get; private set; }
|
||
|
||
private void Awake()
|
||
{
|
||
if (uiManager == null) uiManager = FindAnyObjectByType<UIManager>();
|
||
cachedHands = GetComponentInParent<PlayerHands>();
|
||
if (cachedHands == null) cachedHands = FindAnyObjectByType<PlayerHands>();
|
||
if (interactableLayer.value == 0) interactableLayer = ~0;
|
||
}
|
||
|
||
private void OnDisable()
|
||
{
|
||
ResetProgressTargets();
|
||
if (uiManager != null) uiManager.HidePrompt();
|
||
CurrentTarget = null;
|
||
}
|
||
|
||
private void Update()
|
||
{
|
||
CurrentTarget = null;
|
||
|
||
if (GameInputLock.IsLocked)
|
||
{
|
||
ResetProgressTargets();
|
||
uiManager?.HidePrompt();
|
||
return;
|
||
}
|
||
|
||
if (CarJack.ActiveJackInHand != null) return;
|
||
|
||
if (cachedHands == null) cachedHands = FindAnyObjectByType<PlayerHands>();
|
||
|
||
// Канистра в руках — заливкой и подсказками управляет сама канистра
|
||
if (cachedHands != null && cachedHands.IsHoldingCanister)
|
||
{
|
||
ResetProgressTargets();
|
||
uiManager?.ShowPrompt(cachedHands.CurrentCanister != null ? cachedHands.CurrentCanister.StatusHint : "[G] Поставить канистру");
|
||
return;
|
||
}
|
||
|
||
Ray ray = new Ray(transform.position, transform.forward);
|
||
GameObject playerRoot = transform.root.gameObject;
|
||
|
||
// 0. Если в руках деталь — проверяем все зоны установки по лучу (чтобы кузов не перекрывал зону колеса!)
|
||
if (cachedHands != null && cachedHands.IsHolding)
|
||
{
|
||
RaycastHit[] allHits = Physics.RaycastAll(ray, interactRange, interactableLayer, QueryTriggerInteraction.Collide);
|
||
foreach (var h in allHits)
|
||
{
|
||
CarPartMountZone zone = h.collider.GetComponentInParent<CarPartMountZone>();
|
||
if (zone != null)
|
||
{
|
||
ResetProgressTargets();
|
||
string zPrompt = zone.GetPrompt();
|
||
if (!string.IsNullOrEmpty(zPrompt))
|
||
uiManager?.ShowPrompt(zPrompt);
|
||
else
|
||
uiManager?.HidePrompt();
|
||
return;
|
||
}
|
||
}
|
||
|
||
uiManager?.ShowPrompt($"В руках: {cachedHands.CurrentPart.DisplayName} | [G] Положить [ПКМ] Бросить");
|
||
return;
|
||
}
|
||
|
||
// Сливная пробка картера под днищем (луч может проходить под порогом)
|
||
if (TryDrainPlug(ray, playerRoot)) return;
|
||
|
||
if (TryRaycastPrioritized(ray, out RaycastHit hit))
|
||
{
|
||
CurrentTarget = hit.collider.gameObject;
|
||
|
||
// 1. ТОЧНЫЙ ПОИСК БЛИЖАЙШЕГО К ПРИЦЕЛУ БОЛТА
|
||
WheelBolt bestBolt = FindClosestBoltToRay(ray, hit.point, hit.collider);
|
||
if (bestBolt != null)
|
||
{
|
||
ResetProgressTargets();
|
||
string boltPrompt = bestBolt.GetPrompt();
|
||
if (!string.IsNullOrEmpty(boltPrompt))
|
||
uiManager?.ShowPrompt(boltPrompt);
|
||
else
|
||
uiManager?.HidePrompt();
|
||
return;
|
||
}
|
||
|
||
// 2. ПОДКАПОТНОЕ ПРОСТРАНСТВО: агрегаты, бачки, щуп
|
||
bool isEngineBayTarget = hit.collider.GetComponentInParent<EnginePart>() != null
|
||
|| hit.collider.GetComponentInParent<CarFluidCap>() != null
|
||
|| hit.collider.GetComponentInParent<OilDipstick>() != null;
|
||
|
||
if (!isEngineBayTarget)
|
||
{
|
||
// 3. ДОМКРАТ ПОД ПОРОГОМ
|
||
CarJack jack = hit.collider.GetComponentInParent<CarJack>();
|
||
if (jack == null)
|
||
{
|
||
Collider[] nearJackCols = Physics.OverlapSphere(hit.point, 0.22f, interactableLayer, QueryTriggerInteraction.Collide);
|
||
foreach (var c in nearJackCols)
|
||
{
|
||
jack = c.GetComponentInParent<CarJack>();
|
||
if (jack != null) break;
|
||
}
|
||
}
|
||
|
||
if (jack != null)
|
||
{
|
||
ResetProgressTargets();
|
||
uiManager?.ShowPrompt(jack.GetPrompt());
|
||
if (Input.GetKeyDown(primaryKey))
|
||
jack.Interact(playerRoot);
|
||
return;
|
||
}
|
||
|
||
WheelBrickSupport bricks = hit.collider.GetComponentInParent<WheelBrickSupport>();
|
||
if (bricks == null)
|
||
{
|
||
Collider[] nearBrickCols = Physics.OverlapSphere(hit.point, 0.22f, interactableLayer, QueryTriggerInteraction.Collide);
|
||
foreach (var c in nearBrickCols)
|
||
{
|
||
bricks = c.GetComponentInParent<WheelBrickSupport>();
|
||
if (bricks != null) break;
|
||
}
|
||
}
|
||
|
||
if (bricks != null)
|
||
{
|
||
ResetProgressTargets();
|
||
uiManager?.ShowPrompt(bricks.GetPrompt());
|
||
if (Input.GetKeyDown(primaryKey))
|
||
bricks.Interact(playerRoot);
|
||
return;
|
||
}
|
||
}
|
||
|
||
// 4. ОБЫЧНЫЕ ДЕТАЛИ И АВТОМОБИЛЬ
|
||
IInteractable interactable = hit.collider.GetComponentInParent<IInteractable>();
|
||
VehicleInteraction vehicle = hit.collider.GetComponentInParent<VehicleInteraction>();
|
||
CarPart part = hit.collider.GetComponentInParent<CarPart>();
|
||
CarPartMountZone mountZone = hit.collider.GetComponentInParent<CarPartMountZone>();
|
||
|
||
if (part != lastHoveredPart)
|
||
{
|
||
ResetProgressTargets();
|
||
lastHoveredPart = part;
|
||
}
|
||
|
||
if (interactable != null || vehicle != null)
|
||
{
|
||
if (Input.GetKeyDown(enterVehicleKey) && vehicle != null)
|
||
{
|
||
vehicle.Interact(playerRoot);
|
||
return;
|
||
}
|
||
|
||
if (mountZone == null && part != null)
|
||
{
|
||
if (part.State == PartState.Dropped)
|
||
{
|
||
if (Input.GetKeyDown(primaryKey))
|
||
part.Interact(playerRoot);
|
||
}
|
||
else if (part.State == PartState.Installed)
|
||
{
|
||
bool hasAnimator = part.GetComponent<CarPartAnimator>() != null;
|
||
if (hasAnimator)
|
||
{
|
||
if (Input.GetKeyDown(primaryKey))
|
||
part.Interact(playerRoot);
|
||
|
||
if (Input.GetKey(secondaryKey))
|
||
part.ProcessUnbolting(playerRoot, Time.deltaTime);
|
||
else
|
||
part.ResetUnbolt();
|
||
}
|
||
else
|
||
{
|
||
if (Input.GetKey(primaryKey))
|
||
part.ProcessUnbolting(playerRoot, Time.deltaTime);
|
||
else
|
||
part.ResetUnbolt();
|
||
}
|
||
}
|
||
}
|
||
else if (mountZone == null && interactable != null && Input.GetKeyDown(primaryKey))
|
||
{
|
||
interactable.Interact(playerRoot);
|
||
}
|
||
|
||
string finalPrompt = BuildPrompt(vehicle, interactable, part);
|
||
if (!string.IsNullOrEmpty(finalPrompt))
|
||
uiManager?.ShowPrompt(finalPrompt);
|
||
else
|
||
uiManager?.HidePrompt();
|
||
|
||
return;
|
||
}
|
||
}
|
||
|
||
ResetProgressTargets();
|
||
uiManager?.HidePrompt();
|
||
}
|
||
|
||
private bool TryRaycastPrioritized(Ray ray, out RaycastHit bestHit)
|
||
{
|
||
bestHit = default;
|
||
RaycastHit[] hits = Physics.RaycastAll(ray, interactRange, interactableLayer, QueryTriggerInteraction.Collide);
|
||
if (hits.Length == 0) return false;
|
||
System.Array.Sort(hits, (a, b) => a.distance.CompareTo(b.distance));
|
||
|
||
int bestPriority = int.MaxValue;
|
||
bool found = false;
|
||
bool blockedByClosedHood = false;
|
||
|
||
foreach (RaycastHit h in hits)
|
||
{
|
||
if (h.collider.transform.root == transform.root) continue; // пропускаем игрока
|
||
|
||
// Если на пути закрытый капот — подкапотку за ним не ловим, но сам капот доступен
|
||
CarPartAnimator anim = h.collider.GetComponentInParent<CarPartAnimator>();
|
||
if (anim != null && !anim.IsOpen && anim.name.ToLowerInvariant().Contains("hood"))
|
||
blockedByClosedHood = true;
|
||
|
||
bool isUnderHood = h.collider.GetComponentInParent<CarFluidCap>() != null
|
||
|| h.collider.GetComponentInParent<OilDipstick>() != null
|
||
|| h.collider.GetComponentInParent<EnginePart>() != null;
|
||
if (isUnderHood && blockedByClosedHood) continue;
|
||
|
||
// Твёрдое препятствие не от машины и не интерактивное (стена/пол) — дальше не пробиваем
|
||
if (!h.collider.isTrigger
|
||
&& h.collider.GetComponentInParent<VehicleInteraction>() == null
|
||
&& h.collider.GetComponentInParent<IInteractable>() == null)
|
||
{
|
||
break;
|
||
}
|
||
|
||
int prio = 50;
|
||
if (h.collider.GetComponentInParent<CarFluidCap>() != null
|
||
|| h.collider.GetComponentInParent<OilDipstick>() != null)
|
||
prio = 10;
|
||
else if (h.collider.GetComponentInParent<EnginePart>() != null)
|
||
prio = 15;
|
||
else if (h.collider.GetComponentInParent<CarJack>() != null
|
||
|| h.collider.GetComponentInParent<WheelBrickSupport>() != null)
|
||
prio = 20;
|
||
else
|
||
{
|
||
CarPart cp = h.collider.GetComponentInParent<CarPart>();
|
||
if (cp != null) prio = cp.IsWheel ? 25 : 30;
|
||
else if (h.collider.GetComponentInParent<IInteractable>() != null) prio = 35;
|
||
else if (h.collider.GetComponentInParent<VehicleInteraction>() != null) prio = 40;
|
||
}
|
||
|
||
if (prio < bestPriority)
|
||
{
|
||
bestPriority = prio;
|
||
bestHit = h;
|
||
found = true;
|
||
}
|
||
}
|
||
|
||
return found;
|
||
}
|
||
|
||
private bool TryDrainPlug(Ray ray, GameObject playerRoot)
|
||
{
|
||
RaycastHit[] hits = Physics.RaycastAll(ray, interactRange, interactableLayer, QueryTriggerInteraction.Collide);
|
||
foreach (RaycastHit h in hits)
|
||
{
|
||
OilDrainPlug plug = h.collider.GetComponent<OilDrainPlug>();
|
||
if (plug == null) continue;
|
||
|
||
// Пробка доступна только снизу: камера должна быть невысоко над пробкой (присесть [Ctrl])
|
||
if (transform.position.y - h.point.y > 1.25f) continue;
|
||
|
||
ResetProgressTargets();
|
||
CurrentTarget = plug.gameObject;
|
||
uiManager?.ShowPrompt(plug.GetPrompt());
|
||
if (Input.GetKeyDown(primaryKey)) plug.Interact(playerRoot);
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
private WheelBolt FindClosestBoltToRay(Ray ray, Vector3 hitPoint, Collider hitCollider)
|
||
{
|
||
WheelBolt closest = null;
|
||
float minRayDist = 0.085f;
|
||
bool hasWrench = PlayerToolManager.Instance != null
|
||
&& PlayerToolManager.Instance.currentTool == ToolType.Wrench;
|
||
|
||
void CheckWheel(CarPart part)
|
||
{
|
||
if (part == null || part.TotalBoltsCount == 0 || part.State != PartState.Installed) return;
|
||
foreach (WheelBolt b in part.GetComponentsInChildren<WheelBolt>(true))
|
||
{
|
||
if (b == null || !b.IsAvailableForAim) continue;
|
||
// Пустые гнёзда болтов подсвечиваем и ловим только с ключом, чтобы руками можно было снять колесо
|
||
if (!b.IsTightened && !hasWrench) continue;
|
||
|
||
float distToRay = Vector3.Cross(ray.direction, b.WorldBoltCenter - ray.origin).magnitude;
|
||
if (distToRay < minRayDist)
|
||
{
|
||
minRayDist = distToRay;
|
||
closest = b;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (hitCollider != null)
|
||
CheckWheel(hitCollider.GetComponentInParent<CarPart>());
|
||
|
||
Collider[] nearCols = Physics.OverlapSphere(hitPoint, 0.35f, interactableLayer, QueryTriggerInteraction.Collide);
|
||
foreach (var c in nearCols)
|
||
{
|
||
CheckWheel(c.GetComponentInParent<CarPart>());
|
||
|
||
WheelBolt directBolt = c.GetComponent<WheelBolt>();
|
||
if (directBolt != null && directBolt.IsAvailableForAim && (directBolt.IsTightened || hasWrench))
|
||
{
|
||
float distToRay = Vector3.Cross(ray.direction, directBolt.WorldBoltCenter - ray.origin).magnitude;
|
||
if (distToRay < minRayDist)
|
||
{
|
||
minRayDist = distToRay;
|
||
closest = directBolt;
|
||
}
|
||
}
|
||
}
|
||
|
||
return closest;
|
||
}
|
||
|
||
private string BuildPrompt(VehicleInteraction vehicle, IInteractable interactable, CarPart part)
|
||
{
|
||
string partPrompt = (interactable != null && !(interactable is VehicleInteraction))
|
||
? interactable.GetPrompt()
|
||
: string.Empty;
|
||
|
||
bool canEnter = vehicle != null && !vehicle.isPlayerInside;
|
||
|
||
// У непроданной машины на встрече или машины на площадке продажи — подсказка сделки
|
||
if (vehicle != null && part == null)
|
||
{
|
||
CarOwnership own = vehicle.GetComponent<CarOwnership>();
|
||
if (own != null && !own.isOwned)
|
||
partPrompt = $"[B] Сделка: {own.carTitle} — ${own.askingPrice:N0}";
|
||
}
|
||
|
||
if (canEnter && !string.IsNullOrEmpty(partPrompt))
|
||
return $"[F] Сесть | {partPrompt}";
|
||
if (canEnter)
|
||
return "[F] Сесть в машину";
|
||
|
||
return partPrompt;
|
||
}
|
||
|
||
private void ResetProgressTargets()
|
||
{
|
||
if (lastHoveredPart != null) lastHoveredPart.ResetUnbolt();
|
||
lastHoveredPart = null;
|
||
}
|
||
}
|