knockback enemy via animation

I’ve gotten an attack animation working and was trying to figure out how to add knockback to the attack.
Keep in mind I don’t wish to destroy or subtract health from the enemy only knockback them back.

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

public class armcontroller : MonoBehaviour
{
public GameObject arms;
public bool CanAttack = true;
public float AttackCooldown = 1.0f;
public AudioClip Armattacksound;

 void Update()
{
    if (Input.GetMouseButton(0))
    {
        if (CanAttack)
        {
            ArmAttack();
        }
    }
}

public void ArmAttack()
{

    CanAttack = false;
    Animator anim = arms.GetComponent<Animator>();
    anim.SetTrigger("attack");

    AudioSource ac = GetComponent<AudioSource>();
    ac.PlayOneShot(Armattacksound);

    StartCoroutine(ResetAttackCooldown());
    IEnumerator ResetAttackCooldown()
    {
        yield return new WaitForSeconds(AttackCooldown);
        CanAttack = true;
    }
}

}

Hi!

If you’re using rigidbody, all you have to do is call Rigidbody.AddForce() and you’ll get a standard physics push.

If that’s not the case, you’ll have to do a bit more work. The easiest solution is probably just to change the enemies position via Coroutine, something like this:

const float KnockbackFactor = 0.1f;
IEnumerator ResetAttackCooldown()
{
    float startingTime = Time.time;

    while (Time.time - startingTime < AttackCooldown)
    {
        float percentageComplete = (Time.time - startingTime) / AttackCooldown;

        enemyTransform.position += Vector3.right * Time.deltaTime * KnockbackFactor * (1-percentageComplete);

        yield return null;
    }

    CanAttack = true;
}

This one should also start with more push but slowly decrease. You may need to play around with the KnockbackFactor constant if it doesn’t seem to be doing anything, but it should be more than enough to get you started!

Hope this helps!