Снятие колес работает, покраска тоже более менее. Физика просто говно щяс
This commit is contained in:
1 parent
d4c84b10df
commit
2ce853999d
67 files changed
+155919
-1996
No files matched your search
@@ -1,170 +0,0 @@
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(Rigidbody))]
|
||||
public class AdvancedCarController : MonoBehaviour
|
||||
{
|
||||
public float SpeedKmH => rb.linearVelocity.magnitude * 3.6f;
|
||||
|
||||
[Header("Данные авто")]
|
||||
[SerializeField] private CarPhysicsData data;
|
||||
|
||||
[Header("Колеса (WheelColliders)")]
|
||||
[SerializeField] private WheelCollider[] frontWheels;
|
||||
[SerializeField] private WheelCollider[] rearWheels;
|
||||
|
||||
[Header("Состояние деталей (Для диплома)")]
|
||||
[Range(0.1f, 1f)] public float engineCondition = 1f; // 1 - новое, 0.1 - убитое (не тянет)
|
||||
[Range(0.1f, 1f)] public float tiresCondition = 1f; // Влияет на держак резины
|
||||
|
||||
// Состояние авто
|
||||
public float CurrentSpeedKmH => rb.linearVelocity.magnitude * 3.6f;
|
||||
public float EngineRPM { get; private set; }
|
||||
public int CurrentGear { get; private set; }
|
||||
|
||||
private Rigidbody rb;
|
||||
private float currentSteerAngle;
|
||||
private WheelFrictionCurve originalRearSidewaysFriction;
|
||||
|
||||
// Ввод
|
||||
private float moveInput, steerInput;
|
||||
private bool isBraking, isHandbrake;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
rb = GetComponent<Rigidbody>();
|
||||
rb.centerOfMass = data.centerOfMassOffset; // Понижаем центр масс для стабильности
|
||||
|
||||
// Запоминаем оригинальное трение для ручника
|
||||
if (rearWheels.Length > 0)
|
||||
originalRearSidewaysFriction = rearWheels[0].sidewaysFriction;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
// Чтение инпута (можно заменить на новый Input System)
|
||||
moveInput = Input.GetAxis("Vertical");
|
||||
steerInput = Input.GetAxis("Horizontal");
|
||||
isBraking = Input.GetKey(KeyCode.Space) || (moveInput < 0 && CurrentSpeedKmH > 5f);
|
||||
isHandbrake = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.Space);
|
||||
}
|
||||
|
||||
private void FixedUpdate()
|
||||
{
|
||||
ApplySteering();
|
||||
ProcessEngineAndGears();
|
||||
ApplyAntiRollBar();
|
||||
ProcessHandbrake();
|
||||
}
|
||||
|
||||
public void ProcessInput(float vertical, float horizontal, bool handbrake)
|
||||
{
|
||||
moveInput = vertical;
|
||||
steerInput = horizontal;
|
||||
isHandbrake = handbrake;
|
||||
}
|
||||
|
||||
private void ApplySteering()
|
||||
{
|
||||
// 1. Угол зависит от скорости (на 100 км/ч руль не вывернется на 35 градусов)
|
||||
float speedMultiplier = data.steerAngleBySpeed.Evaluate(CurrentSpeedKmH);
|
||||
float targetSteer = steerInput * data.maxSteerAngle * speedMultiplier;
|
||||
|
||||
// 2. Сглаживание поворота (руль не дергается мгновенно)
|
||||
currentSteerAngle = Mathf.Lerp(currentSteerAngle, targetSteer, Time.fixedDeltaTime * data.steerSmoothing);
|
||||
|
||||
foreach (var wheel in frontWheels)
|
||||
{
|
||||
wheel.steerAngle = currentSteerAngle;
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessEngineAndGears()
|
||||
{
|
||||
// Считаем средние обороты ведущих колес (допустим, задний привод)
|
||||
float wheelRPM = 0;
|
||||
foreach (var w in rearWheels) wheelRPM += Mathf.Abs(w.rpm);
|
||||
wheelRPM /= rearWheels.Length;
|
||||
|
||||
// Вычисляем обороты двигателя через передаточные числа
|
||||
float gearRatio = data.gearRatios[CurrentGear];
|
||||
EngineRPM = Mathf.Clamp(wheelRPM * gearRatio * data.finalDrive, data.minRPM, data.maxRPM);
|
||||
|
||||
// Автоматическая коробка передач
|
||||
if (EngineRPM > data.shiftUpRPM && CurrentGear < data.gearRatios.Length - 1)
|
||||
CurrentGear++;
|
||||
else if (EngineRPM < data.shiftDownRPM && CurrentGear > 0)
|
||||
CurrentGear--;
|
||||
|
||||
// Получаем крутящий момент по графику и умножаем на состояние двигателя!
|
||||
float motorTorque = data.torqueCurve.Evaluate(EngineRPM) * gearRatio * data.finalDrive;
|
||||
float finalTorque = moveInput * motorTorque * engineCondition;
|
||||
|
||||
// Применяем газ или тормоз
|
||||
foreach (var wheel in rearWheels)
|
||||
{
|
||||
if (isBraking)
|
||||
{
|
||||
wheel.motorTorque = 0;
|
||||
wheel.brakeTorque = data.brakeForce;
|
||||
}
|
||||
else
|
||||
{
|
||||
wheel.motorTorque = finalTorque / rearWheels.Length;
|
||||
wheel.brakeTorque = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessHandbrake()
|
||||
{
|
||||
foreach (var wheel in rearWheels)
|
||||
{
|
||||
if (isHandbrake)
|
||||
{
|
||||
wheel.brakeTorque = data.brakeForce;
|
||||
|
||||
// ДРИФТ: Уменьшаем боковое сцепление, умножая на износ шин
|
||||
WheelFrictionCurve fc = wheel.sidewaysFriction;
|
||||
fc.stiffness = originalRearSidewaysFriction.stiffness * data.handbrakeFrictionMultiplier * tiresCondition;
|
||||
wheel.sidewaysFriction = fc;
|
||||
}
|
||||
else if (!isBraking)
|
||||
{
|
||||
wheel.brakeTorque = 0;
|
||||
|
||||
// Возвращаем обычное сцепление с поправкой на убитость шин
|
||||
WheelFrictionCurve fc = wheel.sidewaysFriction;
|
||||
fc.stiffness = originalRearSidewaysFriction.stiffness * tiresCondition;
|
||||
wheel.sidewaysFriction = fc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyAntiRollBar()
|
||||
{
|
||||
// Стабилизатор поперечной устойчивости для передней и задней оси
|
||||
ApplyAxleAntiRoll(frontWheels[0], frontWheels[1]);
|
||||
ApplyAxleAntiRoll(rearWheels[0], rearWheels[1]);
|
||||
}
|
||||
|
||||
private void ApplyAxleAntiRoll(WheelCollider left, WheelCollider right)
|
||||
{
|
||||
float travelL = 1.0f;
|
||||
float travelR = 1.0f;
|
||||
|
||||
bool groundedL = left.GetGroundHit(out WheelHit hitL);
|
||||
if (groundedL) travelL = (-left.transform.InverseTransformPoint(hitL.point).y - left.radius) / left.suspensionDistance;
|
||||
|
||||
bool groundedR = right.GetGroundHit(out WheelHit hitR);
|
||||
if (groundedR) travelR = (-right.transform.InverseTransformPoint(hitR.point).y - right.radius) / right.suspensionDistance;
|
||||
|
||||
// Разница сжатия подвески
|
||||
float antiRollVal = (travelL - travelR) * data.antiRollForce;
|
||||
|
||||
// Применяем противодействующую силу (прижимаем поднявшееся колесо)
|
||||
if (groundedL) rb.AddForceAtPosition(left.transform.up * -antiRollVal, left.transform.position);
|
||||
if (groundedR) rb.AddForceAtPosition(right.transform.up * antiRollVal, right.transform.position);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c02b03f912164de9ae5c7659d886fae9
|
||||
timeCreated: 1791809782
|
||||
@@ -2,29 +2,29 @@ using UnityEngine;
|
||||
|
||||
public enum DriveType { FWD, RWD, AWD }
|
||||
|
||||
[RequireComponent(typeof(Rigidbody))]
|
||||
public class CarController : MonoBehaviour
|
||||
{
|
||||
public float SpeedKmH => rb.linearVelocity.magnitude * 3.6f;
|
||||
|
||||
[Header("Drive Settings")]
|
||||
public float SpeedKmH => rb != null ? rb.linearVelocity.magnitude * 3.6f : 0f;
|
||||
|
||||
[Header("Аркадные настройки движения")]
|
||||
public DriveType driveType = DriveType.AWD;
|
||||
[SerializeField] private float motorForce = 1500f;
|
||||
[SerializeField] private float brakeForce = 3000f;
|
||||
[SerializeField] private float maxSteerAngle = 30f;
|
||||
[SerializeField] private float motorForce = 2200f;
|
||||
[SerializeField] private float maxSpeedKmH = 160f;
|
||||
[SerializeField] private float brakeForce = 4500f;
|
||||
|
||||
[Header("Grip Settings (Friction Stiffness)")]
|
||||
[Tooltip("Сцепление для переднего привода (FWD)")]
|
||||
[SerializeField] private float fwdFrontGrip = 1.2f;
|
||||
[SerializeField] private float fwdRearGrip = 2.0f;
|
||||
[Header("Рулевое управление")]
|
||||
[SerializeField] private float maxSteerAngle = 32f;
|
||||
[SerializeField] private float steerSpeed = 8f;
|
||||
[Tooltip("Во сколько раз уменьшается выворот руля на максимальной скорости")]
|
||||
[SerializeField] private float highSpeedSteerFactor = 0.35f;
|
||||
|
||||
[Tooltip("Сцепление для заднего привода (RWD)")]
|
||||
[SerializeField] private float rwdFrontGrip = 2.0f;
|
||||
[SerializeField] private float rwdRearGrip = 1.2f;
|
||||
[Header("Устойчивость и Дрифт")]
|
||||
[SerializeField] private Vector3 centerOfMassOffset = new Vector3(0f, -0.45f, 0f);
|
||||
[SerializeField] private float antiRollForce = 8000f;
|
||||
[SerializeField] private float normalGrip = 2.2f;
|
||||
[SerializeField] private float handbrakeRearGrip = 0.65f;
|
||||
|
||||
[Tooltip("Сцепление для полного привода (AWD)")]
|
||||
[SerializeField] private float awdFrontGrip = 2.5f;
|
||||
[SerializeField] private float awdRearGrip = 2.5f;
|
||||
|
||||
[Header("Wheel Colliders")]
|
||||
[SerializeField] private WheelCollider frontLeftCollider;
|
||||
[SerializeField] private WheelCollider frontRightCollider;
|
||||
@@ -38,15 +38,41 @@ public class CarController : MonoBehaviour
|
||||
[SerializeField] private Transform rearRightMesh;
|
||||
|
||||
private Rigidbody rb;
|
||||
|
||||
// Входящие данные от игрока
|
||||
private float inputVertical;
|
||||
private float inputHorizontal;
|
||||
private bool inputHandbrake;
|
||||
private float currentSteerAngle;
|
||||
|
||||
private void Start()
|
||||
private void Awake()
|
||||
{
|
||||
rb = GetComponent<Rigidbody>();
|
||||
rb.centerOfMass = centerOfMassOffset;
|
||||
rb.angularDamping = 1.5f;
|
||||
|
||||
SetupArcadeWheel(frontLeftCollider);
|
||||
SetupArcadeWheel(frontRightCollider);
|
||||
SetupArcadeWheel(rearLeftCollider);
|
||||
SetupArcadeWheel(rearRightCollider);
|
||||
}
|
||||
|
||||
private void SetupArcadeWheel(WheelCollider wc)
|
||||
{
|
||||
if (wc == null) return;
|
||||
|
||||
JointSpring spring = wc.suspensionSpring;
|
||||
spring.spring = 35000f;
|
||||
spring.damper = 4500f;
|
||||
spring.targetPosition = 0.5f;
|
||||
wc.suspensionSpring = spring;
|
||||
wc.suspensionDistance = 0.18f;
|
||||
|
||||
WheelFrictionCurve fwd = wc.forwardFriction;
|
||||
fwd.stiffness = 2.0f;
|
||||
wc.forwardFriction = fwd;
|
||||
|
||||
WheelFrictionCurve side = wc.sidewaysFriction;
|
||||
side.stiffness = normalGrip;
|
||||
wc.sidewaysFriction = side;
|
||||
}
|
||||
|
||||
public void ProcessInput(float vertical, float horizontal, bool handbrake)
|
||||
@@ -60,117 +86,138 @@ public class CarController : MonoBehaviour
|
||||
{
|
||||
HandleSteering();
|
||||
HandleMotorAndBrakes();
|
||||
ApplyAntiRoll(frontLeftCollider, frontRightCollider);
|
||||
ApplyAntiRoll(rearLeftCollider, rearRightCollider);
|
||||
UpdateWheelPoses();
|
||||
}
|
||||
|
||||
private void HandleSteering()
|
||||
{
|
||||
float steerAngle = maxSteerAngle * inputHorizontal;
|
||||
frontLeftCollider.steerAngle = steerAngle;
|
||||
frontRightCollider.steerAngle = steerAngle;
|
||||
float speedFactor = Mathf.Lerp(1f, highSpeedSteerFactor, SpeedKmH / maxSpeedKmH);
|
||||
float targetSteer = inputHorizontal * maxSteerAngle * speedFactor;
|
||||
currentSteerAngle = Mathf.Lerp(currentSteerAngle, targetSteer, Time.fixedDeltaTime * steerSpeed);
|
||||
|
||||
if (frontLeftCollider != null) frontLeftCollider.steerAngle = currentSteerAngle;
|
||||
if (frontRightCollider != null) frontRightCollider.steerAngle = currentSteerAngle;
|
||||
}
|
||||
|
||||
private void HandleMotorAndBrakes()
|
||||
{
|
||||
float currentMotorTorque = 0f;
|
||||
float currentBrakeTorque = 0f;
|
||||
float localVelZ = transform.InverseTransformDirection(rb.linearVelocity).z;
|
||||
float motor = 0f;
|
||||
float brake = 0f;
|
||||
|
||||
// Определяем, куда физически движется машина (вперед или назад)
|
||||
float localVelocityZ = transform.InverseTransformDirection(rb.linearVelocity).z;
|
||||
|
||||
// ЛОГИКА ГАЗА (W)
|
||||
if (inputVertical > 0)
|
||||
if (inputVertical > 0.01f)
|
||||
{
|
||||
if (localVelocityZ < -1f) // Если катимся назад, а жмем W -> Тормозим
|
||||
currentBrakeTorque = brakeForce;
|
||||
else // Иначе едем вперед
|
||||
currentMotorTorque = inputVertical * motorForce;
|
||||
if (localVelZ < -1.5f)
|
||||
brake = brakeForce;
|
||||
else if (SpeedKmH < maxSpeedKmH)
|
||||
motor = inputVertical * motorForce;
|
||||
}
|
||||
// ЛОГИКА ТОРМОЗА И ЗАДНЕГО ХОДА (S)
|
||||
else if (inputVertical < 0)
|
||||
else if (inputVertical < -0.01f)
|
||||
{
|
||||
if (localVelocityZ > 1f) // Если едем вперед, а жмем S -> Тормозим
|
||||
currentBrakeTorque = brakeForce;
|
||||
else // Иначе сдаем назад (inputVertical отрицательный, поэтому момент тоже отрицательный)
|
||||
currentMotorTorque = inputVertical * motorForce;
|
||||
}
|
||||
|
||||
// ЛОГИКА РУЧНИКА (Пробел)
|
||||
if (inputHandbrake)
|
||||
{
|
||||
currentMotorTorque = 0f; // Глушим газ
|
||||
currentBrakeTorque = brakeForce * 2f; // Ручник хватает сильнее обычного тормоза
|
||||
}
|
||||
|
||||
ApplyBrakes(currentBrakeTorque, inputHandbrake);
|
||||
ApplyMotor(currentMotorTorque);
|
||||
}
|
||||
|
||||
private void ApplyMotor(float torque)
|
||||
{
|
||||
// Получаем базовые настройки трения
|
||||
WheelFrictionCurve frontFriction = frontLeftCollider.sidewaysFriction;
|
||||
WheelFrictionCurve rearFriction = rearLeftCollider.sidewaysFriction;
|
||||
|
||||
switch (driveType)
|
||||
{
|
||||
case DriveType.FWD:
|
||||
frontLeftCollider.motorTorque = torque;
|
||||
frontRightCollider.motorTorque = torque;
|
||||
rearLeftCollider.motorTorque = 0;
|
||||
rearRightCollider.motorTorque = 0;
|
||||
|
||||
frontFriction.stiffness = fwdFrontGrip;
|
||||
rearFriction.stiffness = fwdRearGrip;
|
||||
break;
|
||||
|
||||
case DriveType.RWD:
|
||||
frontLeftCollider.motorTorque = 0;
|
||||
frontRightCollider.motorTorque = 0;
|
||||
rearLeftCollider.motorTorque = torque;
|
||||
rearRightCollider.motorTorque = torque;
|
||||
|
||||
frontFriction.stiffness = rwdFrontGrip;
|
||||
rearFriction.stiffness = rwdRearGrip;
|
||||
break;
|
||||
|
||||
case DriveType.AWD:
|
||||
float halfTorque = torque / 2f;
|
||||
frontLeftCollider.motorTorque = halfTorque;
|
||||
frontRightCollider.motorTorque = halfTorque;
|
||||
rearLeftCollider.motorTorque = halfTorque;
|
||||
rearRightCollider.motorTorque = halfTorque;
|
||||
|
||||
frontFriction.stiffness = awdFrontGrip;
|
||||
rearFriction.stiffness = awdRearGrip;
|
||||
break;
|
||||
}
|
||||
|
||||
// Применяем измененное трение к колесам
|
||||
frontLeftCollider.sidewaysFriction = frontFriction;
|
||||
frontRightCollider.sidewaysFriction = frontFriction;
|
||||
rearLeftCollider.sidewaysFriction = rearFriction;
|
||||
rearRightCollider.sidewaysFriction = rearFriction;
|
||||
}
|
||||
|
||||
private void ApplyBrakes(float brake, bool isHandbrake)
|
||||
{
|
||||
if (isHandbrake)
|
||||
{
|
||||
// Ручник блокирует только задние колеса (эффект заноса)
|
||||
frontLeftCollider.brakeTorque = 0;
|
||||
frontRightCollider.brakeTorque = 0;
|
||||
rearLeftCollider.brakeTorque = brake;
|
||||
rearRightCollider.brakeTorque = brake;
|
||||
if (localVelZ > 1.5f)
|
||||
brake = brakeForce;
|
||||
else if (SpeedKmH < 45f)
|
||||
motor = inputVertical * motorForce * 0.7f;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Обычный тормоз (S) срабатывает на все колеса, передок сильнее
|
||||
frontLeftCollider.brakeTorque = brake;
|
||||
frontRightCollider.brakeTorque = brake;
|
||||
rearLeftCollider.brakeTorque = brake * 0.5f;
|
||||
rearRightCollider.brakeTorque = brake * 0.5f;
|
||||
// Плавное торможение двигателем, когда газ отпущен
|
||||
brake = 150f;
|
||||
}
|
||||
|
||||
if (inputHandbrake)
|
||||
{
|
||||
motor = 0f;
|
||||
brake = brakeForce * 1.5f;
|
||||
}
|
||||
|
||||
ApplyDriveTorque(motor);
|
||||
ApplyBrakesAndDrift(brake, inputHandbrake);
|
||||
}
|
||||
|
||||
private void ApplyDriveTorque(float torque)
|
||||
{
|
||||
if (driveType == DriveType.FWD)
|
||||
{
|
||||
SetMotor(frontLeftCollider, torque);
|
||||
SetMotor(frontRightCollider, torque);
|
||||
SetMotor(rearLeftCollider, 0f);
|
||||
SetMotor(rearRightCollider, 0f);
|
||||
}
|
||||
else if (driveType == DriveType.RWD)
|
||||
{
|
||||
SetMotor(frontLeftCollider, 0f);
|
||||
SetMotor(frontRightCollider, 0f);
|
||||
SetMotor(rearLeftCollider, torque);
|
||||
SetMotor(rearRightCollider, torque);
|
||||
}
|
||||
else
|
||||
{
|
||||
float half = torque * 0.55f;
|
||||
SetMotor(frontLeftCollider, half);
|
||||
SetMotor(frontRightCollider, half);
|
||||
SetMotor(rearLeftCollider, half);
|
||||
SetMotor(rearRightCollider, half);
|
||||
}
|
||||
}
|
||||
|
||||
private void SetMotor(WheelCollider wc, float val)
|
||||
{
|
||||
if (wc != null && wc.enabled) wc.motorTorque = val;
|
||||
}
|
||||
|
||||
private void ApplyBrakesAndDrift(float brake, bool handbrake)
|
||||
{
|
||||
float targetRearStiffness = handbrake ? handbrakeRearGrip : normalGrip;
|
||||
|
||||
SetRearGrip(rearLeftCollider, targetRearStiffness);
|
||||
SetRearGrip(rearRightCollider, targetRearStiffness);
|
||||
|
||||
if (handbrake)
|
||||
{
|
||||
if (frontLeftCollider != null) frontLeftCollider.brakeTorque = 0f;
|
||||
if (frontRightCollider != null) frontRightCollider.brakeTorque = 0f;
|
||||
if (rearLeftCollider != null) rearLeftCollider.brakeTorque = brake;
|
||||
if (rearRightCollider != null) rearRightCollider.brakeTorque = brake;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (frontLeftCollider != null) frontLeftCollider.brakeTorque = brake;
|
||||
if (frontRightCollider != null) frontRightCollider.brakeTorque = brake;
|
||||
if (rearLeftCollider != null) rearLeftCollider.brakeTorque = brake * 0.6f;
|
||||
if (rearRightCollider != null) rearRightCollider.brakeTorque = brake * 0.6f;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetRearGrip(WheelCollider wc, float targetStiff)
|
||||
{
|
||||
if (wc == null) return;
|
||||
WheelFrictionCurve side = wc.sidewaysFriction;
|
||||
side.stiffness = Mathf.Lerp(side.stiffness, targetStiff, Time.fixedDeltaTime * 10f);
|
||||
wc.sidewaysFriction = side;
|
||||
}
|
||||
|
||||
private void ApplyAntiRoll(WheelCollider left, WheelCollider right)
|
||||
{
|
||||
if (left == null || right == null || !left.enabled || !right.enabled) return;
|
||||
|
||||
float travelL = 1f;
|
||||
float travelR = 1f;
|
||||
|
||||
bool groundedL = left.GetGroundHit(out WheelHit hitL);
|
||||
if (groundedL)
|
||||
travelL = (-left.transform.InverseTransformPoint(hitL.point).y - left.radius) / left.suspensionDistance;
|
||||
|
||||
bool groundedR = right.GetGroundHit(out WheelHit hitR);
|
||||
if (groundedR)
|
||||
travelR = (-right.transform.InverseTransformPoint(hitR.point).y - right.radius) / right.suspensionDistance;
|
||||
|
||||
float force = (travelL - travelR) * antiRollForce;
|
||||
|
||||
if (groundedL) rb.AddForceAtPosition(left.transform.up * -force, left.transform.position);
|
||||
if (groundedR) rb.AddForceAtPosition(right.transform.up * force, right.transform.position);
|
||||
}
|
||||
|
||||
private void UpdateWheelPoses()
|
||||
@@ -183,9 +230,7 @@ public class CarController : MonoBehaviour
|
||||
|
||||
private void UpdateWheelPose(WheelCollider collider, Transform mesh)
|
||||
{
|
||||
// Если меш не назначен, коллайдер выключен или колесо снято с машины
|
||||
// (больше не является дочерним объектом этого авто) — не двигаем его!
|
||||
if (mesh == null || collider == null || !collider.enabled || !mesh.IsChildOf(transform))
|
||||
if (mesh == null || collider == null || !collider.enabled || !mesh.IsChildOf(transform))
|
||||
return;
|
||||
|
||||
collider.GetWorldPose(out Vector3 pos, out Quaternion rot);
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
using UnityEngine;
|
||||
|
||||
[CreateAssetMenu(fileName = "NewCarPhysics", menuName = "Car System/Physics Data")]
|
||||
public class CarPhysicsData : ScriptableObject
|
||||
{
|
||||
[Header("Двигатель и КПП")]
|
||||
public AnimationCurve torqueCurve; // Кривая: X - обороты (RPM), Y - крутящий момент (Nm)
|
||||
public float maxRPM = 7000f;
|
||||
public float minRPM = 800f;
|
||||
public float shiftUpRPM = 6000f;
|
||||
public float shiftDownRPM = 2500f;
|
||||
public float[] gearRatios = { 3.1f, 2.2f, 1.6f, 1.2f, 0.9f, 0.7f };
|
||||
public float finalDrive = 3.4f;
|
||||
|
||||
[Header("Рулевое управление")]
|
||||
public float maxSteerAngle = 35f;
|
||||
public float steerSmoothing = 10f; // Скорость поворота руля
|
||||
[Tooltip("Как сильно режется угол поворота на высокой скорости")]
|
||||
public AnimationCurve steerAngleBySpeed; // X - скорость (км/ч), Y - множитель угла (0..1)
|
||||
|
||||
[Header("Подвеска и физика")]
|
||||
public Vector3 centerOfMassOffset = new Vector3(0, -0.2f, 0); // Пониженный центр масс
|
||||
public float antiRollForce = 5000f; // Стабилизатор поперечной устойчивости
|
||||
public float brakeForce = 3000f;
|
||||
|
||||
[Header("Дрифт (Ручник)")]
|
||||
public float handbrakeFrictionMultiplier = 0.3f; // Насколько скользкой становится задняя ось
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 396086e692304e97aab2b9b09066d2b5
|
||||
timeCreated: 1791809619
|
||||
@@ -1,56 +0,0 @@
|
||||
using UnityEngine;
|
||||
|
||||
[ExecuteInEditMode]
|
||||
public class EasySuspension : MonoBehaviour
|
||||
{
|
||||
[Range(0.1f, 20f)] public float naturalFrequency = 10f;
|
||||
[Range(0.1f, 3f)] public float dampingRatio = 0.8f;
|
||||
[Range(-1f, 1f)] public float forceShift = 0.03f;
|
||||
public bool setSuspensionDistance = true;
|
||||
|
||||
private WheelCollider[] wheelColliders;
|
||||
private Rigidbody rb;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
CacheComponents();
|
||||
}
|
||||
|
||||
private void CacheComponents()
|
||||
{
|
||||
wheelColliders = GetComponentsInChildren<WheelCollider>(true);
|
||||
rb = GetComponent<Rigidbody>();
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (wheelColliders == null || rb == null)
|
||||
{
|
||||
CacheComponents();
|
||||
if (wheelColliders == null || rb == null) return;
|
||||
}
|
||||
|
||||
foreach (WheelCollider wc in wheelColliders)
|
||||
{
|
||||
// ЗАЩИТА: если колесо снято (выключено) или не несет нагрузки — пропускаем, чтобы не делить на 0!
|
||||
if (wc == null || !wc.enabled || wc.sprungMass <= 0.01f) continue;
|
||||
|
||||
JointSpring spring = wc.suspensionSpring;
|
||||
|
||||
spring.spring = Mathf.Pow(Mathf.Sqrt(wc.sprungMass) * naturalFrequency, 2);
|
||||
spring.damper = 2f * dampingRatio * Mathf.Sqrt(spring.spring * wc.sprungMass);
|
||||
|
||||
wc.suspensionSpring = spring;
|
||||
|
||||
Vector3 wheelRelativeBody = transform.InverseTransformPoint(wc.transform.position);
|
||||
float distance = rb.centerOfMass.y - wheelRelativeBody.y + wc.radius;
|
||||
|
||||
wc.forceAppPointDistance = distance - forceShift;
|
||||
|
||||
if (spring.targetPosition > 0.001f && spring.spring > 0.001f && setSuspensionDistance)
|
||||
{
|
||||
wc.suspensionDistance = wc.sprungMass * Physics.gravity.magnitude / (spring.targetPosition * spring.spring);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4d9eeaad380562f42bac8b304778252c
|
||||
@@ -1,29 +0,0 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class WheelVisuals : MonoBehaviour
|
||||
{
|
||||
[System.Serializable]
|
||||
public struct WheelPair
|
||||
{
|
||||
public WheelCollider collider;
|
||||
public Transform mesh;
|
||||
}
|
||||
|
||||
[Header("Привязка колес")]
|
||||
public WheelPair[] wheels;
|
||||
|
||||
private void Update()
|
||||
{
|
||||
foreach (var w in wheels)
|
||||
{
|
||||
if (w.collider == null || w.mesh == null) continue;
|
||||
|
||||
// Получаем физическую позицию колеса
|
||||
w.collider.GetWorldPose(out Vector3 pos, out Quaternion rot);
|
||||
|
||||
// Применяем к 3D-модели
|
||||
w.mesh.position = pos;
|
||||
w.mesh.rotation = rot;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ce1b65bf09494194a68749d417b0e17a
|
||||
timeCreated: 1791809850
|
||||
Reference in new issue
Block a user