Show player death animations

Hey all, one thing that kind of bugged me about this course was that once the Scene and Game managers were in place, when you died the level instantly restart, so you never actually saw the death animations.

I also wanted to add a different death for hitting a water hazard vs enemy or spike.

Here is how I did it, but I think it’d be good to add to the course in the future. Glad to hear feedback on any/all improvements!

In my PlayerMovement script:
Variable declarations-

[SerializeField] Vector2 deathKick = new Vector2(10f, 10f);

[SerializeField] Vector2 deathDrown = new Vector2(0, -0.5f);

[SerializeField] float respawnTime = 1.5f;

float gravityScaleAtStart;

float gravityAtDeath;

void Start()

{

    myRigidBody = GetComponent<Rigidbody2D>();

    myAnimator = GetComponent<Animator>();

    myBodyCollider = GetComponent<CapsuleCollider2D>();

    myFeetCollider = GetComponent<BoxCollider2D>();

    gravityScaleAtStart = myRigidBody.gravityScale = 8f;

    gravityAtDeath = myRigidBody.gravityScale = 1f;

}

void Die()

{

    if (myBodyCollider.IsTouchingLayers(LayerMask.GetMask("Enemy", "Hazards")))

    {

    isAlive = false;

    myRigidBody.velocity = deathKick;

    myAnimator.SetTrigger("Dying");

    StartCoroutine(DeathRespawnTime());

    }

    if (myBodyCollider.IsTouchingLayers(LayerMask.GetMask("Water")))

    {

    isAlive = false;

    myRigidBody.gravityScale = gravityAtDeath;

    myRigidBody.velocity = deathDrown;

    myAnimator.SetTrigger("Dying");

    StartCoroutine(DeathRespawnTime());

    }

}

IEnumerator DeathRespawnTime()

{

    yield return new WaitForSecondsRealtime(respawnTime);

    FindObjectOfType<GameSession>().ProcessPlayerDeath();

}
1 Like

Welcome to the community! This is a really amazing solution to the issue at hand.

Just some observations:

  • I honestly had no idea what deathKick and deathDrown were until I read the entire code and I’m still not 100% sure what they are for but if I understood correctly, maybe deathPushSpeed and drowningSpeed would be better names.
  • Why are you caching the gravityScaleAtStart and gravityAtDeath? Wouldn’t it be better to have them exposed in the inspector to be able to test things more easily?
  • The code below is weird, Is there any reason why you are doing it like that?
    gravityScaleAtStart = myRigidBody.gravityScale = 8f;

    gravityAtDeath = myRigidBody.gravityScale = 1f;

Privacy & Terms