OnCollisionEnter2D , Player knockback

Hello Unity community!

I am struggling to make a proper knockback script for my player, my current goal is to make him get pushed back everytime he gets hit by an enemy.

This is what I got:

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Enemy")
        {
            myRigidbody.AddForce(new Vector2(10, 5) * 500);
        }
    }

My current problems:

  • Knockback is not smooth at all
  • Only gets knocked back to the left side, what if the enemy comes from the other side?

Thank you for your help in advance.

you can check enemys position.
as example: if (collision.gameObject.transform.position.x - transform.position.x > 0)
or position direct: if (collision.gameObject.transform.position.x < transform.position.x )

Resolved.
Thank you