So I add a small functionality to restore driver speed to its normal speed after 3 seconds, using Coroutine. Might do the same for the bump part in the future. Please take a look.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarScript : MonoBehaviour
{
[SerializeField] float SteerSpeed = 230.0f;
[SerializeField] float TopSpeed = 30.0f;
[SerializeField] float MoveSpeed = 20.0f;
[SerializeField] float NeutralSpeed = 10.0f;
[SerializeField] float BoostTime = 3.0f;
[SerializeField] float _speed;
private bool _shouldSlowDown;
private float _marker;
private Coroutine _boostCoroutine;
void Start()
{
this._speed = this.MoveSpeed;
this._shouldSlowDown = false;
}
void Update()
{
if (this._shouldSlowDown)
{
this._shouldSlowDown = false;
this._boostCoroutine = this.StartCoroutine(this.RestoreSpeed(this.BoostTime));
}
float moveAmount = Input.GetAxis("Vertical") * this._speed * Time.deltaTime;
int steerMark = 1;
if (moveAmount < 0)
{
steerMark = -1;
}
float steerAmount = -Input.GetAxis("Horizontal") * this.SteerSpeed * Time.deltaTime * steerMark;
this.transform.Rotate(0, 0, steerAmount);
this.transform.Translate(0, moveAmount, 0);
}
void OnCollisionEnter2D(Collision2D other)
{
this._speed = this.NeutralSpeed;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Boost"))
{
this._StopRestoreSpeed();
this._speed = this.TopSpeed;
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Boost"))
{
this._shouldSlowDown = true;
}
}
IEnumerator RestoreSpeed(float time)
{
while (this._marker < time)
{
Debug.Log("Time marker: " + this._marker);
this._marker += Time.deltaTime;
if (this._marker >= time)
{
this._speed = this.MoveSpeed;
this._StopRestoreSpeed();
}
yield return null;
}
}
private void _StopRestoreSpeed() {
if (this._boostCoroutine != null)
{
this._marker = 0;
this.StopCoroutine(this._boostCoroutine);
}
}
}