Simple attack knockback: How to get two trigger colliders to interact?

Hi everyone,

I am trying to set up a basic knockback function, so that when my player hits the enemy they move back. My knockback code goes on my player.

For some reason, the code I have only works when the enemy’s collider has its IsTrigger set to false. I need it to be set to IsTrigger though, as the enemy has two colliders, one (which will NOT be a trigger) which will stop the player walking through it, and another (which WILL be a trigger) to represent the area you can hit it.

I don’t mind if the collider also triggers when the attack hits the body collider.

The collider on my player’s sword is set to IsTrigger, but this isn’t so important and I can have it set to false if it helps.

This is the Knockback code:

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

public class KnockBack : MonoBehaviour
{
    [SerializeField] private float thrust;
    public float knockTime = 0.3f;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            Rigidbody2D enemy = collision.GetComponent<Rigidbody2D>();
            if (enemy != null)
            {
                StartCoroutine(KnockCoroutine(enemy));
            }
        }
    }

    private IEnumerator KnockCoroutine(Rigidbody2D enemy)
    {
        if(enemy != null)
        {
            Vector2 forceDirection = enemy.transform.position - transform.position;
            Vector2 force = forceDirection.normalized * thrust;
            enemy.velocity = force;
            yield return new WaitForSeconds(knockTime);
            enemy.velocity = Vector2.zero;
        }
    }
}

Any help would be massively appreciated!

This seems to have resolved itself now!! Any suggestions as to where I was going wrong would still be much appreciated though :slight_smile: