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();
}