How to make standard assets vechile ai go backwards when crashing into a wall

When I was testing my game, I made the player car crash the ai car into a wall and the ai car seems to try to drive through the wall but since the wall is a non-trigger collider it can’t. So how do you make ai car go backwards? (e.g. like pressing the down arrow key when you are player. How do you do this functionality for the ai car?)

I ran into this bugger when I was working on an older project. You could try setting the car’s speed to negative. However, me being the lazy noob I am, I just added force to the car’s Rigidbody to force the car to move back and try to follow the player again. Worked 99% of the time.

thx for the reply. i will check it out.

What’s wrong with this code?

using UnityEngine;
using System.Collections;

public class GoBack : MonoBehaviour {

    Rigidbody rig;

    private void Awake()
    {
        rig = GetComponentInParent<Rigidbody> ();
    }

    void OnCollisionEnter(Collision other){
        Debug.Log ("ONCollisionEnter");
        if (other.gameObject.CompareTag ("Wall")) {
            Debug.Log ("It is a wall!");
            rig.AddForce (new Vector3 (0, 0, -10));

        }

    }
}

I am trying to make ai car go backwards by adding a negative force. However it is not working. Also, no debug messages, warnings, or errors show up. What am I doing wrong? I double checked the spelling of on collision enter and attached the script all the colliders of the ai car. So what am I doing wrong?

Check if it is finding the rigidbody at all (in your Awake function).

Take a look in these docs: http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter.html
Since it isn’t running the Debug.log apparently it isn’t detecting the collision.

Never mind, I fixed it. I instead created a trigger collider and put that on the car. Then I decided to put this script instead on to a wall. And this is what I wrote:

using UnityEngine;
using System.Collections;

public class GoBack : MonoBehaviour {

    Rigidbody rig;


    void OnTriggerEnter(Collider other){
        Debug.Log ("ONCollisionEnter");
        if (!other.gameObject.CompareTag ("Go Back"))
            return;
       
            rig = other.gameObject.GetComponentInParent<Rigidbody> ();
            Debug.Log ("It is a wall!");
            rig.AddForce (new Vector3 (0, 0, -10));


    }
}

To be honest, I don’t know why the on collision enter won’t work but whatever. This script works though.

Wow I’m completely stumped on this because I used to use OnCollision before and it worked. Now I have to dig into this…

It is kind of weird… I admit.

I got it to work with 2 cubes but can’t get it to work on my Player gameobject… glad to see your found a solution :slight_smile:

:slight_smile: ur welcome.

@DroidifyDevs For some reason, the script is not working again?. What is going on? The script is the same as I wrote above.