Search Unity

Car following an object?

Discussion in 'Scripting' started by yoash, Jan 2, 2016.

  1. yoash

    yoash

    Joined:
    Sep 3, 2013
    Posts:
    36
    I am trying to make a car drive towards a player and ram him.

    I've looked at the asset store and can't find anything.

    My current script has the car making strange turns and circling the ball.

    Any help would be much appreciated

    Code (CSharp):
    1.     void  Update (){
    2.  
    3.             lookAt();
    4.  
    5.             chase ();
    6.  
    7.      
    8.         //keeps car on floor
    9.   transform.rotation = Quaternion.Euler(lockPos, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
    10.         if (transform.position.y < 0) {
    11.             transform.position = new Vector3 (transform.position.x, 0, transform.position.z);
    12.         }
    13.         if (transform.position.y > 0) {
    14.             transform.position = new Vector3 (transform.position.x, 0, transform.position.z);
    15.            
    16.         }
    17.        
    18.     }
    19.    
    20.     // Turn to face the player.
    21.     void  lookAt (){
    22.         // Rotate to look at player.
    23.         Quaternion rotation= Quaternion.LookRotation(Target.position - transform.position);
    24.        
    25.         transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime);
    26.  
    27.     }
    28.    
    29.     void  chase (){
    30.         transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);  
    31.     }
     
  2. planetxo

    planetxo

    Joined:
    Jan 18, 2016
    Posts:
    5
    Try making the car not chase until it is facing in the direction of the player
     
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    8,131
    @planetxo's suggestion is a good one. Or if you want it slightly more natural, adjust the speed smoothly based on the angle between the car's heading and the direction of the player. (You can use Vector3.Angle to find out what this angle is.)