Respawn and invulnerability

Tutorial by Luca Bordoni
 
This tutorial is oriented to AGD programmers who are already involved in a project; it’s suggested to read & learn the AGD official documentation first.
 
A common question while developing AGD games: “if my sprite dies, i’d like to let the respawn in the exact death point, and the player shouldn’t be killed for few seconds after coming back to life”.
 
 
The solution: working with variables
 
Assuming we still have available some variable, the idea is to setup a couple of variables to clone the player’s horizontal and vertical position, and a third variable to manage a timer for the invulnerability.
 
First of all, as seen in the AGD video tutorials by Paul Jenkinson, we need to setup a timing in the MAIN LOOP event, useful to avoid too fast movements:

IF A = 1
LET A = 0
ELSE
ADD 1 TO A
ENDIF

Now let’s go in GAME INITIALISATION to setup our new variables. We need a variable for the invulnerability timer, let’s say “I”, and other two variables to clone the player’s X/Y position, e.g. “O” and “P”:

LET A = 0

LET I = 0   (no invulnerability when the first play starts)
LET O = 80  (or other value, clones player’s X pixel position)
LET P = 120 (or other value, clones player’s Y pixel position)

Then, let’s enter in the PLAYER 0 event (sprite 0), where we’ll use normally the X/Y variables.
At the bottom of the section, let’s write:


LET O = X
LET P = Y

Now we have two variables always monitoring our player’s position.
 
In the INITIALISE SPRITE event, let’s write:

IF TYPE 0
LET X = O
LET Y = P
ENDIF

That means the player will appear at the cloned coordinates, which correspond to the X/Y values at the start of play!
 
 
Add the invulnerability
 
The following code is the excerpt we’ll have to include in our custom kill routine. The way we can manage a collision between the player and a deadly enemy or block could vary, and here we won’t discuss the killing routine; rather, the way to include an invunerability status for a limited time.
 
So, inside our sprite’s death routine, e.g. into the COLLISION condition between the player and the enemy, let’s give a value to the invulnerability timer:

(start the "IF COLLISION" condition)

IF I > 0
ELSE       (if timer has a value greater than 0, do nothing)
LET I = 25 (or other value, corresponds to some seconds of invulnerability)
KILL
ENDIF

(end the "IF COLLISION" condition)

Note that the LET I = 25 instruction could be included directly into the AGD KILL event, in case we’re managing our routine there. The point is to set the invulnerability timer before the play restarts.
 
Then, in the PLAYER 0 event, let the code begin this way:

IF I > 0
GETRANDOM 7
ADD 65 TO RND
SPRITEINK RND
IF A = 0
SUBTRACT 1 FROM I
ENDIF
ELSE
LET I = 0
SPRITEINK 71
ENDIF

This is a nice tip to change the player’s color in order to let the user know he’s invulnerable 😉