Player knockback on enemy contact

I’m struggling with trying to get my character to move back when he gets hit by an enemy. I want two things to happen:

  1. While the player is being knocked back, I don’t want them to be able to move around.
  2. I want the player to translate a short distance to the left or right, depending on which side they get knocked from.

Here is my OnCollisionEnter function in my player movement script. For some reason, the character does not get moved back when he collides with an enemy, and I can still move him around while his damage animation is playing.

void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.tag == "Enemy")
        {
            if (transform.position.x < col.transform.position.x)
            {
                knockFromRight = true;
            }
            else
            {
                knockFromRight = false;
            }
            if (knockbackCount <= 0)
            {
                GetComponent<Rigidbody> ().velocity = new Vector2 (moveDirection * maxSpeed, GetComponent<Rigidbody> ().velocity.y);
            }
            else
            {
                if (knockFromRight)
                {
                    GetComponent<Rigidbody> ().velocity = new Vector2 (-knockback, 0);
                }
                if (!knockFromRight)
                {
                    GetComponent<Rigidbody> ().velocity = new Vector2 (knockback, 0);
                }
                knockbackCount -= Time.deltaTime;
            }
            anim.SetTrigger ("damage");
        }
    }

If you want your player to stop moving, you have to actually disable input, otherwise your movement code will just override that.

You’re also never setting knockbackCount to anything. I’m not sure what it’s supposed to do, but the else after if(knockbackCount <=0) will never fire unless you’re setting knockbackCount from somewhere else.

My bad, knockbackCount is basically just a countdown timer. In my Awake function, I have it set to equal “knockbackLength”, which is publicly set to 0.2 seconds. I’ll post the entirety of my script to avoid any further confusion. I’m thinking part of the problem is that OnCollisionEnter only executes for one frame, so I’m going to try to move the entire “if (knockbackCount <= 0)” if-else structure into my Update function and see what that does.

using UnityEngine;
using System.Collections;

public class JabMovement : MonoBehaviour
{
    public float maxSpeed = 6.0f;
    public bool facingRight = true;
    public float moveDirection;

    public float jumpSpeed = 600.0f;
    public bool grounded = false;
    public Transform groundCheck;
    public float groundRadius = 0.2f;
    public LayerMask whatIsGround;

    public float handSpeed = 600.0f;
    private bool ActivateTimerToReset = false;
    public float currentComboTimer = 1.0f;
    public int currentComboState = 0;
    private float origTimer;
    public Transform handSpawn;
    public Rigidbody handPrefab;

    private bool knocked = false;
    private bool ActivateKBToReset = false;
    public float knockback;
    public float knockbackLength = 0.2f;
    public float knockbackCount;
    public bool knockFromRight;

    Rigidbody clone;

    private Animator anim;

    void Awake()
    {
        groundCheck = GameObject.Find ("GroundCheck").transform;
        handSpawn = GameObject.Find ("HandSpawn").transform;
        GetComponent<Rigidbody> ().sleepThreshold = 0.0f;
        anim = GetComponentInChildren<Animator> ();
        origTimer = currentComboTimer;
        knockbackCount = knockbackLength;
    }
       
    // Use this for initialization
    void FixedUpdate ()
    {
        grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);

        anim.SetBool("grounded", grounded);

        if (!this.anim.GetCurrentAnimatorStateInfo (0).IsTag ("Attack"))
        {
            GetComponent<Rigidbody> ().velocity = new Vector2 (moveDirection * maxSpeed, GetComponent<Rigidbody> ().velocity.y);
        }
        anim.SetFloat ("speed", Mathf.Abs (moveDirection));


        if (moveDirection > 0.0f && !facingRight)
        {
            Flip ();
        } else if (moveDirection < 0.0f && facingRight) {
            Flip ();
        }
    }
   
    // Update is called once per frame
    void Update ()
    {
        moveDirection = Input.GetAxis ("Horizontal");


        if (grounded && Input.GetButtonDown ("Jump"))
        {
            grounded = false;
            anim.SetBool ("grounded", grounded);
            GetComponent<Rigidbody>().AddForce (new Vector2 (0, jumpSpeed));

        }
        if (Input.GetButtonDown("Fire1") && grounded && !this.anim.GetCurrentAnimatorStateInfo (0).IsTag ("Attack"))
        {
            anim.SetTrigger ("attack");
            GetComponent<Rigidbody> ().velocity = Vector2.zero;
            Attack ();
        }
        if (Input.GetButtonDown("Fire1") && !grounded && !this.anim.GetCurrentAnimatorStateInfo (0).IsTag ("Attack"))
        {
            anim.SetBool ("jumpAttack", true);
            Attack ();
        }
        if (!Input.GetButtonDown("Fire1") && !this.anim.GetCurrentAnimatorStateInfo (0).IsTag ("Attack"))
        {
            anim.SetBool ("jumpAttack", false);
        }
        knocked = false;
        NewComboSystem ();
        ResetComboState (ActivateTimerToReset);
    }
    void Flip()
    {
        facingRight = !facingRight;

        transform.Rotate (Vector3.up, 180.0f, Space.World);
    }
    void Attack()
    {
        clone = Instantiate (handPrefab, handSpawn.position, handSpawn.rotation) as Rigidbody;
        clone.AddForce (handSpawn.transform.right * handSpeed);
    }
    void ResetComboState(bool resetTimer)
    {
        if (resetTimer)
        {
            currentComboTimer -= Time.deltaTime;
            if (currentComboTimer <= 0)
            {
                currentComboState = 0;
                ActivateTimerToReset = false;
                currentComboTimer = origTimer;
            }
        }
    }



    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.tag == "Enemy")
        {
            knocked = true;
            if (transform.position.x < col.transform.position.x)
            {
                knockFromRight = true;
            }
            else
            {
                knockFromRight = false;
            }
            if (knockbackCount <= 0)
            {
                GetComponent<Rigidbody> ().velocity = new Vector2 (moveDirection * maxSpeed, GetComponent<Rigidbody> ().velocity.y);
            }
            else
            {
                if (knockFromRight)
                {
                    GetComponent<Rigidbody> ().velocity = new Vector2 (-knockback, 0);
                }
                if (!knockFromRight)
                {
                    GetComponent<Rigidbody> ().velocity = new Vector2 (knockback, 0);
                }
                knockbackCount -= Time.deltaTime;
            }
            anim.SetTrigger ("damage");
        }
    }
    void NewComboSystem()
    {
        if (Input.GetButtonDown ("Fire1"))
        {
            currentComboState++;
            ActivateTimerToReset = true;
            if (Input.GetButtonDown ("Fire1") && grounded && currentComboState == 2 && !this.anim.GetCurrentAnimatorStateInfo (0).IsTag ("Attack2"))
            {
                anim.SetTrigger ("attack2");
                GetComponent<Rigidbody> ().velocity = Vector2.zero;
                Attack ();
            }
            if (Input.GetButtonDown ("Fire1") && grounded && currentComboState >= 3 && !this.anim.GetCurrentAnimatorStateInfo (0).IsTag ("Attack3"))
            {
                anim.SetTrigger ("attack3");
                GetComponent<Rigidbody> ().velocity = Vector2.zero;
                Attack ();
            }
            if (Input.GetButtonDown ("Fire1") && !grounded && currentComboState == 2)
            {
                anim.SetTrigger ("attack2");
                Attack ();
            }
            if (Input.GetButtonDown ("Fire1") && !grounded && currentComboState >= 3)
            {
                anim.SetTrigger ("attack3");
                Attack ();
            }
        }
    }
}

Yep, that did the trick :slight_smile: Thank you for your advice on disabling the input, I believe that put me on the right track.

I moved the if-else statement to Update, and I also added a countdown timer function, ResetKBState, that disables the player’s movement and jumping until the timer runs out (which I set for half a second). I also changed my Rigidbody.velocity to a Rigidbody.AddForce. For some reason, velocity wasn’t working for me, any idea why?

Anyways, here’s my full script for anyone else who has this problem.

using UnityEngine;
using System.Collections;

public class JabMovement : MonoBehaviour
{
    public float maxSpeed = 6.0f;
    public bool facingRight = true;
    public float moveDirection;

    public float jumpSpeed = 600.0f;
    public bool grounded = false;
    public Transform groundCheck;
    public float groundRadius = 0.2f;
    public LayerMask whatIsGround;

    public float handSpeed = 600.0f;
    private bool ActivateTimerToReset = false;
    public float currentComboTimer = 1.0f;
    public int currentComboState = 0;
    private float origTimer;
    public Transform handSpawn;
    public Rigidbody handPrefab;

    private bool ActivateKBToReset = false;
    public float knockback;
    public float knockbackLength = 0.2f;
    public float knockbackCount;
    public bool knockFromRight;

    Rigidbody clone;

    private Animator anim;

    void Awake()
    {
        groundCheck = GameObject.Find ("GroundCheck").transform;
        handSpawn = GameObject.Find ("HandSpawn").transform;
        GetComponent<Rigidbody> ().sleepThreshold = 0.0f;
        anim = GetComponentInChildren<Animator> ();
        origTimer = currentComboTimer;
        knockbackCount = knockbackLength;
    }
       
    // Use this for initialization
    void FixedUpdate ()
    {
        grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);

        anim.SetBool("grounded", grounded);

        if (!this.anim.GetCurrentAnimatorStateInfo (0).IsTag ("Attack"))
        {
            GetComponent<Rigidbody> ().velocity = new Vector2 (moveDirection * maxSpeed, GetComponent<Rigidbody> ().velocity.y);
        }
        anim.SetFloat ("speed", Mathf.Abs (moveDirection));


        if (moveDirection > 0.0f && !facingRight)
        {
            Flip ();
        } else if (moveDirection < 0.0f && facingRight) {
            Flip ();
        }
    }
   
    // Update is called once per frame
    void Update ()
    {
        moveDirection = Input.GetAxis ("Horizontal");

        if (grounded && Input.GetButtonDown ("Jump"))
        {
            grounded = false;
            anim.SetBool ("grounded", grounded);
            GetComponent<Rigidbody>().AddForce (new Vector2 (0, jumpSpeed));

        }
        if (Input.GetButtonDown("Fire1") && grounded && !this.anim.GetCurrentAnimatorStateInfo (0).IsTag ("Attack"))
        {
            anim.SetTrigger ("attack");
            GetComponent<Rigidbody> ().velocity = Vector2.zero;
            Attack ();
        }
        if (Input.GetButtonDown("Fire1") && !grounded && !this.anim.GetCurrentAnimatorStateInfo (0).IsTag ("Attack"))
        {
            anim.SetBool ("jumpAttack", true);
            Attack ();
        }
        if (!Input.GetButtonDown("Fire1") && !this.anim.GetCurrentAnimatorStateInfo (0).IsTag ("Attack"))
        {
            anim.SetBool ("jumpAttack", false);
        }
        NewComboSystem ();
        ResetComboState (ActivateTimerToReset);
        ResetKBState (ActivateKBToReset);
    }
    void Flip()
    {
        facingRight = !facingRight;

        transform.Rotate (Vector3.up, 180.0f, Space.World);
    }
    void Attack()
    {
        clone = Instantiate (handPrefab, handSpawn.position, handSpawn.rotation) as Rigidbody;
        clone.AddForce (handSpawn.transform.right * handSpeed);
    }
    void ResetComboState(bool resetTimer)
    {
        if (resetTimer)
        {
            currentComboTimer -= Time.deltaTime;
            if (currentComboTimer <= 0)
            {
                currentComboState = 0;
                ActivateTimerToReset = false;
                currentComboTimer = origTimer;
            }
        }
    }

    void ResetKBState (bool resetKB)
    {
        if (resetKB)
        {
            knockbackCount -= Time.deltaTime;
            if (knockbackCount <= 0)
            {
                moveDirection = Input.GetAxis ("Horizontal");
                jumpSpeed = 600.0f;
                ActivateKBToReset = false;
                knockbackCount = knockbackLength;
            }
            else
            {
                moveDirection = 0.0f;
                jumpSpeed = 0.0f;
                if (knockFromRight)
                {
                    GetComponent<Rigidbody> ().AddForce (new Vector2 (-knockback, 0));
                }
                if (!knockFromRight)
                {
                    GetComponent<Rigidbody> ().AddForce (new Vector2 (knockback, 0));
                }
            }
        }
    }

    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.tag == "Enemy")
        {
            ActivateKBToReset = true;
            if (transform.position.x < col.transform.position.x)
            {
                knockFromRight = true;
            }
            else
            {
                knockFromRight = false;
            }
            anim.SetTrigger ("damage");
        }
    }
    void NewComboSystem()
    {
        if (Input.GetButtonDown ("Fire1"))
        {
            currentComboState++;
            ActivateTimerToReset = true;
            if (Input.GetButtonDown ("Fire1") && grounded && currentComboState == 2 && !this.anim.GetCurrentAnimatorStateInfo (0).IsTag ("Attack2"))
            {
                anim.SetTrigger ("attack2");
                GetComponent<Rigidbody> ().velocity = Vector2.zero;
                Attack ();
            }
            if (Input.GetButtonDown ("Fire1") && grounded && currentComboState >= 3 && !this.anim.GetCurrentAnimatorStateInfo (0).IsTag ("Attack3"))
            {
                anim.SetTrigger ("attack3");
                GetComponent<Rigidbody> ().velocity = Vector2.zero;
                Attack ();
            }
            if (Input.GetButtonDown ("Fire1") && !grounded && currentComboState == 2)
            {
                anim.SetTrigger ("attack2");
                Attack ();
            }
            if (Input.GetButtonDown ("Fire1") && !grounded && currentComboState >= 3)
            {
                anim.SetTrigger ("attack3");
                Attack ();
            }
        }
    }
}