How to fix player knockback,How to add Knockback on enemy attack

I want the player to experience knockback when the enemy collides with the player. The Debug.log returns “check”, butt the player does not move. There are no unity error’s. Can anybody help me out?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class Knockback : MonoBehaviour
{
public float thrust;

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {

        Rigidbody2D player = collision.GetComponent<Rigidbody2D>();
        Vector2 difference = player.transform.position - transform.position;
        difference = difference.normalized * thrust;
        player.AddForce(difference, ForceMode2D.Impulse);
        Debug.Log("Check");
                                    
    }
}

},I want the enemy attack to have a knockback effect on the player. I have used this script, butt it doesn’t work. Unity does not show an error. The debug.log function returns check(that works correctly). Butt the player just doesn’t move. Does anyone know what might be the error.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class Knockback : MonoBehaviour
{
public float thrust;

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        Rigidbody2D player = collision.GetComponent<Rigidbody2D>();
        Vector2 difference = player.transform.position - transform.position;
        difference = difference.normalized * thrust;
        player.AddForce(difference, ForceMode2D.Impulse);
        Debug.Log("Check");
   }
}

}

Hello, the code snippet you sent should be fine, at least it worked for me on a new object.

So I assume that somewhere else in the code of each frame you set the rigidbody velocity to a fixed value, or overwrite it again after this calculation. If that’s the case, then you could, for example, add a knockback delay, in which you briefly take control away from the player.