CarController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. using System;
  2. using UnityEngine;
  3. namespace UnityStandardAssets.Vehicles.Car
  4. {
  5. internal enum CarDriveType
  6. {
  7. FrontWheelDrive,
  8. RearWheelDrive,
  9. FourWheelDrive
  10. }
  11. internal enum SpeedType
  12. {
  13. MPH,
  14. KPH
  15. }
  16. public class CarController : MonoBehaviour
  17. {
  18. [SerializeField] private CarDriveType m_CarDriveType = CarDriveType.FourWheelDrive;
  19. [SerializeField] private WheelCollider[] m_WheelColliders = new WheelCollider[4];
  20. [SerializeField] private GameObject[] m_WheelMeshes = new GameObject[4];
  21. [SerializeField] private WheelEffects[] m_WheelEffects = new WheelEffects[4];
  22. [SerializeField] private Vector3 m_CentreOfMassOffset;
  23. [SerializeField] private float m_MaximumSteerAngle;
  24. [Range(0, 1)] [SerializeField] private float m_SteerHelper; // 0 is raw physics , 1 the car will grip in the direction it is facing
  25. [Range(0, 1)] [SerializeField] private float m_TractionControl; // 0 is no traction control, 1 is full interference
  26. [SerializeField] private float m_FullTorqueOverAllWheels;
  27. [SerializeField] private float m_ReverseTorque;
  28. [SerializeField] private float m_MaxHandbrakeTorque;
  29. [SerializeField] private float m_Downforce = 100f;
  30. [SerializeField] private SpeedType m_SpeedType;
  31. [SerializeField] private float m_Topspeed = 200;
  32. [SerializeField] private static int NoOfGears = 5;
  33. [SerializeField] private float m_RevRangeBoundary = 1f;
  34. [SerializeField] private float m_SlipLimit;
  35. [SerializeField] private float m_BrakeTorque;
  36. private Quaternion[] m_WheelMeshLocalRotations;
  37. private Vector3 m_Prevpos, m_Pos;
  38. private float m_SteerAngle;
  39. private int m_GearNum;
  40. private float m_GearFactor;
  41. private float m_OldRotation;
  42. private float m_CurrentTorque;
  43. private Rigidbody m_Rigidbody;
  44. private const float k_ReversingThreshold = 0.01f;
  45. public bool Skidding { get; private set; }
  46. public float BrakeInput { get; private set; }
  47. public float CurrentSteerAngle{ get { return m_SteerAngle; }}
  48. public float CurrentSpeed{ get { return m_Rigidbody.velocity.magnitude*2.23693629f; }}
  49. public float MaxSpeed{get { return m_Topspeed; }}
  50. public float Revs { get; private set; }
  51. public float AccelInput { get; private set; }
  52. // Use this for initialization
  53. private void Start()
  54. {
  55. m_WheelMeshLocalRotations = new Quaternion[4];
  56. for (int i = 0; i < 4; i++)
  57. {
  58. m_WheelMeshLocalRotations[i] = m_WheelMeshes[i].transform.localRotation;
  59. }
  60. m_WheelColliders[0].attachedRigidbody.centerOfMass = m_CentreOfMassOffset;
  61. m_MaxHandbrakeTorque = float.MaxValue;
  62. m_Rigidbody = GetComponent<Rigidbody>();
  63. m_CurrentTorque = m_FullTorqueOverAllWheels - (m_TractionControl*m_FullTorqueOverAllWheels);
  64. }
  65. private void GearChanging()
  66. {
  67. float f = Mathf.Abs(CurrentSpeed/MaxSpeed);
  68. float upgearlimit = (1/(float) NoOfGears)*(m_GearNum + 1);
  69. float downgearlimit = (1/(float) NoOfGears)*m_GearNum;
  70. if (m_GearNum > 0 && f < downgearlimit)
  71. {
  72. m_GearNum--;
  73. }
  74. if (f > upgearlimit && (m_GearNum < (NoOfGears - 1)))
  75. {
  76. m_GearNum++;
  77. }
  78. }
  79. // simple function to add a curved bias towards 1 for a value in the 0-1 range
  80. private static float CurveFactor(float factor)
  81. {
  82. return 1 - (1 - factor)*(1 - factor);
  83. }
  84. // unclamped version of Lerp, to allow value to exceed the from-to range
  85. private static float ULerp(float from, float to, float value)
  86. {
  87. return (1.0f - value)*from + value*to;
  88. }
  89. private void CalculateGearFactor()
  90. {
  91. float f = (1/(float) NoOfGears);
  92. // gear factor is a normalised representation of the current speed within the current gear's range of speeds.
  93. // We smooth towards the 'target' gear factor, so that revs don't instantly snap up or down when changing gear.
  94. var targetGearFactor = Mathf.InverseLerp(f*m_GearNum, f*(m_GearNum + 1), Mathf.Abs(CurrentSpeed/MaxSpeed));
  95. m_GearFactor = Mathf.Lerp(m_GearFactor, targetGearFactor, Time.deltaTime*5f);
  96. }
  97. private void CalculateRevs()
  98. {
  99. // calculate engine revs (for display / sound)
  100. // (this is done in retrospect - revs are not used in force/power calculations)
  101. CalculateGearFactor();
  102. var gearNumFactor = m_GearNum/(float) NoOfGears;
  103. var revsRangeMin = ULerp(0f, m_RevRangeBoundary, CurveFactor(gearNumFactor));
  104. var revsRangeMax = ULerp(m_RevRangeBoundary, 1f, gearNumFactor);
  105. Revs = ULerp(revsRangeMin, revsRangeMax, m_GearFactor);
  106. }
  107. public void Move(float steering, float accel, float footbrake, float handbrake)
  108. {
  109. for (int i = 0; i < 4; i++)
  110. {
  111. Quaternion quat;
  112. Vector3 position;
  113. m_WheelColliders[i].GetWorldPose(out position, out quat);
  114. m_WheelMeshes[i].transform.position = position;
  115. m_WheelMeshes[i].transform.rotation = quat;
  116. }
  117. //clamp input values
  118. steering = Mathf.Clamp(steering, -1, 1);
  119. AccelInput = accel = Mathf.Clamp(accel, 0, 1);
  120. BrakeInput = footbrake = -1*Mathf.Clamp(footbrake, -1, 0);
  121. handbrake = Mathf.Clamp(handbrake, 0, 1);
  122. //Set the steer on the front wheels.
  123. //Assuming that wheels 0 and 1 are the front wheels.
  124. m_SteerAngle = steering*m_MaximumSteerAngle;
  125. m_WheelColliders[0].steerAngle = m_SteerAngle;
  126. m_WheelColliders[1].steerAngle = m_SteerAngle;
  127. SteerHelper();
  128. ApplyDrive(accel, footbrake);
  129. CapSpeed();
  130. //Set the handbrake.
  131. //Assuming that wheels 2 and 3 are the rear wheels.
  132. if (handbrake > 0f)
  133. {
  134. var hbTorque = handbrake*m_MaxHandbrakeTorque;
  135. m_WheelColliders[2].brakeTorque = hbTorque;
  136. m_WheelColliders[3].brakeTorque = hbTorque;
  137. }
  138. CalculateRevs();
  139. GearChanging();
  140. AddDownForce();
  141. CheckForWheelSpin();
  142. TractionControl();
  143. }
  144. private void CapSpeed()
  145. {
  146. float speed = m_Rigidbody.velocity.magnitude;
  147. switch (m_SpeedType)
  148. {
  149. case SpeedType.MPH:
  150. speed *= 2.23693629f;
  151. if (speed > m_Topspeed)
  152. m_Rigidbody.velocity = (m_Topspeed/2.23693629f) * m_Rigidbody.velocity.normalized;
  153. break;
  154. case SpeedType.KPH:
  155. speed *= 3.6f;
  156. if (speed > m_Topspeed)
  157. m_Rigidbody.velocity = (m_Topspeed/3.6f) * m_Rigidbody.velocity.normalized;
  158. break;
  159. }
  160. }
  161. private void ApplyDrive(float accel, float footbrake)
  162. {
  163. float thrustTorque;
  164. switch (m_CarDriveType)
  165. {
  166. case CarDriveType.FourWheelDrive:
  167. thrustTorque = accel * (m_CurrentTorque / 4f);
  168. for (int i = 0; i < 4; i++)
  169. {
  170. m_WheelColliders[i].motorTorque = thrustTorque;
  171. }
  172. break;
  173. case CarDriveType.FrontWheelDrive:
  174. thrustTorque = accel * (m_CurrentTorque / 2f);
  175. m_WheelColliders[0].motorTorque = m_WheelColliders[1].motorTorque = thrustTorque;
  176. break;
  177. case CarDriveType.RearWheelDrive:
  178. thrustTorque = accel * (m_CurrentTorque / 2f);
  179. m_WheelColliders[2].motorTorque = m_WheelColliders[3].motorTorque = thrustTorque;
  180. break;
  181. }
  182. for (int i = 0; i < 4; i++)
  183. {
  184. if (CurrentSpeed > 5 && Vector3.Angle(transform.forward, m_Rigidbody.velocity) < 50f)
  185. {
  186. m_WheelColliders[i].brakeTorque = m_BrakeTorque*footbrake;
  187. }
  188. else if (footbrake > 0)
  189. {
  190. m_WheelColliders[i].brakeTorque = 0f;
  191. m_WheelColliders[i].motorTorque = -m_ReverseTorque*footbrake;
  192. }
  193. }
  194. }
  195. private void SteerHelper()
  196. {
  197. for (int i = 0; i < 4; i++)
  198. {
  199. WheelHit wheelhit;
  200. m_WheelColliders[i].GetGroundHit(out wheelhit);
  201. if (wheelhit.normal == Vector3.zero)
  202. return; // wheels arent on the ground so dont realign the rigidbody velocity
  203. }
  204. // this if is needed to avoid gimbal lock problems that will make the car suddenly shift direction
  205. if (Mathf.Abs(m_OldRotation - transform.eulerAngles.y) < 10f)
  206. {
  207. var turnadjust = (transform.eulerAngles.y - m_OldRotation) * m_SteerHelper;
  208. Quaternion velRotation = Quaternion.AngleAxis(turnadjust, Vector3.up);
  209. m_Rigidbody.velocity = velRotation * m_Rigidbody.velocity;
  210. }
  211. m_OldRotation = transform.eulerAngles.y;
  212. }
  213. // this is used to add more grip in relation to speed
  214. private void AddDownForce()
  215. {
  216. m_WheelColliders[0].attachedRigidbody.AddForce(-transform.up*m_Downforce*
  217. m_WheelColliders[0].attachedRigidbody.velocity.magnitude);
  218. }
  219. // checks if the wheels are spinning and is so does three things
  220. // 1) emits particles
  221. // 2) plays tiure skidding sounds
  222. // 3) Exits skidmarks on the ground
  223. // these effects are controlled through the WheelEffects class
  224. private void CheckForWheelSpin()
  225. {
  226. // loop through all wheels
  227. for (int i = 0; i < 4; i++)
  228. {
  229. WheelHit wheelHit;
  230. m_WheelColliders[i].GetGroundHit(out wheelHit);
  231. // is the tire slipping above the given threshhold
  232. if (Mathf.Abs(wheelHit.forwardSlip) >= m_SlipLimit || Mathf.Abs(wheelHit.sidewaysSlip) >= m_SlipLimit)
  233. {
  234. m_WheelEffects[i].EmitTyreSmoke();
  235. // avoiding all four tires screeching at the same time
  236. // if they do it can lead to some strange audio artefacts
  237. if (!AnySkidSoundPlaying())
  238. {
  239. m_WheelEffects[i].PlayAudio();
  240. }
  241. continue;
  242. }
  243. // if it wasnt slipping stop all the audio
  244. if (m_WheelEffects[i].PlayingAudio)
  245. {
  246. m_WheelEffects[i].StopAudio();
  247. }
  248. // end the trail generation
  249. m_WheelEffects[i].EndSkidTrail();
  250. }
  251. }
  252. // crude traction control that reduces the power to wheel if the car is wheel spinning too much
  253. private void TractionControl()
  254. {
  255. WheelHit wheelHit;
  256. switch (m_CarDriveType)
  257. {
  258. case CarDriveType.FourWheelDrive:
  259. // loop through all wheels
  260. for (int i = 0; i < 4; i++)
  261. {
  262. m_WheelColliders[i].GetGroundHit(out wheelHit);
  263. AdjustTorque(wheelHit.forwardSlip);
  264. }
  265. break;
  266. case CarDriveType.RearWheelDrive:
  267. m_WheelColliders[2].GetGroundHit(out wheelHit);
  268. AdjustTorque(wheelHit.forwardSlip);
  269. m_WheelColliders[3].GetGroundHit(out wheelHit);
  270. AdjustTorque(wheelHit.forwardSlip);
  271. break;
  272. case CarDriveType.FrontWheelDrive:
  273. m_WheelColliders[0].GetGroundHit(out wheelHit);
  274. AdjustTorque(wheelHit.forwardSlip);
  275. m_WheelColliders[1].GetGroundHit(out wheelHit);
  276. AdjustTorque(wheelHit.forwardSlip);
  277. break;
  278. }
  279. }
  280. private void AdjustTorque(float forwardSlip)
  281. {
  282. if (forwardSlip >= m_SlipLimit && m_CurrentTorque >= 0)
  283. {
  284. m_CurrentTorque -= 10 * m_TractionControl;
  285. }
  286. else
  287. {
  288. m_CurrentTorque += 10 * m_TractionControl;
  289. if (m_CurrentTorque > m_FullTorqueOverAllWheels)
  290. {
  291. m_CurrentTorque = m_FullTorqueOverAllWheels;
  292. }
  293. }
  294. }
  295. private bool AnySkidSoundPlaying()
  296. {
  297. for (int i = 0; i < 4; i++)
  298. {
  299. if (m_WheelEffects[i].PlayingAudio)
  300. {
  301. return true;
  302. }
  303. }
  304. return false;
  305. }
  306. }
  307. }