CarAIControl.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. using System;
  2. using UnityEngine;
  3. using Random = UnityEngine.Random;
  4. namespace UnityStandardAssets.Vehicles.Car
  5. {
  6. [RequireComponent(typeof (CarController))]
  7. public class CarAIControl : MonoBehaviour
  8. {
  9. public enum BrakeCondition
  10. {
  11. NeverBrake, // the car simply accelerates at full throttle all the time.
  12. TargetDirectionDifference, // the car will brake according to the upcoming change in direction of the target. Useful for route-based AI, slowing for corners.
  13. TargetDistance, // the car will brake as it approaches its target, regardless of the target's direction. Useful if you want the car to
  14. // head for a stationary target and come to rest when it arrives there.
  15. }
  16. // This script provides input to the car controller in the same way that the user control script does.
  17. // As such, it is really 'driving' the car, with no special physics or animation tricks to make the car behave properly.
  18. // "wandering" is used to give the cars a more human, less robotic feel. They can waver slightly
  19. // in speed and direction while driving towards their target.
  20. [SerializeField] [Range(0, 1)] private float m_CautiousSpeedFactor = 0.05f; // percentage of max speed to use when being maximally cautious
  21. [SerializeField] [Range(0, 180)] private float m_CautiousMaxAngle = 50f; // angle of approaching corner to treat as warranting maximum caution
  22. [SerializeField] private float m_CautiousMaxDistance = 100f; // distance at which distance-based cautiousness begins
  23. [SerializeField] private float m_CautiousAngularVelocityFactor = 30f; // how cautious the AI should be when considering its own current angular velocity (i.e. easing off acceleration if spinning!)
  24. [SerializeField] private float m_SteerSensitivity = 0.05f; // how sensitively the AI uses steering input to turn to the desired direction
  25. [SerializeField] private float m_AccelSensitivity = 0.04f; // How sensitively the AI uses the accelerator to reach the current desired speed
  26. [SerializeField] private float m_BrakeSensitivity = 1f; // How sensitively the AI uses the brake to reach the current desired speed
  27. [SerializeField] private float m_LateralWanderDistance = 3f; // how far the car will wander laterally towards its target
  28. [SerializeField] private float m_LateralWanderSpeed = 0.1f; // how fast the lateral wandering will fluctuate
  29. [SerializeField] [Range(0, 1)] private float m_AccelWanderAmount = 0.1f; // how much the cars acceleration will wander
  30. [SerializeField] private float m_AccelWanderSpeed = 0.1f; // how fast the cars acceleration wandering will fluctuate
  31. [SerializeField] private BrakeCondition m_BrakeCondition = BrakeCondition.TargetDistance; // what should the AI consider when accelerating/braking?
  32. [SerializeField] private bool m_Driving; // whether the AI is currently actively driving or stopped.
  33. [SerializeField] private Transform m_Target; // 'target' the target object to aim for.
  34. [SerializeField] private bool m_StopWhenTargetReached; // should we stop driving when we reach the target?
  35. [SerializeField] private float m_ReachTargetThreshold = 2; // proximity to target to consider we 'reached' it, and stop driving.
  36. private float m_RandomPerlin; // A random value for the car to base its wander on (so that AI cars don't all wander in the same pattern)
  37. private CarController m_CarController; // Reference to actual car controller we are controlling
  38. private float m_AvoidOtherCarTime; // time until which to avoid the car we recently collided with
  39. private float m_AvoidOtherCarSlowdown; // how much to slow down due to colliding with another car, whilst avoiding
  40. private float m_AvoidPathOffset; // direction (-1 or 1) in which to offset path to avoid other car, whilst avoiding
  41. private Rigidbody m_Rigidbody;
  42. private void Awake()
  43. {
  44. // get the car controller reference
  45. m_CarController = GetComponent<CarController>();
  46. // give the random perlin a random value
  47. m_RandomPerlin = Random.value*100;
  48. m_Rigidbody = GetComponent<Rigidbody>();
  49. }
  50. private void FixedUpdate()
  51. {
  52. if (m_Target == null || !m_Driving)
  53. {
  54. // Car should not be moving,
  55. // use handbrake to stop
  56. m_CarController.Move(0, 0, -1f, 1f);
  57. }
  58. else
  59. {
  60. Vector3 fwd = transform.forward;
  61. if (m_Rigidbody.velocity.magnitude > m_CarController.MaxSpeed*0.1f)
  62. {
  63. fwd = m_Rigidbody.velocity;
  64. }
  65. float desiredSpeed = m_CarController.MaxSpeed;
  66. // now it's time to decide if we should be slowing down...
  67. switch (m_BrakeCondition)
  68. {
  69. case BrakeCondition.TargetDirectionDifference:
  70. {
  71. // the car will brake according to the upcoming change in direction of the target. Useful for route-based AI, slowing for corners.
  72. // check out the angle of our target compared to the current direction of the car
  73. float approachingCornerAngle = Vector3.Angle(m_Target.forward, fwd);
  74. // also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle
  75. float spinningAngle = m_Rigidbody.angularVelocity.magnitude*m_CautiousAngularVelocityFactor;
  76. // if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount
  77. float cautiousnessRequired = Mathf.InverseLerp(0, m_CautiousMaxAngle,
  78. Mathf.Max(spinningAngle,
  79. approachingCornerAngle));
  80. desiredSpeed = Mathf.Lerp(m_CarController.MaxSpeed, m_CarController.MaxSpeed*m_CautiousSpeedFactor,
  81. cautiousnessRequired);
  82. break;
  83. }
  84. case BrakeCondition.TargetDistance:
  85. {
  86. // the car will brake as it approaches its target, regardless of the target's direction. Useful if you want the car to
  87. // head for a stationary target and come to rest when it arrives there.
  88. // check out the distance to target
  89. Vector3 delta = m_Target.position - transform.position;
  90. float distanceCautiousFactor = Mathf.InverseLerp(m_CautiousMaxDistance, 0, delta.magnitude);
  91. // also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle
  92. float spinningAngle = m_Rigidbody.angularVelocity.magnitude*m_CautiousAngularVelocityFactor;
  93. // if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount
  94. float cautiousnessRequired = Mathf.Max(
  95. Mathf.InverseLerp(0, m_CautiousMaxAngle, spinningAngle), distanceCautiousFactor);
  96. desiredSpeed = Mathf.Lerp(m_CarController.MaxSpeed, m_CarController.MaxSpeed*m_CautiousSpeedFactor,
  97. cautiousnessRequired);
  98. break;
  99. }
  100. case BrakeCondition.NeverBrake:
  101. break;
  102. }
  103. // Evasive action due to collision with other cars:
  104. // our target position starts off as the 'real' target position
  105. Vector3 offsetTargetPos = m_Target.position;
  106. // if are we currently taking evasive action to prevent being stuck against another car:
  107. if (Time.time < m_AvoidOtherCarTime)
  108. {
  109. // slow down if necessary (if we were behind the other car when collision occured)
  110. desiredSpeed *= m_AvoidOtherCarSlowdown;
  111. // and veer towards the side of our path-to-target that is away from the other car
  112. offsetTargetPos += m_Target.right*m_AvoidPathOffset;
  113. }
  114. else
  115. {
  116. // no need for evasive action, we can just wander across the path-to-target in a random way,
  117. // which can help prevent AI from seeming too uniform and robotic in their driving
  118. offsetTargetPos += m_Target.right*
  119. (Mathf.PerlinNoise(Time.time*m_LateralWanderSpeed, m_RandomPerlin)*2 - 1)*
  120. m_LateralWanderDistance;
  121. }
  122. // use different sensitivity depending on whether accelerating or braking:
  123. float accelBrakeSensitivity = (desiredSpeed < m_CarController.CurrentSpeed)
  124. ? m_BrakeSensitivity
  125. : m_AccelSensitivity;
  126. // decide the actual amount of accel/brake input to achieve desired speed.
  127. float accel = Mathf.Clamp((desiredSpeed - m_CarController.CurrentSpeed)*accelBrakeSensitivity, -1, 1);
  128. // add acceleration 'wander', which also prevents AI from seeming too uniform and robotic in their driving
  129. // i.e. increasing the accel wander amount can introduce jostling and bumps between AI cars in a race
  130. accel *= (1 - m_AccelWanderAmount) +
  131. (Mathf.PerlinNoise(Time.time*m_AccelWanderSpeed, m_RandomPerlin)*m_AccelWanderAmount);
  132. // calculate the local-relative position of the target, to steer towards
  133. Vector3 localTarget = transform.InverseTransformPoint(offsetTargetPos);
  134. // work out the local angle towards the target
  135. float targetAngle = Mathf.Atan2(localTarget.x, localTarget.z)*Mathf.Rad2Deg;
  136. // get the amount of steering needed to aim the car towards the target
  137. float steer = Mathf.Clamp(targetAngle*m_SteerSensitivity, -1, 1)*Mathf.Sign(m_CarController.CurrentSpeed);
  138. // feed input to the car controller.
  139. m_CarController.Move(steer, accel, accel, 0f);
  140. // if appropriate, stop driving when we're close enough to the target.
  141. if (m_StopWhenTargetReached && localTarget.magnitude < m_ReachTargetThreshold)
  142. {
  143. m_Driving = false;
  144. }
  145. }
  146. }
  147. private void OnCollisionStay(Collision col)
  148. {
  149. // detect collision against other cars, so that we can take evasive action
  150. if (col.rigidbody != null)
  151. {
  152. var otherAI = col.rigidbody.GetComponent<CarAIControl>();
  153. if (otherAI != null)
  154. {
  155. // we'll take evasive action for 1 second
  156. m_AvoidOtherCarTime = Time.time + 1;
  157. // but who's in front?...
  158. if (Vector3.Angle(transform.forward, otherAI.transform.position - transform.position) < 90)
  159. {
  160. // the other ai is in front, so it is only good manners that we ought to brake...
  161. m_AvoidOtherCarSlowdown = 0.5f;
  162. }
  163. else
  164. {
  165. // we're in front! ain't slowing down for anybody...
  166. m_AvoidOtherCarSlowdown = 1;
  167. }
  168. // both cars should take evasive action by driving along an offset from the path centre,
  169. // away from the other car
  170. var otherCarLocalDelta = transform.InverseTransformPoint(otherAI.transform.position);
  171. float otherCarAngle = Mathf.Atan2(otherCarLocalDelta.x, otherCarLocalDelta.z);
  172. m_AvoidPathOffset = m_LateralWanderDistance*-Mathf.Sign(otherCarAngle);
  173. }
  174. }
  175. }
  176. public void SetTarget(Transform target)
  177. {
  178. m_Target = target;
  179. m_Driving = true;
  180. }
  181. }
  182. }