0
\$\begingroup\$

In 2D platformer I'm having difficulty with knockback feature that happens when character touches enemy. That's implementation of it.

Character.cs:

public IEnumerator KnockBack(float knockbackDuration, float knockbackPower, Transform obj)
{
    float timer = 0;

    while (knockbackDuration > timer)
    {
        timer += Time.deltaTime;
        Vector2 direction = (obj.transform.position - transform.position).normalized;
        rigidbody.AddForce(-direction * knockbackPower);
    }

    yield return 0;
}

Enemy.cs invokes that knockback:

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Player")
    {
        StartCoroutine(player.KnockBack(knockbackDuration, knockbackPower, this.transform));
    }
}

When character stays still, enemy approaches it and triggers normal knockback. With pressed movement key char comes toward enemy and just pushes it. Nothing else happens. And if it jumps toward enemy, knockback is very, very powerful.

I try to get all of it behave in the same way. Enclosing code for character movements, just in case. Maybe vectors of rigidbody are overlapping somehow and that's the trouble.

private void Walk()
{
    float move = Input.GetAxis("Horizontal");
    rb.velocity = new Vector2(move * maxSpeed, GetComponent<Rigidbody2D>().velocity.y);
}

private void Jump()
{
    if (Input.GetKeyDown(KeyCode.Space) & onGround)
    {
        rb.velocity = new Vector2(rb.velocity.x, jumpForce);
    }
}

Also, if it is important, both of them have a BoxCollider2D.

\$\endgroup\$
3
  • \$\begingroup\$ It's somewhat ambiguous what parts of your text describe behaviour you want, and what parts describe a problem to solve. Can you edit your question to clarify how this code behaves now, and how that differs from what you want? \$\endgroup\$
    – DMGregory
    Commented Jul 3, 2022 at 23:31
  • \$\begingroup\$ Maybe yield return 0 should be in the while structure? otherwise there is no point in using coroutines. And can this coroutine accumulate? Maybe you can save it, and cancel the previous one before starting a new one. \$\endgroup\$
    – Mangata
    Commented Jul 4, 2022 at 2:26
  • \$\begingroup\$ @DMGregory The problem is that knockback mechanism produces very different result in such cases as: 1) coming up against enemy, 2) jumping towards enemy, 3) staying still when enemy approaches character. In fact only the last one works out correctly. \$\endgroup\$
    – FeelZ
    Commented Jul 4, 2022 at 9:24

0

You must log in to answer this question.

Browse other questions tagged .