0
\$\begingroup\$

How do I revert back to "normal" speed after a slight boost from hitting a collider mid-air?

private void OnCollisionEnter2D(Collision2D collision)
{
    var Speed = lastVelocity.magnitude;
    var Direction = Vector3.Reflect(lastVelocity.normalized, collision.GetContact(0).normal);
    rb.velocity = Direction * Mathf.Max(Speed, 0f);

    if (collision.gameObject.CompareTag("Blocker"))
    {
        rb.AddForce(Direction * 5f, ForceMode2D.Impulse);
    }

}

I'm using AddForce & it works but the thing is, it doesn't revert back to normal speed. I was told to try forcemode.impulse but it didn't work.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Use a coroutine:

IEnumerator WaitThenChangeSpeed(float delay, float speed) {
    yield return new WaitForSeconds(delay);
    rb.velocity = rb.velocity.normalized * speed;
}

void OnCollisionEnter2D(Collision2D collision)
{
    var speed = lastVelocity.magnitude;
    var direction = Vector3.Reflect(lastVelocity, collision.GetContact(0).normal).normalized;
    rb.velocity = direction * speed;

    if (collision.gameObject.CompareTag("Blocker"))
    {
        rb.AddForce(Direction * 5f, ForceMode2D.Impulse);
        StartCoroutine(WaitThenChangeSpeed(1f, speed));
    }
}

Note that there's no need for Mathf.Max here. By construction, Speed can only be non-negative, because .magnitude never returns a negative number.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .