How to Add Knockback Force Based on What Rotation it Came From

Whenever an enemy does a certain attack and it connects, I want the player to be launched backwards. The current code I have works, but it moves them based on what X Y and Z are put as, whereas I’d like it so that force is applied based on what rotation the enemy was in when they struck the player.

public class EnemyKnockbackHit : MonoBehaviour {

	public Rigidbody playerRigidbody;
	public Slider healthbar;
	public Vector3 moveDirection;
	
	void OnTriggerEnter(Collider attack)
    {
      if (attack.gameObject.tag == "KnockbackHit") {
     
          healthbar.value -= 20;
		  playerRigidbody.AddForce( moveDirection * -500f);
         }
		 
	  
     }

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

Do you mean to receive a knockback force from the direction the enemy is relative to the player? If so, just find the vector player position - enemy position and assign it to moveDirection:

void OnTriggerEnter(Collider attack){
    if (attack.gameObject.tag == "KnockbackHit") {
        healthbar.value -= 20;
        moveDirection = playerRigidbody.transform.position - attack.transform.position;
        playerRigidbody.AddForce( moveDirection.normalized * -500f);
    }
}

Not entirely sure what you mean from the wording of your question, but I assume you are trying to get an effect so that if the enemy is moving straight at the character the character will be knocked back, and if the enemy is spinning really fast and moving slowly, then you’d want the character to be knocked sideways, and if both spinning and charging, the character should be knocked back and sideways?

If so, I think what you are looking for is Unity - Scripting API: Rigidbody.GetPointVelocity , which will return the velocity of a point in world space of a rigidbody, taking into account the angular velocity. So you’d find the impact point of the enemy and your character and ask your enemy’s rigidbody what the point velocity is at that point. Then you’d use AddForceAtPosition on your character to knock it in the correct direction (possibly spinning it as well!)

If you don’t have a rigidbody for the enemy, respond in the comments and I can write down the math for you (but I assume you have a rigidbody since your enemy is rotating).