Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

car ai doesnt drive around objectsh

Discussion in 'Scripting' started by ghost123_1234, Jan 9, 2015.

  1. ghost123_1234

    ghost123_1234

    Joined:
    Jan 9, 2015
    Posts:
    88
    hello

    i followed a tutorial on youtube for the car ai tutorial

    this is the script from that
    Code (JavaScript):
    1. var centerOfMass : Vector3;
    2. var path : Array;
    3. var pathGroup : Transform;
    4. var maxSteer : float = 15.0;
    5. var wheelFL : WheelCollider;  
    6. var wheelFR : WheelCollider;
    7. var wheelRL : WheelCollider;  
    8. var wheelRR : WheelCollider;
    9. var currentPathObj : int;
    10. var distFromPath : float = 20;
    11. var maxTorque : float = 50;
    12. var currentSpeed : float;
    13. var topSpeed : float = 150;
    14. var decellarationSpeed : float = 10;
    15. var breakingMesh : Renderer;
    16. var idleBreakLight : Material;
    17. var activeBreakLight : Material;
    18. var isBreaking : boolean;
    19. var inSector : boolean;
    20. var sensorLength : float = 5;
    21. var frontSensorStartPoint : float = 5;
    22. var frontSensorSideDist : float = 5;
    23. var frontSensorsAngle : float = 30;
    24. var sidewaySensorLength : float = 5;
    25. var avoidSpeed : float = 10;
    26. private var flag : int = 0;
    27. var reversing : boolean = false;
    28. var reverCounter : float = 0.0;
    29. var waitToReverse : float = 2.0;
    30. var reverFor : float = 1.5;
    31. var respawnWait: float = 5;
    32. var respawnCounter : float = 0.0;
    33.  
    34.  
    35.  
    36. function Start () {
    37. rigidbody.centerOfMass = centerOfMass;
    38. GetPath();
    39. }
    40.  
    41. function GetPath (){
    42. var path_objs : Array = pathGroup.GetComponentsInChildren(Transform);
    43. path = new Array();
    44.  
    45. for (var path_obj : Transform in path_objs){
    46. if (path_obj != pathGroup)
    47.   path [path.length] = path_obj;
    48. }
    49. }
    50.  
    51.  
    52. function Update () {
    53. if (flag == 0)
    54. GetSteer();
    55. Move();
    56. BreakingEffect ();
    57. Sensors();
    58. Respawn ();
    59. }
    60.  
    61. function GetSteer(){
    62. var steerVector : Vector3 = transform.InverseTransformPoint(Vector3(path[currentPathObj].position.x,transform.position.y,path[currentPathObj].position.z));
    63. var newSteer : float = maxSteer * (steerVector.x / steerVector.magnitude);
    64. wheelFL.steerAngle = newSteer;
    65. wheelFR.steerAngle = newSteer;
    66.  
    67. if (steerVector.magnitude <= distFromPath){
    68. currentPathObj++;
    69. if (currentPathObj >= path.length)
    70. currentPathObj = 0;
    71. }
    72.  
    73. }
    74.  
    75. function Move (){
    76. currentSpeed = 2*(22/7)*wheelRL.radius*wheelRL.rpm * 60 / 1000;
    77. currentSpeed = Mathf.Round (currentSpeed);
    78. if (currentSpeed <= topSpeed && !inSector){
    79. if (!reversing){
    80. wheelRL.motorTorque = maxTorque;
    81. wheelRR.motorTorque = maxTorque;
    82. }
    83. else {
    84. wheelRL.motorTorque = -maxTorque;
    85. wheelRR.motorTorque = -maxTorque;
    86. }
    87. wheelRL.brakeTorque = 0;
    88. wheelRR.brakeTorque = 0;
    89. }
    90. else if (!inSector){
    91. wheelRL.motorTorque = 0;
    92. wheelRR.motorTorque = 0;
    93. wheelRL.brakeTorque = decellarationSpeed;
    94. wheelRR.brakeTorque = decellarationSpeed;
    95. }
    96. }
    97.  
    98. function BreakingEffect (){
    99. if (isBreaking){
    100. breakingMesh.material = activeBreakLight;
    101. }
    102. else {
    103. breakingMesh.material = idleBreakLight;
    104. }
    105.  
    106. }
    107.  
    108. function Sensors(){
    109. flag = 0;
    110. var avoidSenstivity : float = 0;
    111. var pos : Vector3;
    112. var hit : RaycastHit;
    113. var rightAngle = Quaternion.AngleAxis(frontSensorsAngle,transform.up) * transform.forward;
    114. var leftAngle = Quaternion.AngleAxis(-frontSensorsAngle,transform.up) * transform.forward;
    115.  
    116.  
    117.  
    118. pos = transform.position;
    119. pos += transform.forward*frontSensorStartPoint;
    120.  
    121. //BRAKING SENSOR
    122.  
    123. if (Physics.Raycast(pos,transform.forward,hit,sensorLength)){
    124. if (hit.transform.tag != "Terrain"){
    125. flag++;
    126. wheelRL.brakeTorque = decellarationSpeed;
    127. wheelRR.brakeTorque = decellarationSpeed;
    128. Debug.DrawLine(pos,hit.point,Color.red);
    129. }
    130. }
    131. else {
    132. wheelRL.brakeTorque = 0;
    133. wheelRR.brakeTorque = 0;
    134. }
    135.  
    136.  
    137. //Front Straight Right Sensor
    138. pos += transform.right*frontSensorSideDist;
    139.  
    140. if (Physics.Raycast(pos,transform.forward,hit,sensorLength)){
    141. if (hit.transform.tag != "Terrain"){
    142. flag++;
    143. avoidSenstivity -= 1;  
    144. Debug.Log("Avoiding");
    145. Debug.DrawLine(pos,hit.point,Color.white);
    146. }
    147. }
    148. else if (Physics.Raycast(pos,rightAngle,hit,sensorLength)){
    149. if (hit.transform.tag != "Terrain"){
    150. avoidSenstivity -= 0.5;  
    151. flag++;
    152. Debug.DrawLine(pos,hit.point,Color.white);
    153. }
    154. }
    155.  
    156.  
    157. //Front Straight left Sensor
    158. pos = transform.position;
    159. pos += transform.forward*frontSensorStartPoint;
    160. pos -= transform.right*frontSensorSideDist;
    161.  
    162. if (Physics.Raycast(pos,transform.forward,hit,sensorLength)){
    163. if (hit.transform.tag != "Terrain"){
    164. flag++;
    165. avoidSenstivity += 1;  
    166. Debug.Log("Avoiding");
    167. Debug.DrawLine(pos,hit.point,Color.white);
    168. }
    169. }
    170. else if (Physics.Raycast(pos,leftAngle,hit,sensorLength)){
    171. if (hit.transform.tag != "Terrain"){
    172. flag++;
    173. avoidSenstivity += 0.5;
    174. Debug.DrawLine(pos,hit.point,Color.white);
    175. }
    176. }
    177.  
    178. //Right SideWay Sensor
    179. if (Physics.Raycast(transform.position,transform.right,hit,sidewaySensorLength)){
    180. if (hit.transform.tag != "Terrain"){
    181. flag++;
    182. avoidSenstivity -= 0.5;
    183. Debug.DrawLine(transform.position,hit.point,Color.white);
    184. }
    185. }
    186.  
    187.  
    188. //Left SideWay Sensor
    189. if (Physics.Raycast(transform.position,-transform.right,hit,sidewaySensorLength)){
    190. if (hit.transform.tag != "Terrain"){
    191. flag++;
    192. avoidSenstivity += 0.5;
    193. Debug.DrawLine(transform.position,hit.point,Color.white);
    194. }
    195. }
    196.  
    197. pos = transform.position;
    198. pos += transform.forward*frontSensorStartPoint;
    199. //Front Mid Sensor
    200. if (avoidSenstivity == 0){
    201.  
    202. if (Physics.Raycast(pos,transform.forward,hit,sensorLength)){
    203. if (hit.transform.tag != "Terrain"){
    204. if (hit.normal.x < 0 )
    205. avoidSenstivity = -1;
    206. else  
    207. avoidSenstivity = 1;
    208. Debug.DrawLine(pos,hit.point,Color.white);
    209. }
    210. }
    211. }
    212.  
    213.  
    214. if (rigidbody.velocity.magnitude < 2 && !reversing){
    215. reverCounter += Time.deltaTime;
    216. if (reverCounter >= waitToReverse){
    217. reverCounter = 0;
    218. reversing = true;
    219. }
    220. }
    221. else if (!reversing){
    222. reverCounter = 0;  
    223. }
    224.  
    225.  
    226. if (reversing){
    227. avoidSenstivity *= -1;
    228. reverCounter += Time.deltaTime;
    229. if (reverCounter >= reverFor){
    230. reverCounter = 0;
    231. reversing = false;
    232. }
    233. }
    234.  
    235.  
    236. if (flag != 0)
    237. AvoidSteer (avoidSenstivity);
    238.  
    239.  
    240. }
    241.  
    242.  
    243. function AvoidSteer (senstivity : float){
    244. wheelFL.steerAngle = avoidSpeed*senstivity;
    245. wheelFR.steerAngle = avoidSpeed*senstivity;
    246.  
    247. }
    248.  
    249.  
    250. function Respawn (){
    251. if (rigidbody.velocity.magnitude < 2){
    252. respawnCounter += Time.deltaTime;
    253. if (respawnCounter >= respawnWait){
    254. if (currentPathObj == 0){
    255. transform.position = path[path.length-1].position;
    256. }
    257. else{
    258. transform.position = path[currentPathObj-1].position;
    259. }
    260. respawnCounter = 0;
    261. transform.localEulerAngles.z = 0;
    262. }
    263. }
    264. }  

    but for some reason.
    in the video when i putt an object on the path the car drives around it but at my car it doesnt do that

    does somebody know why
     
  2. cl9-2

    cl9-2

    Joined:
    May 31, 2013
    Posts:
    417
    I've tested this script and it works, although the code that is used for the avoidance is quirky

    If the car is avoiding static or slow moving objects, you'll need to make the sensor lengths much longer than the defaults.

    The only problem with this is that nearby obstacles (including other AI cars) might not be avoided in time.

    You could also consider
    • Adding both short range and long range sensors
    • Using raycast layers since using strings (i.e. tag and object names) in an update loop should be avoided
    • Doing ray cast calculations at a lower rate or spreading their calculations across frames
     
  3. ghost123_1234

    ghost123_1234

    Joined:
    Jan 9, 2015
    Posts:
    88
    thx
    i will try to make the sensors longer first.

    thanks!
     
  4. cl9-2

    cl9-2

    Joined:
    May 31, 2013
    Posts:
    417
    Sure, no problem.

    Also, in case anyone is interested in a converted C# version (which uses standard arrays for the waypoints rather than the Array class)

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class AICar : MonoBehaviour {
    5.  
    6.     public Vector3 centerOfMass;
    7.     private Transform[] path;
    8.     public Transform pathGroup;
    9.     public float maxSteer = 15.0f;
    10.     public WheelCollider wheelFL;
    11.     public WheelCollider wheelFR;
    12.     public WheelCollider wheelRL;
    13.     public WheelCollider wheelRR;
    14.     public int currentPathObj;
    15.     public float distFromPath = 20;
    16.     public float maxTorque = 50;
    17.     public float currentSpeed;
    18.     public float topSpeed = 150;
    19.     public float decellarationSpeed = 10;
    20.     public Renderer breakingMesh;
    21.     public Material idleBreakLight;
    22.     public Material activeBreakLight;
    23.     public bool  isBreaking;
    24.     public bool  inSector;
    25.     public float sensorLength = 5;
    26.     public float frontSensorStartPoint = 5;
    27.     public float frontSensorSideDist = 5;
    28.     public float frontSensorsAngle = 30;
    29.     public float sidewaySensorLength = 5;
    30.     public float avoidSpeed = 10;
    31.     private int flag = 0;
    32.     public bool  reversing = false;
    33.     private float reverCounter = 0.0f;
    34.     public float waitToReverse = 2.0f;
    35.     public float reverFor = 1.5f;
    36.     public float respawnWait = 5;
    37.     private float respawnCounter = 0.0f;
    38.  
    39.     void  Start (){
    40.         rigidbody.centerOfMass = centerOfMass;
    41.         GetPath();
    42.     }
    43.  
    44.     void  GetPath (){
    45.         Transform[] path_objs = pathGroup.GetComponentsInChildren<Transform>();
    46.         path = new Transform[path_objs.Length - 1];
    47.      
    48.         int i = 0;
    49.      
    50.         foreach(Transform path_obj in path_objs){
    51.             if (path_obj != pathGroup)
    52.             {
    53.                 path [i] = path_obj;
    54.                 i++;
    55.             }
    56.         }
    57.     }
    58.  
    59.  
    60.     void  Update (){
    61.         if (flag == 0)
    62.             GetSteer();
    63.         Move();
    64.         BreakingEffect ();
    65.         Sensors();
    66.         Respawn ();
    67.     }
    68.  
    69.     void  GetSteer (){
    70.         Vector3 steerVector = transform.InverseTransformPoint(new Vector3(path[currentPathObj].position.x,transform.position.y,path[currentPathObj].position.z));
    71.         float newSteer = maxSteer * (steerVector.x / steerVector.magnitude);
    72.         wheelFL.steerAngle = newSteer;
    73.         wheelFR.steerAngle = newSteer;
    74.  
    75.         if (steerVector.magnitude <= distFromPath){
    76.             currentPathObj++;
    77.             if (currentPathObj >= path.Length)
    78.                 currentPathObj = 0;
    79.         }
    80.      
    81.     }
    82.  
    83.     void  Move (){
    84.         currentSpeed = 2*(22/7)*wheelRL.radius*wheelRL.rpm * 60 / 1000;
    85.         currentSpeed = Mathf.Round (currentSpeed);
    86.         if (currentSpeed <= topSpeed && !inSector){
    87.             if (!reversing){
    88.                 wheelRL.motorTorque = maxTorque;
    89.                 wheelRR.motorTorque = maxTorque;
    90.             }
    91.             else {
    92.                 wheelRL.motorTorque = -maxTorque;
    93.                 wheelRR.motorTorque = -maxTorque;
    94.             }
    95.             wheelRL.brakeTorque = 0;
    96.             wheelRR.brakeTorque = 0;
    97.         }
    98.         else if (!inSector){
    99.             wheelRL.motorTorque = 0;
    100.             wheelRR.motorTorque = 0;
    101.             wheelRL.brakeTorque = decellarationSpeed;
    102.             wheelRR.brakeTorque = decellarationSpeed;
    103.         }
    104.     }
    105.  
    106.     void  BreakingEffect (){
    107.         if (isBreaking && breakingMesh){
    108.             breakingMesh.material = activeBreakLight;
    109.         }
    110.         else if (breakingMesh) {
    111.             breakingMesh.material = idleBreakLight;
    112.         }
    113.      
    114.     }
    115.  
    116.     void  Sensors (){
    117.         flag = 0;
    118.         float avoidSenstivity = 0;
    119.         Vector3 pos;
    120.         RaycastHit hit;
    121.         Vector3 rightAngle = Quaternion.AngleAxis(frontSensorsAngle,transform.up) * transform.forward;
    122.         Vector3 leftAngle = Quaternion.AngleAxis(-frontSensorsAngle,transform.up) * transform.forward;
    123.      
    124.      
    125.      
    126.         pos = transform.position;
    127.         pos += transform.forward*frontSensorStartPoint;
    128.      
    129.         //BRAKING SENSOR
    130.      
    131.         if (Physics.Raycast(pos,transform.forward,out hit,sensorLength)){
    132.             if (hit.transform.tag != "Terrain"){
    133.                 flag++;
    134.                 wheelRL.brakeTorque = decellarationSpeed;
    135.                 wheelRR.brakeTorque = decellarationSpeed;
    136.                 Debug.DrawLine(pos,hit.point,Color.red);
    137.             }
    138.         }
    139.         else {
    140.             wheelRL.brakeTorque = 0;
    141.             wheelRR.brakeTorque = 0;
    142.         }
    143.      
    144.      
    145.         //Front Straight Right Sensor
    146.         pos += transform.right*frontSensorSideDist;
    147.      
    148.         if (Physics.Raycast(pos,transform.forward,out hit,sensorLength)){
    149.             if (hit.transform.tag != "Terrain"){
    150.                 flag++;
    151.                 avoidSenstivity -= 1;
    152.                 Debug.Log("Avoiding");
    153.                 Debug.DrawLine(pos,hit.point,Color.white);
    154.             }
    155.         }
    156.         else if (Physics.Raycast(pos,rightAngle,out hit,sensorLength)){
    157.             if (hit.transform.tag != "Terrain"){
    158.                 avoidSenstivity -= 0.5f;
    159.                 flag++;
    160.                 Debug.DrawLine(pos,hit.point,Color.white);
    161.             }
    162.         }
    163.      
    164.      
    165.         //Front Straight left Sensor
    166.         pos = transform.position;
    167.         pos += transform.forward*frontSensorStartPoint;
    168.         pos -= transform.right*frontSensorSideDist;
    169.      
    170.         if (Physics.Raycast(pos,transform.forward,out hit,sensorLength)){
    171.             if (hit.transform.tag != "Terrain"){
    172.                 flag++;
    173.                 avoidSenstivity += 1;
    174.                 Debug.Log("Avoiding");
    175.                 Debug.DrawLine(pos,hit.point,Color.white);
    176.             }
    177.         }
    178.         else if (Physics.Raycast(pos,leftAngle,out hit,sensorLength)){
    179.             if (hit.transform.tag != "Terrain"){
    180.                 flag++;
    181.                 avoidSenstivity += 0.5f;
    182.                 Debug.DrawLine(pos,hit.point,Color.white);
    183.             }
    184.         }
    185.      
    186.         //Right SideWay Sensor
    187.         if (Physics.Raycast(transform.position,transform.right,out hit,sidewaySensorLength)){
    188.             if (hit.transform.tag != "Terrain"){
    189.                 flag++;
    190.                 avoidSenstivity -= 0.5f;
    191.                 Debug.DrawLine(transform.position,hit.point,Color.white);
    192.             }
    193.         }
    194.      
    195.      
    196.         //Left SideWay Sensor
    197.         if (Physics.Raycast(transform.position,-transform.right,out hit,sidewaySensorLength)){
    198.             if (hit.transform.tag != "Terrain"){
    199.                 flag++;
    200.                 avoidSenstivity += 0.5f;
    201.                 Debug.DrawLine(transform.position,hit.point,Color.white);
    202.             }
    203.         }
    204.      
    205.         pos = transform.position;
    206.         pos += transform.forward*frontSensorStartPoint;
    207.         //Front Mid Sensor
    208.         if (avoidSenstivity == 0){
    209.          
    210.             if (Physics.Raycast(pos,transform.forward,out hit,sensorLength)){
    211.                 if (hit.transform.tag != "Terrain"){
    212.                     if (hit.normal.x < 0 )
    213.                         avoidSenstivity = -1;
    214.                     else
    215.                         avoidSenstivity = 1;
    216.                     Debug.DrawLine(pos,hit.point,Color.white);
    217.                 }
    218.             }
    219.         }
    220.      
    221.      
    222.         if (rigidbody.velocity.magnitude < 2 && !reversing){
    223.             reverCounter += Time.deltaTime;
    224.             if (reverCounter >= waitToReverse){
    225.                 reverCounter = 0;
    226.                 reversing = true;
    227.             }
    228.         }
    229.         else if (!reversing){
    230.             reverCounter = 0;
    231.         }
    232.      
    233.      
    234.         if (reversing){
    235.             avoidSenstivity *= -1;
    236.             reverCounter += Time.deltaTime;
    237.             if (reverCounter >= reverFor){
    238.                 reverCounter = 0;
    239.                 reversing = false;
    240.             }
    241.         }
    242.      
    243.      
    244.         if (flag != 0)
    245.             AvoidSteer (avoidSenstivity);
    246.      
    247.      
    248.     }
    249.  
    250.  
    251.     void  AvoidSteer ( float senstivity  ){
    252.         wheelFL.steerAngle = avoidSpeed*senstivity;
    253.         wheelFR.steerAngle = avoidSpeed*senstivity;
    254.      
    255.     }
    256.  
    257.  
    258.     void  Respawn (){
    259.         if (rigidbody.velocity.magnitude < 2){
    260.             respawnCounter += Time.deltaTime;
    261.             if (respawnCounter >= respawnWait){
    262.                 if (currentPathObj == 0){
    263.                     transform.position = path[path.Length-1].position;
    264.                 }
    265.                 else{
    266.                     transform.position = path[currentPathObj-1].position;
    267.                 }
    268.                 respawnCounter = 0;
    269.                 transform.localEulerAngles.Set (transform.localEulerAngles.x, 0, transform.localEulerAngles.z);
    270.             }
    271.         }
    272.     }
    273. }
     
  5. ghost123_1234

    ghost123_1234

    Joined:
    Jan 9, 2015
    Posts:
    88
    thanks again i can understand C# better then js
     
  6. Emile97

    Emile97

    Joined:
    May 28, 2017
    Posts:
    105
    that's true and i'm stuck there, i mean the car doesn't avoid close object ... also when i have many cars (like 6 of them). the cars form a "queue" and follow each other like babies , do you know why ??