Game Development Reference
In-Depth Information
Death and resurrection - respawning
With the state system now set up properly, we need to add some logic to the
PlayerStateListener
script so that it knows how to handle player death and
respawn. What we want to happen is this: when the player dies, they respawn at
a point in the level and the camera snaps back to this point. So, let's start by adding
another empty GameObject. Name this one
Player Respawn Point
and set the
X
and
Y
position of it to
X: 0
,
Y: 1.5
. It should now be hovering above the same place
that the player is at in the level.
This will give the game a way to find a spawn point in the level and allow us to
move it around if we need to. Next, let's tell the player's state scripts to use this
object. Open the
PlayerStateListener
script and add the following code near its
beginning, where the properties are defined:
public GameObject playerRespawnPoint = null;
As you may have guessed, we need to place the new respawn point object in the
Player Respawn Point
field in the
Inspector
panel. Go back to the Unity editor
and add the
playerRespawnPoint
object to this newly created field on the
Player
object's
PlayerStateListener
component.
Scroll down a little bit in
PlayerStateListener
; let's modify the
resurrect
state
inside the
onStateChange
method. Set the code to look like the following:
case PlayerStateController.playerStates.resurrect:
transform.position = playerRespawnPoint.transform.position;
transform.rotation = Quaternion.identity;
rigidbody2D.velocity = Vector2.zero;
break;
This will now cause the player object to move to the appropriate respawn point in
the scene when the
resurrect
state is toggled. As the camera is already tracking
the player based on its states, the
Main Camera
object will automatically keep up.
Currently, we don't need much else to happen except for the player to resurrect as
soon as they die, so let's temporarily modify the
kill
and
resurrect
cases in the
onStateCycle
method to quickly jump to the next state.
case PlayerStateController.playerStates.kill:
onStateChange(PlayerStateController.playerStates.resurrect);
break;
case PlayerStateController.playerStates.resurrect:
onStateChange(PlayerStateController.playerStates.idle);break;