First Commit
This commit is contained in:
commit
eed6b79efc
2836 files changed
+948481
No files matched your search
@@ -0,0 +1,377 @@
|
||||
using UnityEngine;
|
||||
|
||||
public enum DriveType { FWD, RWD, AWD }
|
||||
|
||||
[RequireComponent(typeof(Rigidbody))]
|
||||
public class CarController : MonoBehaviour
|
||||
{
|
||||
public float SpeedKmH => rb != null ? rb.linearVelocity.magnitude * 3.6f : 0f;
|
||||
|
||||
[Header("Аркадные настройки движения")]
|
||||
public DriveType driveType = DriveType.AWD;
|
||||
[SerializeField] private float motorForce = 2200f;
|
||||
[SerializeField] private float maxSpeedKmH = 160f;
|
||||
[SerializeField] private float brakeForce = 4500f;
|
||||
|
||||
[Header("Рулевое управление")]
|
||||
[SerializeField] private float maxSteerAngle = 32f;
|
||||
[SerializeField] private float steerSpeed = 8f;
|
||||
[Tooltip("Во сколько раз уменьшается выворот руля на максимальной скорости")]
|
||||
[SerializeField] private float highSpeedSteerFactor = 0.35f;
|
||||
|
||||
[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;
|
||||
|
||||
[Header("Wheel Colliders")]
|
||||
[SerializeField] private WheelCollider frontLeftCollider;
|
||||
[SerializeField] private WheelCollider frontRightCollider;
|
||||
[SerializeField] private WheelCollider rearLeftCollider;
|
||||
[SerializeField] private WheelCollider rearRightCollider;
|
||||
|
||||
[Header("Wheel Meshes")]
|
||||
[SerializeField] private Transform frontLeftMesh;
|
||||
[SerializeField] private Transform frontRightMesh;
|
||||
[SerializeField] private Transform rearLeftMesh;
|
||||
[SerializeField] private Transform rearRightMesh;
|
||||
|
||||
private Rigidbody rb;
|
||||
private EngineBayManager engineBay;
|
||||
private AudioSource engineAudio;
|
||||
private bool hasDriver;
|
||||
private bool engineRunning;
|
||||
private float startCooldown;
|
||||
private float misfireTimer;
|
||||
|
||||
/// <summary>Двигатель заведен (без исправного АКБ и свечей не заводится).</summary>
|
||||
public bool EngineRunning => engineRunning;
|
||||
/// <summary>Сообщение на приборной панели (например, «Двигатель не заводится!»).</summary>
|
||||
public string DashboardMessage { get; private set; }
|
||||
public float DashboardMessageTimer { get; private set; }
|
||||
public EngineBayManager EngineBay => engineBay;
|
||||
public float MaxSpeedKmH => maxSpeedKmH;
|
||||
|
||||
private float inputVertical;
|
||||
private float inputHorizontal;
|
||||
private bool inputHandbrake = true; // Припаркованная машина стоит на ручнике
|
||||
private float currentSteerAngle;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
rb = GetComponent<Rigidbody>();
|
||||
rb.centerOfMass = centerOfMassOffset;
|
||||
rb.angularDamping = 1.5f;
|
||||
rb.interpolation = RigidbodyInterpolation.Interpolate;
|
||||
engineBay = GetComponent<EngineBayManager>();
|
||||
|
||||
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)
|
||||
{
|
||||
inputVertical = vertical;
|
||||
inputHorizontal = horizontal;
|
||||
inputHandbrake = handbrake;
|
||||
|
||||
if (hasDriver && !engineRunning && Mathf.Abs(vertical) > 0.1f && startCooldown <= 0f)
|
||||
TryStartEngine();
|
||||
}
|
||||
|
||||
/// <summary>Водитель сел/вышел. При выходе двигатель глушится.</summary>
|
||||
public void SetDriver(bool present)
|
||||
{
|
||||
hasDriver = present;
|
||||
if (!present)
|
||||
{
|
||||
StopEngine();
|
||||
ProcessInput(0f, 0f, true);
|
||||
}
|
||||
}
|
||||
|
||||
public void TryStartEngine()
|
||||
{
|
||||
startCooldown = 1.6f;
|
||||
string reason = string.Empty;
|
||||
bool ok = engineBay == null || engineBay.TryStart(out reason);
|
||||
|
||||
if (ok)
|
||||
{
|
||||
engineRunning = true;
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.Starter, transform.position, 0.9f);
|
||||
ShowDashboardMessage("Двигатель запущен", 1.5f);
|
||||
}
|
||||
else
|
||||
{
|
||||
engineRunning = false;
|
||||
ProceduralAudioManager.Instance?.Play(SfxId.RelayClick, transform.position, 1f);
|
||||
ShowDashboardMessage(reason, 4f);
|
||||
}
|
||||
}
|
||||
|
||||
public void StopEngine()
|
||||
{
|
||||
engineRunning = false;
|
||||
if (engineBay != null) engineBay.StopEngine();
|
||||
}
|
||||
|
||||
public void ShowDashboardMessage(string msg, float seconds)
|
||||
{
|
||||
DashboardMessage = msg;
|
||||
DashboardMessageTimer = seconds;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (startCooldown > 0f) startCooldown -= Time.deltaTime;
|
||||
if (DashboardMessageTimer > 0f) DashboardMessageTimer -= Time.deltaTime;
|
||||
|
||||
if (engineBay != null && engineRunning && !engineBay.EngineRunning)
|
||||
{
|
||||
engineRunning = false; // Двигатель заглох (например, сел аккумулятор)
|
||||
ShowDashboardMessage("Двигатель заглох!", 3f);
|
||||
}
|
||||
|
||||
UpdateEngineAudio();
|
||||
}
|
||||
|
||||
private void UpdateEngineAudio()
|
||||
{
|
||||
if (engineAudio == null)
|
||||
{
|
||||
ProceduralAudioManager pam = ProceduralAudioManager.Instance;
|
||||
if (pam == null) return;
|
||||
engineAudio = pam.CreateEngineSource(transform);
|
||||
}
|
||||
|
||||
float sfx = ProceduralAudioManager.Instance != null ? ProceduralAudioManager.Instance.sfxVolume : 0.8f;
|
||||
if (!engineRunning)
|
||||
{
|
||||
engineAudio.volume = Mathf.MoveTowards(engineAudio.volume, 0f, Time.deltaTime * 2f);
|
||||
if (engineAudio.volume <= 0.001f && engineAudio.isPlaying) engineAudio.Stop();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!engineAudio.isPlaying) engineAudio.Play();
|
||||
float load = Mathf.Clamp01(Mathf.Abs(inputVertical));
|
||||
float speed01 = Mathf.Clamp01(SpeedKmH / Mathf.Max(maxSpeedKmH, 1f));
|
||||
float pitch = 0.75f + speed01 * 1.5f + load * 0.15f;
|
||||
float vol = (0.35f + load * 0.35f) * sfx;
|
||||
|
||||
// Пропуски зажигания: мотор «троит» и проседает по громкости
|
||||
if (engineBay != null && (engineBay.IsMisfiring || engineBay.OilKnocking))
|
||||
{
|
||||
misfireTimer -= Time.deltaTime;
|
||||
if (misfireTimer <= 0f)
|
||||
{
|
||||
misfireTimer = Random.Range(0.08f, 0.35f);
|
||||
vol *= Random.Range(0.2f, 0.6f);
|
||||
}
|
||||
}
|
||||
|
||||
engineAudio.pitch = Mathf.Lerp(engineAudio.pitch, pitch, Time.deltaTime * 6f);
|
||||
engineAudio.volume = Mathf.Lerp(engineAudio.volume, vol, Time.deltaTime * 8f);
|
||||
}
|
||||
|
||||
private void FixedUpdate()
|
||||
{
|
||||
HandleSteering();
|
||||
HandleMotorAndBrakes();
|
||||
ApplyAntiRoll(frontLeftCollider, frontRightCollider);
|
||||
ApplyAntiRoll(rearLeftCollider, rearRightCollider);
|
||||
UpdateWheelPoses();
|
||||
}
|
||||
|
||||
private void HandleSteering()
|
||||
{
|
||||
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 localVelZ = transform.InverseTransformDirection(rb.linearVelocity).z;
|
||||
float motor = 0f;
|
||||
float brake = 0f;
|
||||
|
||||
// Связь физики с техсостоянием: мощность и тормоза зависят от агрегатов и жидкостей под капотом
|
||||
float powerMul = engineBay != null ? engineBay.PowerMultiplier : 1f;
|
||||
float brakeMul = engineBay != null ? engineBay.BrakeMultiplier : 1f;
|
||||
float speedLimit = engineBay != null ? Mathf.Min(maxSpeedKmH, engineBay.MaxSpeedLimit) : maxSpeedKmH;
|
||||
float effectiveMotor = engineRunning ? motorForce * powerMul : 0f;
|
||||
float effectiveBrake = brakeForce * brakeMul;
|
||||
|
||||
if (inputVertical > 0.01f)
|
||||
{
|
||||
if (localVelZ < -1.5f)
|
||||
brake = effectiveBrake;
|
||||
else if (SpeedKmH < speedLimit)
|
||||
motor = inputVertical * effectiveMotor;
|
||||
}
|
||||
else if (inputVertical < -0.01f)
|
||||
{
|
||||
if (localVelZ > 1.5f)
|
||||
brake = effectiveBrake;
|
||||
else if (SpeedKmH < 45f)
|
||||
motor = inputVertical * effectiveMotor * 0.7f;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Плавное торможение двигателем, когда газ отпущен
|
||||
brake = 150f;
|
||||
}
|
||||
|
||||
if (inputHandbrake)
|
||||
{
|
||||
motor = 0f;
|
||||
brake = effectiveBrake * 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()
|
||||
{
|
||||
UpdateWheelPose(frontLeftCollider, frontLeftMesh);
|
||||
UpdateWheelPose(frontRightCollider, frontRightMesh);
|
||||
UpdateWheelPose(rearLeftCollider, rearLeftMesh);
|
||||
UpdateWheelPose(rearRightCollider, rearRightMesh);
|
||||
}
|
||||
|
||||
private void UpdateWheelPose(WheelCollider collider, Transform mesh)
|
||||
{
|
||||
if (mesh == null || collider == null || !collider.enabled || !mesh.IsChildOf(transform))
|
||||
return;
|
||||
|
||||
collider.GetWorldPose(out Vector3 pos, out Quaternion rot);
|
||||
mesh.position = pos;
|
||||
|
||||
// Если на эту ступицу поставили запасное колесо с противоположной стороны машины (развернутое на 180°),
|
||||
// сохраняем его разворот при вращении колеса!
|
||||
float angleDiff = Quaternion.Angle(mesh.localRotation, Quaternion.Euler(0f, 180f, 0f));
|
||||
if (angleDiff < 60f)
|
||||
mesh.rotation = rot * Quaternion.Euler(0f, 180f, 0f);
|
||||
else
|
||||
mesh.rotation = rot;
|
||||
}
|
||||
|
||||
public void ReplaceWheelMesh(WheelCollider col, Transform newMesh)
|
||||
{
|
||||
if (col == frontLeftCollider) frontLeftMesh = newMesh;
|
||||
else if (col == frontRightCollider) frontRightMesh = newMesh;
|
||||
else if (col == rearLeftCollider) rearLeftMesh = newMesh;
|
||||
else if (col == rearRightCollider) rearRightMesh = newMesh;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user