217 lines
8.2 KiB
C#
217 lines
8.2 KiB
C#
using UnityEngine;
|
|
|
|
[RequireComponent(typeof(BoxCollider))]
|
|
public class WheelBrickSupport : MonoBehaviour, IInteractable
|
|
{
|
|
private Rigidbody carRb;
|
|
private Transform carRoot;
|
|
private WheelCollider targetWheelCollider;
|
|
private string targetWheelName;
|
|
|
|
private GameObject physicsAnchorObj;
|
|
private ConfigurableJoint supportJoint;
|
|
|
|
public static WheelBrickSupport CreateUnderWheel(CarPart missingWheelPart, GameObject customBricksPrefab = null)
|
|
{
|
|
if (missingWheelPart == null) return null;
|
|
|
|
Rigidbody rb = missingWheelPart.GetComponentInParent<Rigidbody>();
|
|
if (rb == null) return null;
|
|
|
|
Transform carTr = rb.transform;
|
|
WheelCollider wc = missingWheelPart.LinkedWheelCollider;
|
|
Vector3 wheelWorldPos = wc != null ? wc.transform.position : missingWheelPart.transform.position;
|
|
|
|
// Находим точку под порогом рядом с колесной аркой (чтобы новое колесо не проходило сквозь кирпичи)
|
|
Vector3 localWheel = carTr.InverseTransformPoint(wheelWorldPos);
|
|
float zOffset = -Mathf.Sign(localWheel.z) * 0.42f;
|
|
float sideSign = Mathf.Sign(localWheel.x);
|
|
if (sideSign == 0f) sideSign = 1f;
|
|
|
|
Vector3 localSupportPoint = new Vector3(localWheel.x * 0.92f, localWheel.y, localWheel.z + zOffset);
|
|
Vector3 worldSupportPoint = carTr.TransformPoint(localSupportPoint);
|
|
|
|
// Ищем высоту асфальта строго под точкой опоры
|
|
float groundY = wheelWorldPos.y - (wc != null ? wc.radius : 0.32f);
|
|
RaycastHit[] hits = Physics.RaycastAll(worldSupportPoint + Vector3.up * 0.5f, Vector3.down, 2.0f, ~0, QueryTriggerInteraction.Ignore);
|
|
foreach (var h in hits)
|
|
{
|
|
if (h.collider.transform.IsChildOf(carTr)) continue;
|
|
groundY = h.point.y;
|
|
break;
|
|
}
|
|
|
|
// Высота от земли до днища/порога
|
|
float sillClearance = wc != null ? Mathf.Clamp((wheelWorldPos.y - groundY) * 0.62f, 0.14f, 0.26f) : 0.18f;
|
|
Vector3 spawnPos = new Vector3(worldSupportPoint.x, groundY, worldSupportPoint.z);
|
|
|
|
GameObject supportObj = new GameObject($"BrickSupport_{missingWheelPart.name}");
|
|
supportObj.layer = missingWheelPart.gameObject.layer;
|
|
supportObj.transform.position = spawnPos;
|
|
supportObj.transform.rotation = carTr.rotation;
|
|
|
|
WheelBrickSupport support = supportObj.AddComponent<WheelBrickSupport>();
|
|
support.Initialize(rb, wc, missingWheelPart.name, sillClearance, customBricksPrefab);
|
|
return support;
|
|
}
|
|
|
|
private void Initialize(Rigidbody rb, WheelCollider wc, string wheelName, float height, GameObject customPrefab)
|
|
{
|
|
carRb = rb;
|
|
carRoot = rb.transform;
|
|
targetWheelCollider = wc;
|
|
targetWheelName = wheelName;
|
|
|
|
// Настраиваем триггер-коллайдер для луча игрока
|
|
BoxCollider col = GetComponent<BoxCollider>();
|
|
col.isTrigger = true;
|
|
col.size = new Vector3(0.32f, height + 0.06f, 0.38f);
|
|
col.center = new Vector3(0f, (height + 0.06f) * 0.5f, 0f);
|
|
|
|
// Создаем визуал кирпичей (префаб или процедурную кладку)
|
|
if (customPrefab != null)
|
|
{
|
|
GameObject visual = Instantiate(customPrefab, transform);
|
|
visual.transform.localPosition = Vector3.zero;
|
|
visual.transform.localRotation = Quaternion.identity;
|
|
foreach (var c in visual.GetComponentsInChildren<Collider>(true)) c.enabled = false;
|
|
}
|
|
else
|
|
{
|
|
BuildProceduralBricks(height);
|
|
}
|
|
|
|
// Фиксируем этот угол машины на текущей высоте, чтобы она не кренилась без колеса
|
|
Vector3 contactWorld = transform.position + Vector3.up * height;
|
|
CreateSupportJoint(contactWorld);
|
|
}
|
|
|
|
private void BuildProceduralBricks(float totalHeight)
|
|
{
|
|
Material brickMat = new Material(Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard"));
|
|
brickMat.color = new Color(0.68f, 0.28f, 0.18f); // Кирпичный цвет
|
|
|
|
int layers = 3;
|
|
float brickH = totalHeight / layers;
|
|
float brickW = 0.12f;
|
|
float brickL = 0.25f;
|
|
|
|
for (int row = 0; row < layers; row++)
|
|
{
|
|
float yPos = (row + 0.5f) * brickH;
|
|
bool rotated = (row % 2 == 1);
|
|
|
|
for (int i = -1; i <= 1; i += 2)
|
|
{
|
|
GameObject brick = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
|
Destroy(brick.GetComponent<Collider>());
|
|
brick.transform.SetParent(transform, false);
|
|
|
|
float offset = i * (brickW * 0.54f);
|
|
brick.transform.localPosition = rotated
|
|
? new Vector3(0f, yPos, offset)
|
|
: new Vector3(offset, yPos, 0f);
|
|
|
|
brick.transform.localRotation = rotated
|
|
? Quaternion.Euler(0f, 90f, 0f)
|
|
: Quaternion.identity;
|
|
|
|
brick.transform.localScale = new Vector3(brickW, brickH * 0.92f, brickL);
|
|
brick.GetComponent<Renderer>().sharedMaterial = brickMat;
|
|
}
|
|
}
|
|
}
|
|
|
|
private void CreateSupportJoint(Vector3 contactWorld)
|
|
{
|
|
if (carRb == null) return;
|
|
|
|
physicsAnchorObj = new GameObject("BricksPhysicsAnchor");
|
|
physicsAnchorObj.transform.position = contactWorld;
|
|
|
|
Rigidbody anchorRb = physicsAnchorObj.AddComponent<Rigidbody>();
|
|
anchorRb.isKinematic = true;
|
|
|
|
supportJoint = physicsAnchorObj.AddComponent<ConfigurableJoint>();
|
|
supportJoint.connectedBody = carRb;
|
|
supportJoint.autoConfigureConnectedAnchor = false;
|
|
supportJoint.anchor = Vector3.zero;
|
|
supportJoint.connectedAnchor = carRb.transform.InverseTransformPoint(contactWorld);
|
|
|
|
JointDrive verticalDrive = new JointDrive
|
|
{
|
|
positionSpring = carRb.mass * 220f,
|
|
positionDamper = carRb.mass * 30f,
|
|
maximumForce = carRb.mass * 80f
|
|
};
|
|
|
|
JointDrive horizontalDrive = new JointDrive
|
|
{
|
|
positionSpring = carRb.mass * 40f,
|
|
positionDamper = carRb.mass * 10f,
|
|
maximumForce = carRb.mass * 30f
|
|
};
|
|
|
|
supportJoint.xDrive = horizontalDrive;
|
|
supportJoint.yDrive = verticalDrive;
|
|
supportJoint.zDrive = horizontalDrive;
|
|
}
|
|
|
|
private bool IsWheelReadyToHoldCar()
|
|
{
|
|
if (carRoot == null) return true;
|
|
|
|
// Если эту сторону уже подняли домкратом — кирпичи тоже можно свободно вытащить
|
|
if (CarJack.IsWheelLifted(transform)) return true;
|
|
|
|
// Ищем установленное на эту ступицу колесо и проверяем его болты
|
|
foreach (CarPart part in carRoot.GetComponentsInChildren<CarPart>(false))
|
|
{
|
|
if (part.State != PartState.Installed) continue;
|
|
|
|
bool isMatchingHub = (targetWheelCollider != null && part.LinkedWheelCollider == targetWheelCollider)
|
|
|| part.name == targetWheelName;
|
|
|
|
if (isMatchingHub)
|
|
{
|
|
return part.TotalBoltsCount == 0 || part.TightenedBoltsCount >= part.TotalBoltsCount;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public string GetPrompt()
|
|
{
|
|
if (!IsWheelReadyToHoldCar())
|
|
{
|
|
return "Машина стоит на кирпичах\n<color=yellow>Сначала установите колесо и закрутите все болты!</color>";
|
|
}
|
|
|
|
return "[E] Убрать кирпичи";
|
|
}
|
|
|
|
public void Interact(GameObject interactor)
|
|
{
|
|
if (!IsWheelReadyToHoldCar()) return;
|
|
|
|
RemoveBricks();
|
|
}
|
|
|
|
public void RemoveBricks()
|
|
{
|
|
if (physicsAnchorObj != null)
|
|
Destroy(physicsAnchorObj);
|
|
|
|
if (carRb != null)
|
|
carRb.WakeUp();
|
|
|
|
Destroy(gameObject);
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
if (physicsAnchorObj != null)
|
|
Destroy(physicsAnchorObj);
|
|
}
|
|
} |