Timed boost with Coroutines

I also implemented coroutines! Right now, the boost and bump will only last 3 seconds, but you can easily just pass any time amount to the coroutine.

public class Driver : MonoBehaviour
{

[SerializeField] float steerSpeed = 0.1f;
[SerializeField] float baseSpeed = 10f;
[SerializeField] float boostSpeed = 20f;
[SerializeField] float slowSpeed = 4f;
[SerializeField] float timeToNormal = 3f;
float moveSpeed;

// Start is called before the first frame update
void Start()
{
    moveSpeed = baseSpeed;
}

// Update is called once per frame
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(0f, moveAmount, 0f) ;
}

void OnCollisionEnter2D(Collision2D other)
{
    if (other.gameObject.CompareTag("Scenery"))
    {
        moveSpeed = slowSpeed;
        StartCoroutine(backToNormal(timeToNormal));
    }
}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.CompareTag("SpeedUp"))
    {
        moveSpeed = boostSpeed;
        StartCoroutine(backToNormal(timeToNormal));
    }
}

IEnumerator backToNormal(float time)
{
    yield return new WaitForSeconds(time);
    moveSpeed = baseSpeed;

}

}

3 Likes

That’s an interesting design choice, hope you upload your final game, sounds interesting.

You can achieve the same results using the Invoke method.

Thanks, Yee! That does seem a lot easier. I’ll have to try it.

Thank you for this! This is just what I was looking for! I didn’t want the slow of fast speed to be eternal. Now, thanks to you I am able to have the speed temporarily.

Privacy & Terms