Search Unity

Cars Spawning but not Moving

Discussion in 'Scripting' started by ASMach, Aug 17, 2012.

  1. ASMach

    ASMach

    Joined:
    Nov 26, 2011
    Posts:
    43
    Hi guys,

    I have a highway level where there are a few spawn points and a few endpoints. The spawn points point directly to the endpoints, with no waypoints in the middle. Here is the spawn point script (CarSpawnpoint.js):

    Code (csharp):
    1.  
    2. #pragma strict
    3.  
    4. var speedLimit : float = 130;
    5.  
    6. var terminus : GameObject;
    7.  
    8. var cars : GameObject[];
    9.  
    10. var minSpawnTime : float = 1.0;
    11. var maxSpawnTime : float = 5.0;
    12.  
    13. private var spawnInterval : float = 0;
    14. private var timeBetweenSpawn : float = 0;
    15.  
    16. function SetSpawnTime () {
    17.  
    18.     spawnInterval = Random.Range(minSpawnTime, maxSpawnTime);
    19.    
    20. }
    21.  
    22. function Awake () {
    23.    
    24.     SetSpawnTime();
    25.    
    26.     speedLimit = speedLimit / 3.6;
    27.    
    28. }
    29.  
    30. function Start () {
    31.  
    32. }
    33.  
    34. function Update () {
    35.  
    36.     timeBetweenSpawn += Time.deltaTime;
    37.    
    38.     if(timeBetweenSpawn >= spawnInterval)
    39.     {
    40.  
    41.         // TODO: Spawn cars at random from the array of possible cars
    42.  
    43.         var car = Instantiate(cars[Random.Range(0, (cars.Length -1))], transform.position, Quaternion.identity );
    44.    
    45.         // Give them the default target "terminus"
    46.    
    47.         var carMovement : CarMovement = car.GetComponent(CarMovement);
    48.        
    49.         carMovement.target = terminus;
    50.        
    51.         // Make the car have the speed limit of the start point
    52.    
    53.         carMovement.speedLimit = speedLimit;
    54.         carMovement.speed = speedLimit;
    55.        
    56.         /*
    57.         // Set a color for the car
    58.        
    59.         var colorScript : CarColor = car.GetComponent(CarColor);
    60.        
    61.         var r : float = Random.Range(0, 1);
    62.         var g : float = Random.Range(0, 1);
    63.         var b : float = Random.Range(0, 1);
    64.        
    65.         colorScript.carColor = Color(r, g, b, 1.0);
    66.         */
    67.        
    68.         SetSpawnTime();
    69.        
    70.     }
    71.  
    72. }
    73.  
    74. function OnDrawGizmos () {
    75.  
    76.     Gizmos.DrawIcon (transform.position, "car_spawn_icon.psd", true);
    77.    
    78. }
    79.  
    The above code spawns cars just as they should be spawned. However, the cars themselves don't move to the endpoints, even though I've set them in the editor. The following is the script for the cars (CarMovement.js):

    Code (csharp):
    1.  
    2. #pragma strict
    3.  
    4. var leftFrontWheel : GameObject;
    5. var rightFrontWheel : GameObject;
    6. var leftRearWheel : GameObject;
    7. var rightRearWheel : GameObject;
    8.  
    9. private var waypoints : GameObject[];
    10. private var endpoints : GameObject[];
    11.  
    12. private var leftFrontWheelTrans : Transform;
    13. private var rightFrontWheelTrans : Transform;
    14. private var leftRearWheelTrans : Transform;
    15. private var rightRearWheelTrans : Transform;
    16.  
    17. var maxSpeed : float = 150;
    18. var accelerationRate = 2.67;
    19.  
    20. var speed : float = 0;
    21. var speedLimit : float = 50;
    22.  
    23. var target : GameObject;
    24.  
    25. private var targetScript : CarNavpoint;
    26.  
    27. private var pooped : boolean = false;
    28.  
    29.  
    30. function Awake () {
    31.  
    32.     // Store references to wheel rotations for future reference
    33.    
    34.     leftFrontWheelTrans = leftFrontWheel.transform;
    35.     leftRearWheelTrans = rightFrontWheel.transform;
    36.     rightFrontWheelTrans = leftRearWheel.transform;
    37.     rightRearWheelTrans = rightRearWheel.transform;
    38.    
    39.     Debug.Log("Wheels setup");
    40.    
    41.     if (target)
    42.         GetComponent(NavMeshAgent).destination = target.transform.position;
    43.  
    44. }
    45.  
    46.  
    47. function Start () {
    48.  
    49.     GetRandomDestination();
    50.    
    51.     GetEndPoints();
    52.    
    53.     if (waypoints == 0)
    54.     {
    55.         targetScript = target.GetComponent(CarNavpoint);
    56.         speedLimit = targetScript.speedLimit / 3.6;
    57.     }
    58.  
    59. }
    60.  
    61. function GetWaypoints () {
    62.    
    63.     waypoints = GameObject.FindGameObjectsWithTag("Road Navpoint");
    64.    
    65.     Debug.Log("Waypoints array loaded");
    66.    
    67. }
    68.  
    69. function GetEndPoints () {
    70.  
    71.     endpoints = GameObject.FindGameObjectsWithTag("Car End Point");
    72.    
    73.     Debug.Log("Waypoints array loaded");
    74. }
    75.  
    76. function GetNearestTaggedObject() : GameObject {
    77.     // and finally the actual process for finding the nearest object:
    78.  
    79.     var nearestDistanceSqr = Mathf.Infinity;
    80.     var nearestObj : GameObject = null;
    81.  
    82.     // loop through each tagged object, remembering nearest one found
    83.     for (var obj : GameObject in waypoints) {
    84.    
    85.         Debug.Log("Iterating waypoints...");
    86.  
    87.         var objectPos = obj.transform.position;
    88.         var distanceSqr = (objectPos - transform.position).sqrMagnitude;
    89.  
    90.         if (distanceSqr < nearestDistanceSqr) {
    91.             nearestObj = obj;
    92.             nearestDistanceSqr = distanceSqr;
    93.         }
    94.     }
    95.     Debug.Log("Nearest waypoint found.");
    96.     return nearestObj;
    97. }
    98.  
    99. function GetRandomDestination() {
    100.    
    101.     if (GetComponent(NavMeshAgent).destination == null)
    102.     {
    103.         Debug.Log("Target not set, searching for one...");
    104.         GetWaypoints();
    105.         target = GetNearestTaggedObject();
    106.         GetComponent(NavMeshAgent).destination = target.transform.position;
    107.     }
    108.     else
    109.         Debug.Log("Pre-existing target found");
    110.    
    111. }
    112.  
    113. function Update () {
    114.  
    115.     Debug.Log("Car update method called");
    116.  
    117.     // Movement speed code
    118.    
    119.     if (!pooped)
    120.     {
    121.         if(speed < speedLimit)
    122.             speed += accelerationRate;
    123.         if(speed > speedLimit)
    124.             speed = speedLimit;
    125.     }
    126.     else
    127.     {
    128.         if(speed < maxSpeed)
    129.             speed += accelerationRate;
    130.         if(speed > maxSpeed)
    131.             speed = maxSpeed;
    132.     }
    133.  
    134.     Debug.Log("Travelling at " + (speed * 3.6) + "km/h");
    135.  
    136.     GetComponent(NavMeshAgent).speed = speed;
    137.    
    138.     // Turn wheels
    139.    
    140.     leftFrontWheelTrans.Rotate(Vector3((speed / 3.6) * Time.deltaTime, 0, 0));
    141.     rightFrontWheelTrans.Rotate(Vector3((speed / 3.6) * Time.deltaTime, 0, 0));
    142.     leftRearWheelTrans.Rotate(Vector3((speed / 3.6) * Time.deltaTime, 0, 0));
    143.     rightRearWheelTrans.Rotate(Vector3((speed / 3.6) * Time.deltaTime, 0, 0));
    144.    
    145.     // Get new navpoint if previous target is reached
    146.    
    147.     if (transform.position == target.transform.position)
    148.     {
    149.         if(target.tag == "Car End Point")
    150.         {
    151.             Debug.Log("At endpoint, destory");
    152.             Destroy(this.gameObject);
    153.         }
    154.         else
    155.         {
    156.             Debug.Log("At navpoint, deciding where to go next...");
    157.        
    158.             if (targetScript.connections.Length > 0)
    159.             {
    160.                 var element : int = Random.Range(0, targetScript.connections.Length);
    161.            
    162.                     target = targetScript.connections[element];
    163.                
    164.                 Debug.Log("Connection[" + element + "] chosen.");
    165.            
    166.                 GetComponent(NavMeshAgent).destination = target.transform.position;
    167.             }
    168.             else
    169.             {  
    170.                 GetComponent(NavMeshAgent).destination = target.transform.position + Vector3(30, 0, 0);
    171.            
    172.                 Debug.Log("No connections found, proceeding straight as an arrow...");
    173.             }
    174.         }
    175.     }
    176. }
    177.  
    The script for the endpoints is pretty simple:

    Code (csharp):
    1.  
    2. #pragma strict
    3.  
    4. var speedLimit : float = 130;
    5.  
    6. function Awake () {
    7.  
    8.     speedLimit = speedLimit / 3.6;
    9.    
    10. }
    11.  
    12. function Start () {
    13.  
    14. }
    15.  
    16. function Update () {
    17.  
    18. // TODO: Spawn cars at random from the array of possible cars
    19. // Give them the default target "terminus"
    20. // Make the car have the speed limit of the start point
    21.  
    22. }
    23.  
    24. function OnDrawGizmos () {
    25.  
    26.     Gizmos.DrawIcon (transform.position, "car_kill_icon.psd", true);
    27.    
    28. }
    29.  
    The cars all have NavMeshAgent scripts, and the highway has a baked NavMesh. Running the code gives a console output that shows that each car's update method is getting called. Turning off some of the Debug.Log calls so that only the Logs in the Update () method get called shows that each car's Update() method is being called pretty frequently. And most bizarre of all is that if I place a car into the scene all on its own and set its target manually in the editor, it goes to the target the way I want the spawned cars to. What's wrong with my code?


    EDIT: Adding the following Debug.Log() to the Update() method:

    Code (csharp):
    1.  
    2. Debug.Log("Car update method called, position: x:" + transform.position.x + " y:" + transform.position.y + " z:" + transform.position.z);
    3.  
    Shows that the transform of spawned cars doesn't change at all, even though each car's destination is set. Why aren't the spawned cars going to their destinations even when their NavMesh's destinations are being set ok?

    EDIT: The following code must be in Start(), not Awake():

    Code (csharp):
    1.  
    2. if (target)
    3.         GetComponent(NavMeshAgent).destination = target.transform.position;
    4.  
    MachCUBED
     
    Last edited: Aug 17, 2012