My hurt & death animations

Hi everyone!

I changed the code slightly, so that my character doesn’t die until they’ve been hit three times. In order to do this:

  1. Add the following line to the very top of the code (for me, Line #5):
using UnityEngine.SceneManagement;
  1. I added the following code to the beginning of my script:
    bool isAlive = true;
    bool isInvulnerable = false;
    float playerHealth = 3f;
  1. I expanded upon the code Rick gave us in the lecture:
     void Die()
    {
        if (isInvulnerable) { return; }  //This means a player can't be hit over & over.....
        if(myBodyCollider.IsTouchingLayers(LayerMask.GetMask("Enemies")))
        {
            isAlive = false;
            playerHealth -= 1f; //This subtracts 1 health
            isInvulnerable = true;  //This prevents further damage for the time being
            if (playerHealth > 0)
            {
                ResetBool();  //This is a script where I set all of my "myAnimator.SetBool..." options to false, to guarantee that the only animation that plays is the injured one
                myRigidbody.gravityScale = gravityScaleAtStart; //This is to ensure that if the player is on a ladder, they obey the laws of physics, not the ladder...
                myAnimator.SetBool("IsHurt", true); //start animation
                myRigidbody.AddForce(transform.up*verticalKnockback, ForceMode2D.Impulse); //vertical knockback
                myRigidbody.AddForce(transform.right * horizontalKnockback, ForceMode2D.Impulse);  //horizontal knockback
                Invoke("RemoveInvulnerable", 2f);   //resets all variables with the hurt animation, so we can go back to normal
                Debug.Log(playerHealth);
            }
            else
            {
                ResetBool();
                myAnimator.SetBool("IsDead", true);
                Invoke("RestartLevel", 3f);  //See below
            }           
        }
    }

    void ResetBool()  //This is to reset all animation bools
    {
        myAnimator.SetBool("IsJumping", false);
        myAnimator.SetBool("IsClimbing", false);
        myAnimator.SetBool("IsMelee", false);
    }

    void RemoveInvulnerable()  //This whole thing is to set things back to normal
    {
        isAlive = true;
        isInvulnerable = false;
        myAnimator.SetBool("IsHurt", false);
        myAnimator.SetBool("IsWalking", false);
        moveSpeed = 0f;  //this is needed to ensure you start over with the "idle" animation
    }

    void RestartLevel()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name); //This is to restart the level if you die
    }

Hope this helps!

Steve

2 Likes

Privacy & Terms