Skip to content
zal0 edited this page Jan 27, 2022 · 1 revision

Right now our character dies when he collides with an enemy. Usually you don't want that... it's better to have a small life bar and give the player a few chances before dying. In our SpritePlayer we can easily declare a new var life initialized with 3

UINT8 life;

void START() {
	life = 3;
}

And then when the player collides with an enemy substract one unit and kill him when reaching zero

void UPDATE() {
	...

	SPRITEMANAGER_ITERATE(i, spr) {
		if (spr->type == SpriteEnemy) {
			if (CheckCollision(THIS, spr)) {
				PlayFx(CHANNEL_1, 10, 0x4f, 0xc7, 0xf3, 0x73, 0x86);

				SpriteManagerRemove(i);
                life --;
				if (!life) {
					SetState(StateGame);
				}
			}
		}
	}
}

Our users will be thankfull now but there is still something missing. It's hard to know how much life does the player still have at some point. We can easily create a HUD at the bottom of the screen with a new gbm and gbr files.

First create hud_tiles.gbr file with the different tiles (an empty one, a hearth and an empty hearth) like this enter image description here

And then you can compose hud.gbm for the HUD like this enter image description here

To load this HUD into the game you need to import the map and call INIT_HUD on StateGame.c

IMPORT_MAP(hud);
...

void START() {
    ...
	INIT_HUD(hud);
}

This will automatically place the window based on the map height

Now we need to Update the HUD whenever we lost one life unit. We can add the function UpdateHUD to our SpritePlayer.c and call it from UPDATE when the player gets hit

#include "Scroll.h"

...

//Declare it above the UPDATE method since it's going to be called from there
void UpdateHudLife() {
	for (UINT8 i = 0; i < 3; ++i)
		UPDATE_HUD_TILE(16 + i, 0, i < life ? 1 : 2);
}

...
void UPDATE() {
    ...

    SPRITEMANAGER_ITERATE(i, spr) {
		if (spr->type == SpriteEnemy) {
			if (CheckCollision(THIS, spr)) {
				PlayFx(CHANNEL_1, 10, 0x4f, 0xc7, 0xf3, 0x73, 0x86);

				SpriteManagerRemove(i);
				life --;
				UpdateHudLife();
				if (!life) {
					SetState(StateGame);
				}
			}
		}
	}
}

Our hud will look like this

enter image description here

Clone this wiki locally