A checkpoint usually represents a certain distance through the game (or perhaps a track) in which an agent (user or NPC) has succeeded reaching. Reaching (or passing) checkpoints often results in bonus awards, such as extra time, points, ammo, and so on. Also, if a player has multiple lives, then often a player will be respawned only back as far as the most recently passed checkpoint, rather than right to the beginning of the level.
This recipe demonstrates a simple approach to the checkpoints, whereby once the player's character has passed a checkpoint, if they die they are moved back only to the most recently passed checkpoint.
This recipe builds upon the player-controlled 3D cube Unity project that you created at the beginning of this chapter. So, make a copy of this project, open it, and then follow the steps for this recipe.
To have the respawn position upon losing a life change depending on the checkpoints passed, follow these steps:
OnTriggerEnter
collision messages to be received).CheckPoints
to the Cube-player GameObject:using UnityEngine; using System.Collections; public class CheckPoints : MonoBehaviour { private Vector3 respawnPosition; void Start (){ respawnPosition = transform.position; } void OnTriggerEnter (Collider hit){ if(hit.CompareTag("CheckPoint")){ respawnPosition = transform.position; } if(hit.CompareTag("Death")){ transform.position = respawnPosition; } } }
The C# script class called CheckPoints
has one variable called respawnPosition
, which is a Vector3 that refers to the position the player's cube is to be moved to (respawned) if it collides with a Death tagged object. The default setting for this is the position of the player's cube when the scene begins—so in the Start()
method, we set it to the player's position.
Each time an object tagged called CheckPoint is collided with, the value of respawnPosition
is updated to the current position of the player's red cube at this point in time (that is, where it is when it touches the stretched cube tagged called CheckPoint). So that the next time the object tagged Death is hit, the cube will be respawned back to where it last touched the object tagged called CheckPoint.
18.116.36.194