My solution to restoring speed when crashing or boosting!

Without using coroutine because I got so confused when trying to use them.
Hope this helps anyone and open for feedback!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Driver : MonoBehaviour
{
    [SerializeField] float steerSpeed = 1f;
    [SerializeField] float moveSpeed = 0.01f;
    [SerializeField] float slowSpeed = 0.01f;
    [SerializeField] float boostSpeed = 0.01f;
    [SerializeField] int boostDuration = 2;
    float regularSpeed = 20;

    private bool isBoostActivated = false;
    private bool hasCarCrashed = false;
    
    void Start() 
    {

    }

    void Update()
    {
        float steerAmount = Input.GetAxis("Horizontal") * steerSpeed * Time.deltaTime;
        float moveAmount = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime; 
        transform.Rotate(0, 0, -steerAmount);
        transform.Translate(0, moveAmount, 0);
        if(isBoostActivated)
        {
            moveSpeed = boostSpeed;
        }
        if(hasCarCrashed)
        {
            moveSpeed = slowSpeed;
        }
    }

    void OnCollisionEnter2D(Collision2D other) 
    {
        if (!hasCarCrashed)
        {
            Debug.Log("Slowing player speed");
            hasCarCrashed = true;
        }
        Invoke("EndCrash", boostDuration);
    }
    void OnTriggerEnter2D(Collider2D other) 
    {
        if(other.tag == "Boost")
        {
            if (!isBoostActivated)
            {
                Debug.Log("Boosting player speed");
                isBoostActivated = true;
            }
            Invoke("EndBoost", boostDuration);
        }

        if(other.tag == "Car")
         
            if (!hasCarCrashed)
            {
                Debug.Log("Slowing player speed");
                hasCarCrashed = true;
            }
            Invoke("EndCrash", boostDuration);
        }
    private void EndBoost()
    {
        isBoostActivated = false;
        moveSpeed = regularSpeed;
    }
    private void EndCrash()
    {
        hasCarCrashed = false;
        moveSpeed = regularSpeed;
    }
}

Privacy & Terms