Coins and bats
A game needs a goal and a danger. Here the goal is coins, one at a time and each in a new place, and the danger is bats that keep coming and chase the player. Three bites, and the game is over.
Who collides with whom#
Every object collides with every other unless it is told otherwise, which is right until there
are two kinds of thing that should not notice each other. A bat flying over a coin must not pick
it up, and the game has to be able to say "bats hurt the player" without an if in
every collision. That is what collision layers are for. Give each kind of thing one bit, in a new
header beside the player's:
#pragma once
// Who collides with whom: one bit for each kind of thing in the game.
namespace layer {
constexpr unsigned PLAYER = 1u << 0;
constexpr unsigned COIN = 1u << 1;
constexpr unsigned BAT = 1u << 2;
} // namespace layerEach object has two of these numbers:
collision_layer is what it is, and
collision_mask is what it collides
with. Two objects touch when either one's mask has the other's layer in it. The player is on the
player's layer and collides with coins and bats; the rest of its file is as it was:
#include "player.h"
#include "layers.h"
#include <rmp/behavior.h>
#include <rmp/input.h>
#include <rmp/math.h>
namespace {
constexpr float SPEED = 260; // design units per second
} // namespace
void Player::_ready() {
// A white box until it has a picture.
shape = rmp::rect({ 40, 40 });
shape.color = RAYWHITE;
collision_layer = layer::PLAYER;
collision_mask = layer::COIN | layer::BAT;
// Eight directions, from the keyboard, a d-pad or a stick.
add<rmp::behavior::TopDown>({ .speed = SPEED });
}
void Player::_update(float /*delta*/) {
// The mouse held down, or a finger on the screen: run towards it. Not when
// the pointer is on a button, which is the interface's and not the game's.
if (rmp::input::pointer_down() && !rmp::input::consumed_pointer()) {
const Vector2 to = rmp::input::pointer() - position;
if (Vector2Length(to) > 8) velocity = Vector2Normalize(to) * SPEED;
}
}The coins and the bats each have the player's bit in their mask and nothing else, so a bat and a coin never touch, and neither do two bats. The Collision chapter of the manual has the rest: solid objects that push each other apart, and the edges of the world.
The game scene#
The game scene gets three things to do, each in a function of its own: make a coin, make a bat, and end the game. Replace both files:
#pragma once
// The game: the rabbit, the coins and the bats, in an arena the size of the
// design resolution.
#include <rmp/scene.h>
class GameScene : public rmp::Scene {
public:
void _ready() override;
void _update(float delta) override;
void _draw() override;
private:
void spawn_coin();
void spawn_bat();
void caught();
rmp::Handle<rmp::Object> _player; // kept across frames, so a handle
int _coins = 0;
float _next_bat = 1; // seconds until the next bat comes
};#include "game.h"
#include "../objects/layers.h"
#include "../objects/player.h"
#include "game_over.h"
#include "main_menu.h"
#include <rmp/behavior.h>
#include <rmp/input.h>
#include <rmp/random.h>
#include <rmp/ui.h>
#include <string>
namespace {
// The arena is the design resolution: [window] width and height in the .toml.
constexpr Rectangle ARENA{ 0, 0, RMP_WINDOW_WIDTH, RMP_WINDOW_HEIGHT };
constexpr float SECONDS_PER_BAT = 4;
} // namespace
void GameScene::_ready() {
background = Color{ 52, 92, 60, 255 }; // grass
// P, Escape, or the gamepad's Start button.
rmp::input::action("pause", KEY_P, KEY_ESCAPE, GAMEPAD_BUTTON_MIDDLE_RIGHT);
auto &player = spawn<Player>({
.position = { ARENA.width / 2, ARENA.height / 2 },
.edges = rmp::Edge::CLAMP,
.bounds = ARENA,
});
player.add<rmp::behavior::Health>({
.hp = 3,
.destroy_on_death = false, // it stays on screen, under the game over
.on_death = [this](rmp::Object &) { caught(); },
.hurt_by = layer::BAT,
});
_player = player.handle();
spawn_coin();
}
void GameScene::_update(float delta) {
// There is no pause menu yet, so for now "pause" goes back to the menu.
if (rmp::input::just_pressed("pause")) rmp::Scene::change<MainMenuScene>();
_next_bat -= delta;
if (_next_bat <= 0) {
spawn_bat();
_next_bat = SECONDS_PER_BAT;
}
}
void GameScene::_draw() {
const int lives = _player->get<rmp::behavior::Health>()->hp;
rmp::ui::begin({ .placement = rmp::ui::Align::TOP_LEFT });
rmp::ui::row({ .gap = 24 }, [&] {
rmp::ui::text("Coins " + std::to_string(_coins));
rmp::ui::text("Lives " + std::to_string(lives));
});
rmp::ui::end();
}
void GameScene::spawn_coin() {
// Anywhere in the arena, clear of its edges and of the score at the top.
const Vector2 at{ rmp::random::range(40.0f, ARENA.width - 40),
rmp::random::range(80.0f, ARENA.height - 40) };
auto &coin = spawn({ .position = at, .shape = rmp::circle(10) });
coin.shape.color = GOLD;
coin.collision_layer = layer::COIN;
coin.collision_mask = layer::PLAYER;
coin.on_collision([this](rmp::Object &self, rmp::Object &) {
self.destroy();
++_coins;
spawn_coin();
});
}
void GameScene::spawn_bat() {
// From just outside the arena, above it or below it.
const Vector2 at{ rmp::random::range(0.0f, ARENA.width),
rmp::random::chance(0.5f) ? -40.0f : ARENA.height + 40 };
auto &bat = spawn({ .position = at, .shape = rmp::circle(16) });
bat.shape.color = Color{ 90, 60, 120, 255 };
bat.collision_layer = layer::BAT;
bat.collision_mask = layer::PLAYER;
// Each one a little faster or slower, so that they do not fly as one.
bat.add<rmp::behavior::Follow>({
.target = _player,
.speed = rmp::random::range(70.0f, 120.0f),
});
}
void GameScene::caught() { rmp::Scene::push<GameOverScene>(_coins); }Coins#
A coin needs no class of its own: it is a plain rmp::Object,
which is what spawn() makes when it is not given
a type. Its shape is a gold circle, made with rmp::circle(),
and it goes somewhere random in the arena:
rmp::random::range() is a number between two
others, from a generator the framework seeds from the clock when the game starts.
spawn() returns a reference to the new object, good for the rest of the frame,
which is all spawn_coin() needs it for. What the coin does when it is touched is a
function handed to it with on_collision(),
which runs when the coin touches something its layers allow, and that can only be the player:
self.destroy()takes the coin out. It stops being drawn and touched at once, and its memory goes when the frame ends, so nothing still running in this frame is left holding a dangling reference._coins++counts it. The lambda capturesthis, the scene, which owns the coin and therefore outlives it.spawn_coin()puts the next one somewhere else.
The two kinds of name are the framework's rule for who calls whom: _collision(),
with an underscore, would be a hook you override in a class of your own; on_collision()
takes a function, for when a class would be more than the job needs.
Bats#
A bat starts just outside the arena, above it or below it, which
rmp::random::chance(0.5f) decides. It chases
the player with another behavior from the catalogue,
rmp::behavior::Follow, at a speed of its
own so that the bats spread out instead of flying as one. The first comes after a second and
then one every four: _update() counts _next_bat down by
delta, the seconds since the last frame, and makes a bat when it reaches zero.
Follow is given the player as a handle, an
rmp::Handle made by
player.handle(), and not as a reference, and
the scene keeps one in _player the same way. A reference is good for the frame
it was got in: a destroyed object's memory goes when that frame ends, and a reference kept past
it points at nothing. A handle knows when its object is gone, and reads as empty from then on.
Lives#
The player gets a second behavior, rmp::behavior::Health,
and it is the whole of being hurt. The scene adds it, and not the player's own file, because what
a death means is the game's business: here, it ends the game.
.hp = 3is three lives..hurt_by = layer::BATsays what costs one: touching anything on the bats' layer.- After a bite the
player cannot be bitten again for 0.6 seconds,
Health's default, and blinks while that lasts. Each bite that lands starts the wait again, so a bat sitting on the rabbit costs a life every 0.6 seconds and not sixty a second: three lives last a little over a second. .on_deathruns once, when the last life goes, and callscaught()..destroy_on_death = falseleaves the rabbit on screen for the game over to be drawn over.
The fields are written in the order Health declares them, which C++20 requires of
designated initialisers.
The score#
_draw() puts the coins and the lives in the top-left corner, with
rmp::ui again: begin() with .placement set to
rmp::ui::Align::TOP_LEFT, and a
row to put the two side by side. A container takes
its contents as a lambda, so there is no closing call to forget. The strings are temporaries, and
that is safe: text() copies what it is given.
The lives are read from the player's Health through the handle, with
get<rmp::behavior::Health>(). The scene
draws its interface after its objects, so the score is always on top of the game.
Game over#
When the last life goes, the game does not end: a new scene is put on top of it. Two new files
in src/scenes/:
#pragma once
// Pushed on top of the game when the rabbit is caught. The game stays on
// screen, frozen, underneath.
#include <rmp/scene.h>
class GameOverScene : public rmp::Scene {
public:
explicit GameOverScene(int coins) : _coins(coins) {}
void _draw() override;
private:
int _coins;
};#include "game_over.h"
#include "game.h"
#include "main_menu.h"
#include <rmp/ui.h>
#include <string>
void GameOverScene::_draw() {
// A veil over the game, which has already drawn this frame.
DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), Color{ 0, 0, 0, 150 });
rmp::ui::begin();
rmp::ui::text("Caught!", { .size = rmp::ui::Size::LARGE });
rmp::ui::text(std::to_string(_coins) + " coins");
if (rmp::ui::button("Play again", { .style = rmp::ui::Variant::PRIMARY })) {
rmp::Scene::change<GameScene>();
}
if (rmp::ui::button("Menu")) rmp::Scene::change<MainMenuScene>();
rmp::ui::end();
}rmp::Scene::push<GameOverScene>(_coins)
puts it on top of the game, and the arguments go to its constructor, which is how the score gets
there. A scene pushed on top of another freezes it: the game below is still drawn, but nothing in
it moves and it hears no input. Nothing in the game scene says "stop": it is simply not updated
while something is on top of it.
The veil is plain raylib, DrawRectangle(), called in _draw(): the game
underneath has already drawn this frame, so the rectangle darkens it, and the menu is drawn over
both.
Play again is rmp::Scene::change<GameScene>(), which ends both scenes and
starts a new game from nothing: a new GameScene, with no coins, no bats and three
lives. Starting over needs no reset code, because everything that was the old game belonged to
the old scene.
Run it#
rmp runGather the gold coins and keep away from the purple bats. The third bite brings the game over up, frozen on the moment you were caught.
