🛤 Get slower when you are out of the Road

After finishing the “Delivery Driver” I was thinking of a list of improvements in order to take on small challenges. One of them is to reduce the speed of the car when it’s outside of the Road. After searching a little I found the OnTriggerExit2D and OnTriggerStay2D was a good solution.

Also, we are using here the “tags” we see in the lecture. I highly recommend creating an empty object, get all the roads inside as a child and then putting the tag once for all

    [SerializeField] float steerSpeed = 200f;
    [SerializeField] float moveSpeed = 15f;
    [SerializeField] float outOfRoadSpeed = 5f;
    [SerializeField] float normalSpeed = 15f;

     void OnTriggerExit2D(Collider2D other)
    {
        if (other.tag == "roads")
        {
            moveSpeed = outOfRoadSpeed;
            Debug.Log("Out of the Road!");
        }
    }

     void OnTriggerStay2D(Collider2D other)
    {
        if (other.tag == "roads") 
        { 
            moveSpeed = normalSpeed;
            Debug.Log("Return to normalSpeed");
        }
    }

Hope this helps someone!

Cheers

4 Likes

Thank you for sharing this. This is awesome!

Thanks for sharing this! I was also trying to figure this out as well. Cheers!

Did you set up a collider for each road piece ?

Privacy & Terms