Part 4 — Enemies, lives and a game-over screen
Danger, a way to lose, and a second scene that lets the player try again.
15 min readCollecting coins is pleasant but not tense. A game needs a way to lose.
Make an enemy
- Press ✨, generator
creature, nameenemy. - Options:
{ "palette": "slime", "width": 32, "height": 32 }. - Add it and place one on a platform.
- Rename it
Enemyand tag itenemy. - Give it dynamic physics so it is affected by gravity.
Make it patrol
- With the enemy selected, add the behaviour
patrol. - Set distance to
180and speed to60.
It now walks back and forth around where you placed it. Slow is usually better than fast: a slow enemy is an obstacle to time, a fast one is a coin flip.
Make it dangerous
- Add the behaviour
damageOnTouchto the enemy. - Set amount to
1. - Set invulnerableMs to
1000. - Set variable to
lives.
Add the lives variable
- Open the Assets tab and find Variables.
- Add one called
lives, typenumber, value3. - While you are there add
best, typenumber, value0, and tick Persist.
A persisted variable is saved to the player's device and restored on load. That is how a high score survives a reload, and it keeps working in an exported game with no server involved.
Add LIVES {lives} to your HUD, either in the same text entity
or a second one.
A game-over scene
- In the Scenes panel press +.
- Name it
Game Overand set its Type tomenu. - Add a
bitmapTextentity on the UI layer at 640, 260 with the textGAME OVERand a font size around64. - Add a second one at 640, 360 with the behaviour
bindTextand the templateSCORE {score} BEST {best}. - Add a third at 640, 480 reading
PRESS SPACE TO PLAY AGAIN, and give it the behaviourpulseso it breathes.
Wire the loss
Back on your main scene's graph, add this alongside the coin rule:
On Variable Changed (lives)
└─ If lives <= 0
true ─→ Record Best score into best
└─ Go To Scene Game Over
- Drag in On Variable Changed and set
Variable to
lives. - Drag in If and set its expression to
lives <= 0. - Wire the event to the If.
- Drag in Record Best. Set Current to
scoreand Best tobest. - Wire the If's true pin to Record Best.
- Drag in Go To Scene, choose
Game Over, and set a delay of600so the death registers. - Wire Record Best to Go To Scene.
Let them try again
Select the Game Over scene, switch to Logic, and make a graph for it:
On Input (jump, pressed)
└─ Set Variable score = 0
└─ Set Variable lives = 3
└─ Go To Scene (your main scene)
On Input uses the mapped action jump rather than the
Space key directly, which means it also works from the on-screen joystick
and survives any rebinding.
Play it
Collect coins, then walk into the enemy three times. You should lose a life per touch — not sixty — see the game-over screen with your score, and be able to restart with Space.