Platformer
A level designed in LDtk. Three levels side by side in one world — a meadow, a desert, a snowfield — with Kenney's Pixel Platformer art. The player stands on the IntGrid and runs along it without catching on a seam, every coin, enemy, sign, door and platform is placed in the editor and arrives through on_object() with its fields (a patrol is an Array<Point>, a platform's destination a Point, the key names its door with an EntityRef), and walking off the edge of a level is neighbour_at() and a scene change. Music, effects, a shaking camera held to each level's edges, the run in an rmp::global, the best one in rmp::save. A window of another shape shows more of the world (Stretch::EXPAND, so the zoom is one constant), and the pause is a scene of its own — the level blurred behind overlay() — reached by Escape, P, a gamepad's Start or a HUD button for a finger, which Space, the jump, does not press. The art, the sounds and the first version of world.ldtk come out of tools/make_platformer_assets.py; the level is LDtk's from there on. One file per scene under src/scenes/, the things in the level under src/objects/.

Run it
From a clone of the framework:
rmp example 07_platformerKeys
Read from the code below: the actions it defines with rmp::input::action, the ones that come defined that it reads by name, and the keys it asks raylib about directly.
| Action | Keys |
|---|---|
jump | Space, W, ↑, gamepad right face down |
pause | Esc, P, gamepad middle right |
The code
Every file of examples/games/07_platformer, as it is at the commit this site documents (on GitHub).
src/main.cpp 51 lines
// ---------------------------------------------------------------------------
// examples/games/07_platformer -- a platformer whose levels are made in LDtk.
//
// Three levels side by side in one LDtk world -- a meadow, a desert and a
// snowfield -- with Kenney's Pixel Platformer art, walked through from left to
// right to the flag.
//
// What the framework does here, and therefore what is NOT in these files:
//
// rmp::Tilemap resources/world.ldtk, loaded by name. The scene draws it,
// and the player stands on its IntGrid `Solid` cells, and on
// any tile tagged `Solid` in the tileset (the meadow's crate).
// No collision code anywhere in the game.
// entities every coin, enemy, sign and door is placed in LDtk and
// arrives through map.on_object(): a patrol is an
// Array<Point> drawn in the editor, a platform's destination
// is a Point, the key names its door with an EntityRef, a
// sign's text is a String and its arrow an Enum.
// the world walking off the right edge of a level is
// map.neighbour_at() and a scene change; the player arrives
// at the same world position in the next one.
// Platformer the run, the jump, coyote time and the buffered jump.
// rmp::Camera follows with smoothing, stops at the level's edges
// (`limits = map.bounds()`), and shakes when you are hit.
// the stretch Stretch::EXPAND: a window of another shape shows more of
// the world rather than bars, so the zoom is one constant.
// rmp::ui the menus; the pause, the level blurred behind it by
// overlay(); and the HUD's Pause button for a finger, which
// Space -- the jump -- does not press.
// rmp::audio the music and the effects, by name. Asking for the track
// that is already playing does not restart it, so the music
// carries on from one level to the next.
// rmp::save the best run, kept between sessions.
// rmp::global the run itself -- lives, coins, the clock, what has been
// collected -- which has to outlive each level's scene.
//
// What is left is the game: what a coin is worth, what a stomp does, how long
// you are safe after a hit, and when you have won.
//
// Open resources/world.ldtk in LDtk 1.5 to change the levels; the game reads
// whatever it saves. Paint IntGrid `Solid` and the auto-layer rules draw the
// edges and corners; a level's `biome` (Grass, Sand or Snow) picks the terrain.
//
// Run it: `rmp example 07_platformer`.
// ---------------------------------------------------------------------------
#include <rmp/app.h>
#include "game.h"
RMP_GAME(game::TitleScene);include/game.h 161 lines
#pragma once
// ---------------------------------------------------------------------------
// What every file of the platformer shares: the collision layers, the run
// that outlives a level, the four scenes, and two helpers for the art.
// ---------------------------------------------------------------------------
#include <rmp/scene.h>
#include <raylib.h>
#include <string>
#include <string_view>
#include <vector>
namespace game {
inline constexpr float TILE = 18; // the grid of tiles.png and of every level
// How much of the world is on screen: twelve and a half rows of tiles at the
// [window] size, each pixel of the art two of the screen's. A window of another
// shape is rmp::app::Stretch::EXPAND's (TitleScene::_ready()): the view scaled
// to fit it, and MORE of the world showing the way the window is longer --
// never fewer rows than these. So the zoom is a constant, and nothing here
// reads the window's size.
inline constexpr float VIEW_HEIGHT = 225;
inline constexpr float ZOOM = RMP_WINDOW_HEIGHT / VIEW_HEIGHT;
// The tiles of tiles.png this game draws by hand, by index (20 to a row).
namespace tiles {
inline constexpr int KEY = 27;
inline constexpr int DOOR = 28;
inline constexpr int HEART = 44;
inline constexpr int HEART_EMPTY = 46;
inline constexpr int PLATFORM_LEFT = 48;
inline constexpr int PLATFORM_MIDDLE = 49;
inline constexpr int PLATFORM_RIGHT = 50;
inline constexpr int SPIKES = 68;
inline constexpr int SIGN = 86;
inline constexpr int SIGN_LEFT = 87;
inline constexpr int SIGN_RIGHT = 88;
inline constexpr int FLAG = 111; // and 112, the other half of its wave
inline constexpr int POLE = 131;
inline constexpr int COIN = 151;
inline constexpr int POINT = 157; // the decimal point
inline constexpr int TIMES = 158; // the x in "x 12"
inline constexpr int DIGIT_0 = 160; // to 169
} // namespace tiles
// Who notices whom. The player is on its own layer and everything that can
// touch it looks at that layer; nothing else needs to know about anything else.
namespace layer {
inline constexpr unsigned PLAYER = 1u << 0;
inline constexpr unsigned ENEMY = 1u << 1;
inline constexpr unsigned PICKUP = 1u << 2; // coins and keys
inline constexpr unsigned HAZARD = 1u << 3; // spikes
inline constexpr unsigned SOLID = 1u << 4; // moving platforms and doors
inline constexpr unsigned GOAL = 1u << 5;
inline constexpr unsigned SIGN = 1u << 6;
} // namespace layer
// THE RUN: what survives walking from one level into the next, and dying.
// A level is a scene, and a scene keeps nothing when it changes, so this is an
// rmp::global<Run>() -- and `gone` is what stops a coin collected in the
// Meadow from being there again when the player walks back to it.
struct Run {
int lives = 3;
int coins = 0;
float seconds = 0;
// The iids of the coins, keys, enemies and doors that are no more.
std::vector<std::string> gone;
// The iids of the doors the player holds a key for.
std::vector<std::string> keys;
};
Run &run();
void new_run();
bool contains(const std::vector<std::string> &list, std::string_view iid);
// The best run, as rmp::save keeps it: the most coins, and on a tie the
// faster time. Returns true when this one is a new best (and keeps it).
struct Best {
int coins = -1; // -1: nobody has finished yet
float seconds = 0;
};
Best best();
bool keep_if_best(int coins, float seconds);
// A tile of tiles.png by its index, drawn with its top-left corner at `at`.
void draw_tile(int index, Vector2 at, Color tint = WHITE, bool flip_x = false);
// The same tile `scale` times its size, for the HUD.
void draw_icon(int index, Vector2 at, float scale);
// A number in the sheet's own pixel digits, at `scale`, left to right from `at`.
void draw_number(int value, Vector2 at, float scale);
// "73.4" as tiles: the run clock.
void draw_seconds(float seconds, Vector2 at, float scale);
// ---------------------------------------------------------------------------
// The scenes
// ---------------------------------------------------------------------------
class TitleScene : public rmp::Scene {
public:
void _ready() override;
void _update(float delta) override;
void _draw() override;
private:
Best _best; // read once: a file, not something to ask sixty times a second
float _clock = 0;
};
// Where the player comes into a level from: nowhere (a new game, or a level
// started from its Player entity), or another level, at a world position --
// which is the same place in this one, because the levels share the world.
struct Entry {
bool carried = false;
Vector2 position{};
Vector2 velocity{};
};
class LevelScene : public rmp::Scene {
public:
explicit LevelScene(std::string level, Entry entry = {});
void _ready() override;
void _update(float delta) override;
void _draw() override;
// Called by the player when it is hit, and by this scene when it falls.
void lose_life();
void win();
private:
void respawn();
std::string _level;
Entry _entry;
Vector2 _start{}; // where a lost life puts the player back
rmp::Handle<rmp::Object> _player;
bool _over = false;
};
// Pushed on top of the level by the HUD's Pause button, Escape, P or a
// gamepad's Start: the level stays on screen, frozen and blurred, under it.
class PauseScene : public rmp::Scene {
public:
void _update(float delta) override;
void _draw() override;
};
// Pushed on top of the level when it ends: the level stays on screen, frozen,
// under it -- the scene stack's defaults, and no code here.
class EndScene : public rmp::Scene {
public:
EndScene(bool won, bool record);
void _draw() override;
private:
bool _won;
bool _record;
};
} // namespace gameinclude/objects.h 170 lines
#pragma once
// ---------------------------------------------------------------------------
// Everything that moves, hurts or can be picked up. Each one is placed in
// LDtk and built from its rmp::MapObject by a factory in src/scenes/level.cpp;
// what it does when the player touches it is its own _collision().
// ---------------------------------------------------------------------------
#include "game.h"
#include <rmp/object.h>
#include <raylib.h>
#include <string>
#include <vector>
namespace game {
class Player : public rmp::Object {
public:
void _ready() override;
void _update(float delta) override;
// A life, a knock away from `from_x`, and a moment of grace.
void hurt(float from_x);
// Off an enemy's head.
void bounce();
// Coming down onto the top of `other`: a stomp rather than a bump.
[[nodiscard]] bool falling_onto(const rmp::Object &other) const;
[[nodiscard]] bool hurting() const { return _knocked > 0; }
private:
float _grace = 0; // seconds of not being hurt again
float _knocked = 0; // seconds without control after a hit
int _jumps_heard = 0; // the Platformer's jump count when the sound last played
};
// What walks and flies. The same rules for both when the player touches one:
// from above it is stomped, from anywhere else it hurts.
class Enemy : public rmp::Object {
public:
std::string iid;
bool stompable = true;
void _collision(rmp::Object &other) override;
void _update(float delta) override;
protected:
virtual void patrol(float delta) = 0;
virtual const char *squashed_tag() const { return nullptr; }
private:
float _dying = -1; // seconds left of the squashed frame, -1 = alive
};
// Back and forth along its floor, between the x of its first and last patrol
// Points. The floor is where LDtk put it; the Points say where to turn.
class Walker : public Enemy {
public:
float speed = 40;
float left = 0;
float right = 0;
void _ready() override;
protected:
void patrol(float delta) override;
const char *squashed_tag() const override { return "squash"; }
private:
int _direction = -1;
};
// Along the whole route of its Points, there and back again.
class Bat : public Enemy {
public:
float speed = 50;
std::vector<Vector2> route;
void _ready() override;
protected:
void patrol(float delta) override;
private:
std::size_t _next = 1;
int _step = 1;
};
// From where LDtk put it to its `to` Point and back, carrying whoever stands
// on it. Solid and immovable: the player lands on it like on the floor.
class Platform : public rmp::Object {
public:
void _ready() override;
Vector2 from{};
Vector2 to{};
float speed = 40;
rmp::Handle<rmp::Object> rider; // the only one who can stand on it
void _update(float delta) override;
void _draw() override;
private:
void carry_rider(Vector2 before);
float _travelled = 0;
int _direction = 1;
float _waiting = 0; // at either end, long enough to get on or off
};
class Coin : public rmp::Object {
public:
void _ready() override;
std::string iid;
int value = 1;
void _collision(rmp::Object &other) override;
};
// A key opens the door its `opens` field names -- an EntityRef in LDtk, an
// iid here, compared against the door's own.
class Key : public rmp::Object {
public:
void _ready() override;
std::string iid;
std::string opens;
void _update(float delta) override;
void _draw() override;
void _collision(rmp::Object &other) override;
private:
float _clock = 0;
};
class Door : public rmp::Object {
public:
void _ready() override;
std::string iid;
void _draw() override;
void _collision(rmp::Object &other) override;
};
class Spikes : public rmp::Object {
public:
void _ready() override;
void _draw() override;
void _collision(rmp::Object &other) override;
};
// A wooden sign that says something while the player stands near it.
class Sign : public rmp::Object {
public:
void _ready() override;
std::string text;
int tile = tiles::SIGN;
void _update(float delta) override;
void _draw() override;
void _collision(rmp::Object &other) override;
private:
float _player_near = 0;
};
class Goal : public rmp::Object {
public:
void _ready() override;
void _update(float delta) override;
void _draw() override;
void _collision(rmp::Object &other) override;
private:
float _waving = 0; // seconds, the flag's own clock
};
} // namespace gamesrc/art.cpp 94 lines
// The run, the best run, and drawing from tiles.png.
#include "game.h"
#include <rmp/app.h>
#include <rmp/assets.h>
#include <rmp/save.h>
#include <algorithm>
#include <cmath>
#include <string>
namespace game {
namespace {
// A global and not a static texture: globals are destroyed while the window is
// still open, and a texture freed after the GPU context is gone is a crash.
struct Art {
rmp::Texture tiles = rmp::assets::load_texture("tiles.png");
};
Rectangle source_of(int index) {
const int columns = 20;
const int column = index % columns;
const int row = index / columns;
return Rectangle{ static_cast<float>(column) * TILE, static_cast<float>(row) * TILE,
TILE, TILE };
}
void draw_scaled_tile(int index, Vector2 at, float scale) {
const Texture2D &tiles = rmp::global<Art>().tiles;
DrawTexturePro(tiles, source_of(index),
Rectangle{ at.x, at.y, TILE * scale, TILE * scale }, Vector2{}, 0,
WHITE);
}
} // namespace
Run &run() { return rmp::global<Run>(); }
void new_run() { rmp::global<Run>() = Run{}; }
bool contains(const std::vector<std::string> &list, std::string_view iid) {
return std::find(list.begin(), list.end(), iid) != list.end();
}
Best best() {
rmp::Value saved;
rmp::save::read("platformer", saved);
return Best{ saved["coins"].as_int(-1), saved["seconds"].as_float(0) };
}
bool keep_if_best(int coins, float seconds) {
const Best before = best();
const bool better =
coins > before.coins || (coins == before.coins && seconds < before.seconds);
if (!better) return false;
rmp::Value v;
v["coins"] = coins;
v["seconds"] = seconds;
rmp::save::write("platformer", v);
return true;
}
void draw_icon(int index, Vector2 at, float scale) { draw_scaled_tile(index, at, scale); }
void draw_tile(int index, Vector2 at, Color tint, bool flip_x) {
const Texture2D &tiles = rmp::global<Art>().tiles;
Rectangle source = source_of(index);
if (flip_x) source.width = -source.width;
DrawTextureRec(tiles, source, at, tint);
}
// Each digit sits in the middle of its cell, so the advance (11 px) is
// narrower than the cell.
void draw_number(int value, Vector2 at, float scale) {
const std::string digits = std::to_string(std::max(0, value));
for (std::size_t i = 0; i < digits.size(); ++i) {
draw_scaled_tile(tiles::DIGIT_0 + (digits[i] - '0'),
{ at.x + (static_cast<float>(i) * 11 * scale), at.y }, scale);
}
}
void draw_seconds(float seconds, Vector2 at, float scale) {
const int tenths = static_cast<int>(std::floor(seconds * 10));
draw_number(tenths / 10, at, scale);
const float after =
static_cast<float>(std::to_string(tenths / 10).size()) * 11 * scale;
draw_scaled_tile(tiles::POINT, { at.x + after - (3 * scale), at.y }, scale);
draw_number(tenths % 10, { at.x + after + (5 * scale), at.y }, scale);
}
} // namespace gamesrc/objects/enemies.cpp 97 lines
// The walker and the bat, and the one rule they share: stomped from above,
// hurtful from anywhere else.
#include "game.h"
#include "objects.h"
#include <rmp/assets.h>
#include <rmp/audio.h>
#include <cmath>
namespace game {
void Enemy::_collision(rmp::Object &other) {
if (_dying >= 0 || (other.collision_layer & layer::PLAYER) == 0) return;
auto &player = static_cast<Player &>(other);
if (stompable && player.falling_onto(*this)) {
player.bounce();
rmp::audio::play("stomp");
run().gone.push_back(iid); // stomped for the rest of the run
// Out of every collision from now on, flattened for a moment, gone.
collision_layer = 0;
collision_mask = 0;
if (const char *tag = squashed_tag()) {
sprite.play(tag);
_dying = 0.4f;
} else {
flip_y = true; // what has no squashed frame falls out of the sky
gravity_scale = 1;
_dying = 1.0f;
}
return;
}
player.hurt(position.x);
}
void Enemy::_update(float delta) {
if (_dying >= 0) {
_dying -= delta;
if (_dying < 0) destroy();
return;
}
patrol(delta);
}
void Walker::_ready() {
sprite.sheet = rmp::assets::load_sheet("walker.aseprite");
sprite.play("walk");
collider = rmp::rect({ 14, 12 });
collider.offset = { 0, 6 }; // the beetle is the bottom half of its frame
collision_layer = layer::ENEMY;
collision_mask = layer::PLAYER;
}
void Walker::patrol(float delta) {
position.x += static_cast<float>(_direction) * speed * delta;
if (position.x <= left) {
position.x = left;
_direction = 1;
} else if (position.x >= right) {
position.x = right;
_direction = -1;
}
flip_x = _direction > 0;
}
void Bat::_ready() {
sprite.sheet = rmp::assets::load_sheet("bat.aseprite");
sprite.play("fly");
collider = rmp::rect({ 16, 12 });
collision_layer = layer::ENEMY;
collision_mask = layer::PLAYER;
}
void Bat::patrol(float delta) {
if (route.size() < 2) return;
const Vector2 target = route[_next];
const Vector2 to{ target.x - position.x, target.y - position.y };
const float distance = std::sqrt((to.x * to.x) + (to.y * to.y));
const float step = speed * delta;
if (distance <= step) {
position = target;
// There and back along the route: turn round at either end.
if (_next + 1 >= route.size()) _step = -1;
if (_next == 0) _step = 1;
if (_step > 0)
++_next;
else
--_next;
return;
}
position.x += to.x / distance * step;
position.y += to.y / distance * step;
if (std::fabs(to.x) > 0.5f) flip_x = to.x > 0;
}
} // namespace gamesrc/objects/player.cpp 99 lines
// The player. rmp::behavior::Platformer does the running and the jumping; this
// is what belongs to this game: being hit, the stomp, the sound of a jump and
// which animation to show.
#include "game.h"
#include "objects.h"
#include <rmp/assets.h>
#include <rmp/audio.h>
#include <rmp/behavior.h>
#include <rmp/input.h>
#include <cmath>
namespace game {
namespace {
// After a hit it cannot be hurt again for GRACE_SECONDS, and for KNOCK_SECONDS
// it is thrown back at KNOCK_SPEED, out of control.
constexpr float GRACE_SECONDS = 1.5f;
constexpr float KNOCK_SECONDS = 0.3f;
constexpr float KNOCK_SPEED = 110;
} // namespace
void Player::_ready() {
// Space, W or Up, or the gamepad's bottom button.
rmp::input::action("jump", KEY_SPACE, KEY_W, KEY_UP, GAMEPAD_BUTTON_RIGHT_FACE_DOWN);
sprite.sheet = rmp::assets::load_sheet("player.aseprite");
sprite.play("idle");
// The alien fills 20 px of its 24 px frame and stands on the bottom edge.
collider = rmp::rect({ 12, 20 });
collider.offset = { 0, 2 };
collision_layer = layer::PLAYER;
collision_mask = layer::ENEMY | layer::PICKUP | layer::HAZARD | layer::SOLID |
layer::GOAL | layer::SIGN;
layer = 5; // in front of everything else
add<rmp::behavior::Platformer>({
.speed = 130,
.acceleration = 1400,
.gravity = 1100,
.jump = 380, // 3.6 tiles high, 4.5 long at full speed
.jump_action = "jump",
});
}
void Player::_update(float delta) {
_grace -= delta;
_knocked -= delta;
// Thrown back after a hit: the knock wins over the controls for a moment.
if (_knocked > 0) velocity.x = velocity.x < 0 ? -KNOCK_SPEED : KNOCK_SPEED;
// Blinking while it cannot be hurt: shown for 0.12 s of every 0.2 s.
visible = _grace <= 0 || std::fmod(_grace, 0.2f) < 0.12f;
// The jump sound. Platformer counts the jumps it makes, so when the count
// goes up a jump has just happened -- a buffered or a coyote jump too.
const auto platformer = get<rmp::behavior::Platformer>();
if (platformer->ours.jumps_used > _jumps_heard)
rmp::audio::play("jump", { .volume = 0.6f });
_jumps_heard = platformer->ours.jumps_used;
if (hurting()) {
sprite.play("hurt");
} else if (!platformer->grounded()) {
sprite.play("jump");
} else if (std::fabs(velocity.x) > 10) {
sprite.play("walk");
} else {
sprite.play("idle");
}
// The art faces left: turn it round while it moves right.
if (velocity.x < -1) flip_x = false;
if (velocity.x > 1) flip_x = true;
}
void Player::hurt(float from_x) {
if (_grace > 0) return;
_grace = GRACE_SECONDS;
_knocked = KNOCK_SECONDS;
velocity = { position.x < from_x ? -KNOCK_SPEED : KNOCK_SPEED, -240 };
// The player only ever lives in a LevelScene.
static_cast<LevelScene &>(scene()).lose_life();
}
void Player::bounce() { velocity.y = -260; }
bool Player::falling_onto(const rmp::Object &other) const {
if (velocity.y <= 0) return false;
const Rectangle me = world_collider();
const Rectangle it = other.world_collider();
// The feet are in the top half of it. One frame of falling is a few pixels,
// so a stomp always lands there.
return me.y + me.height - it.y < it.height / 2;
}
} // namespace gamesrc/objects/things.cpp 228 lines
// What is placed in the level and is not alive: the moving platform, coins,
// the key and its door, spikes, signs and the flag.
#include "game.h"
#include "objects.h"
#include <rmp/assets.h>
#include <rmp/audio.h>
#include <cmath>
namespace game {
namespace {
bool is_player(const rmp::Object &other) {
return (other.collision_layer & layer::PLAYER) != 0;
}
// The top-left corner of an object's box, which is where tiles are drawn from.
Vector2 corner(const rmp::Object &object) {
const Rectangle box = object.world_collider();
return Vector2{ box.x, box.y };
}
} // namespace
// ---- the moving platform ----------------------------------------------------
void Platform::_ready() {
// Solid and immovable: the floor, as far as the player is concerned. The
// box is LDtk's, set by the factory.
solid = true;
immovable = true;
collision_layer = layer::SOLID;
collision_mask = layer::PLAYER;
}
void Platform::_update(float delta) {
const float dx = to.x - from.x;
const float dy = to.y - from.y;
const float length = std::sqrt((dx * dx) + (dy * dy));
if (length <= 0) return;
// There and back, with a pause at either end: a lift that turns round the
// instant it arrives is level with the ledge for one frame, and nobody can
// step off in one frame.
const Vector2 before = position;
if (_waiting > 0) {
_waiting -= delta;
} else {
_travelled += static_cast<float>(_direction) * speed * delta / length;
if (_travelled >= 1 || _travelled <= 0) {
_travelled = _travelled >= 1 ? 1.0f : 0.0f;
_direction = -_direction;
_waiting = 0.6f;
}
}
position = { from.x + (dx * _travelled), from.y + (dy * _travelled) };
carry_rider(before);
}
// Whoever stands on it goes with it. Moving the platform is not enough: the
// player on top would stay where it was, and the platform would slide out from
// under its feet.
void Platform::carry_rider(Vector2 before) {
const auto player = rider.get();
if (!player) return;
const Rectangle me = world_collider();
const Rectangle them = player->world_collider();
const float feet = them.y + them.height;
// Standing on it: feet on its top as it was before this frame's move,
// within a couple of pixels, and over it across.
const Rectangle was{ me.x - (position.x - before.x), me.y - (position.y - before.y),
me.width, me.height };
const bool on_top = std::fabs(feet - was.y) < 3 && them.x + them.width > was.x &&
them.x < was.x + was.width;
// Not riding: jumping off it (on its way up), or stepping off onto a ledge
// while the platform goes down -- taking it down too would put it inside
// the ledge.
const bool jumping = player->velocity.y < 0;
const bool going_down = position.y > before.y;
const bool on_a_ledge =
scene().map.solid_in(Rectangle{ them.x, feet, them.width, 1 });
if (!on_top || jumping || (going_down && on_a_ledge)) return;
// Across by as much as it moved, and up or down to stand exactly on its top.
player->position.x += position.x - before.x;
player->position.y += me.y - feet;
}
void Platform::_draw() {
const Vector2 at = corner(*this);
draw_tile(tiles::PLATFORM_LEFT, at);
draw_tile(tiles::PLATFORM_MIDDLE, { at.x + TILE, at.y });
draw_tile(tiles::PLATFORM_RIGHT, { at.x + (2 * TILE), at.y });
}
// ---- coins, the key, the door -------------------------------------------------
void Coin::_ready() {
sprite.sheet = rmp::assets::load_sheet("coin.aseprite");
sprite.play("spin");
collider = rmp::rect({ 10, 10 });
collision_layer = layer::PICKUP;
collision_mask = layer::PLAYER;
}
void Coin::_collision(rmp::Object &other) {
if (!alive() || !is_player(other)) return;
run().coins += value;
run().gone.push_back(iid);
rmp::audio::play("coin", { .volume = 0.7f });
destroy();
}
void Key::_ready() {
collider = rmp::rect({ 14, 10 });
collision_layer = layer::PICKUP;
collision_mask = layer::PLAYER;
}
void Key::_update(float delta) { _clock += delta; }
void Key::_draw() {
// It bobs up and down, so it reads as a thing to take.
const float bob = std::sin(_clock * 3) * 2;
draw_tile(tiles::KEY, { position.x - (TILE / 2), position.y - (TILE / 2) + bob });
}
void Key::_collision(rmp::Object &other) {
if (!alive() || !is_player(other)) return;
run().keys.push_back(opens);
run().gone.push_back(iid);
rmp::audio::play("key");
destroy();
}
void Door::_ready() {
solid = true;
immovable = true;
collision_layer = layer::SOLID;
collision_mask = layer::PLAYER;
}
void Door::_draw() {
const Vector2 at = corner(*this);
// One tile per row the door is tall.
for (int row = 0; static_cast<float>(row) * TILE + 1 < world_collider().height; ++row)
draw_tile(tiles::DOOR, { at.x, at.y + static_cast<float>(row) * TILE });
}
void Door::_collision(rmp::Object &other) {
if (!alive() || !is_player(other) || !contains(run().keys, iid)) return;
run().gone.push_back(iid);
rmp::audio::play("door");
destroy();
}
// ---- what hurts, what talks, what wins ----------------------------------------
void Spikes::_ready() {
collision_layer = layer::HAZARD;
collision_mask = layer::PLAYER;
}
void Spikes::_draw() {
// The collider is the points only, the bottom of the cells; the art fills
// the cells, so it is drawn from the cells' corner.
const float width = world_collider().width + 4;
const Vector2 at{ position.x - (width / 2), position.y - (TILE / 2) };
for (int column = 0; static_cast<float>(column) * TILE + 1 < width; ++column)
draw_tile(tiles::SPIKES, { at.x + static_cast<float>(column) * TILE, at.y });
}
void Spikes::_collision(rmp::Object &other) {
if (is_player(other)) static_cast<Player &>(other).hurt(position.x);
}
void Sign::_ready() {
// The box is where the player can read it from, not the sign itself.
collider = rmp::rect({ 54, 36 });
collision_layer = layer::SIGN;
collision_mask = layer::PLAYER;
}
void Sign::_update(float delta) { _player_near -= delta; }
void Sign::_draw() {
draw_tile(tile, { position.x - (TILE / 2), position.y - (TILE / 2) });
if (_player_near <= 0 || text.empty()) return;
// World space, in raylib's default font at its own 10 px: the camera's
// zoom makes it as chunky as the art.
const int width = MeasureText(text.c_str(), 10);
const auto x = static_cast<int>(position.x) - (width / 2);
const auto y = static_cast<int>(position.y) - 30;
DrawRectangle(x - 3, y - 2, width + 6, 14, Color{ 20, 24, 40, 200 });
DrawText(text.c_str(), x, y, 10, RAYWHITE);
}
void Sign::_collision(rmp::Object &other) {
if (is_player(other)) _player_near = 0.15f;
}
void Goal::_ready() {
collider = rmp::rect({ 10, 36 });
collision_layer = layer::GOAL;
collision_mask = layer::PLAYER;
}
// The flag's clock is the delta it is handed, not GetTime(): the game's time
// is what the scene stack says it is, which is what lets a paused scene stop
// waving and a scripted run (tests/e2e/) draw the same flag every time.
void Goal::_update(float delta) { _waving += delta; }
void Goal::_draw() {
// The pole in the bottom cell, the flag waving in the top one.
const Rectangle box = world_collider();
const float left = position.x - (TILE / 2);
draw_tile(tiles::POLE, { left, box.y + box.height - TILE });
const int wave = static_cast<int>(_waving * 4) % 2; // four times a second
draw_tile(tiles::FLAG + wave, { left, box.y + box.height - (2 * TILE) });
}
void Goal::_collision(rmp::Object &other) {
if (is_player(other)) static_cast<LevelScene &>(scene()).win();
}
} // namespace gamesrc/scenes/end.cpp 35 lines
// The end of a run, pushed on top of the level. The level underneath freezes
// and stays on screen, and stops hearing the keyboard -- the scene stack's
// defaults -- so this is only what it says and the two ways out, in an
// overlay: in front of the level, which it dims towards a night blue.
#include "game.h"
#include <rmp/audio.h>
#include <rmp/ui.h>
namespace game {
EndScene::EndScene(bool won, bool record) : _won(won), _record(record) {}
void EndScene::_draw() {
const Run &r = run();
rmp::ui::overlay({ .dim = 2 / 3.0f, .veil = Color{ 10, 12, 24, 255 } }, [&] {
rmp::ui::text(_won ? "You made it!" : "Game over",
{ .size = rmp::ui::Size::LARGE });
rmp::ui::text(TextFormat("%d coins in %.1f s", r.coins, r.seconds));
if (_won && _record)
rmp::ui::text("A new best!", { .color = rmp::ui::ColorRole::PRIMARY });
if (rmp::ui::button("Play again")) {
rmp::audio::play("select");
new_run();
rmp::Scene::change<LevelScene>("");
}
if (rmp::ui::button("Menu")) {
rmp::audio::play("select");
rmp::Scene::change<TitleScene>();
}
});
}
} // namespace gamesrc/scenes/level.cpp 214 lines
// ---------------------------------------------------------------------------
// One level of the world: load it, build what LDtk placed in it, and watch the
// player leave it -- into the next level, or off the bottom.
// ---------------------------------------------------------------------------
#include "game.h"
#include "objects.h"
#include <rmp/assets.h>
#include <rmp/audio.h>
#include <rmp/input.h>
#include <rmp/tilemap.h>
#include <rmp/ui.h>
#include <algorithm>
#include <utility>
namespace game {
namespace {
// A sign's picture: plain, or with the arrow LDtk's `arrow` Enum asks for.
int sign_tile(std::string_view arrow) {
if (arrow == "Left") return tiles::SIGN_LEFT;
if (arrow == "Right") return tiles::SIGN_RIGHT;
return tiles::SIGN;
}
} // namespace
LevelScene::LevelScene(std::string level, Entry entry)
: _level(std::move(level)), _entry(entry) {}
void LevelScene::_ready() {
// "" is the first level of the world, whatever LDtk calls it: rename or
// reorder the levels there and the game still starts at the beginning.
map = rmp::assets::load_map("world.ldtk", _level);
rmp::audio::music("music"); // already playing after a level change: not restarted
// Not Space, not Enter: those are the jump's and the menus'. Defining it
// again in the next level replaces it, never adds to it.
rmp::input::action("pause", KEY_ESCAPE, KEY_P, GAMEPAD_BUTTON_MIDDLE_RIGHT);
// The player first, so that what is built below can know who it is.
auto &player =
spawn<Player>({ .position = _entry.position, .velocity = _entry.velocity });
_player = player.handle();
// ---- what LDtk placed, one factory per entity -------------------------
//
// Anything already collected, stomped or opened in this run is in
// run().gone by its iid, and is simply not built again.
map.on_object("Player", [this](rmp::Scene &, const rmp::MapObject &o) {
if (!_entry.carried) _player->position = o.position;
});
map.on_object("Coin", [](rmp::Scene &s, const rmp::MapObject &o) {
if (contains(run().gone, o.iid)) return;
auto &coin = s.spawn<Coin>({ .position = o.position, .layer = 1 });
coin.iid = o.iid;
coin.value = o.property_int("value", 1);
});
map.on_object("Walker", [](rmp::Scene &s, const rmp::MapObject &o) {
if (contains(run().gone, o.iid)) return;
auto &walker = s.spawn<Walker>({ .position = o.position, .layer = 2 });
walker.iid = o.iid;
walker.speed = o.property_float("speed", 40);
walker.stompable = o.property_bool("stompable", true);
// The route is drawn in LDtk as Points; a walker keeps to its floor
// and only needs to know where to turn.
walker.left = walker.right = o.position.x;
for (int i = 0; i < o.property_count("patrol"); ++i) {
const float x = o.property_point("patrol", i).x;
walker.left = std::min(walker.left, x);
walker.right = std::max(walker.right, x);
}
});
map.on_object("Bat", [](rmp::Scene &s, const rmp::MapObject &o) {
if (contains(run().gone, o.iid)) return;
auto &bat = s.spawn<Bat>({ .position = o.position, .layer = 2 });
bat.iid = o.iid;
bat.speed = o.property_float("speed", 50);
for (int i = 0; i < o.property_count("patrol"); ++i) {
bat.route.push_back(o.property_point("patrol", i));
}
if (bat.route.empty()) bat.route.push_back(o.position);
});
map.on_object("MovingPlatform", [this](rmp::Scene &s, const rmp::MapObject &o) {
auto &platform = s.spawn<Platform>({ .position = o.position });
platform.collider = rmp::rect(o.size);
platform.from = o.position;
platform.to = o.property_point("to", o.position);
platform.speed = o.property_float("speed", 40);
platform.rider = _player;
});
map.on_object("Key", [](rmp::Scene &s, const rmp::MapObject &o) {
if (contains(run().gone, o.iid)) return;
auto &key = s.spawn<Key>({ .position = o.position, .layer = 1 });
key.iid = o.iid;
key.opens = o.property_string("opens");
});
map.on_object("Door", [](rmp::Scene &s, const rmp::MapObject &o) {
if (contains(run().gone, o.iid)) return;
auto &door = s.spawn<Door>({ .position = o.position });
door.collider = rmp::rect(o.size);
door.iid = o.iid;
});
map.on_object("Spikes", [](rmp::Scene &s, const rmp::MapObject &o) {
// Only the points hurt: the bottom eight pixels, a little in from the ends.
auto &spikes = s.spawn<Spikes>({ .position = o.position });
spikes.collider = rmp::rect({ o.size.x - 4, 8 });
spikes.collider.offset = { 0, (o.size.y / 2) - 4 };
});
map.on_object("Sign", [](rmp::Scene &s, const rmp::MapObject &o) {
auto &sign = s.spawn<Sign>({ .position = o.position, .layer = -1 });
sign.text = o.property_string("text");
sign.tile = sign_tile(o.property_string("arrow", "None"));
});
map.on_object("Goal", [](rmp::Scene &s, const rmp::MapObject &o) {
s.spawn<Goal>({ .position = o.position });
});
map.spawn_objects(*this);
_start = _player->position;
// ---- the camera ----------------------------------------------------------
camera.follow = _player;
camera.limits = map.bounds(); // the level's own rectangle, in the world
camera.smoothing = 10;
camera.zoom = ZOOM;
}
void LevelScene::_update(float delta) {
if (_over) return;
if (rmp::input::just_pressed("pause")) {
rmp::Scene::push<PauseScene>(); // this scene freezes under it, clock and all
return;
}
run().seconds += delta;
const auto player = _player.get();
if (!player) return;
// THE NEXT LEVEL. Out of this one and into another of the world: change
// to it, and arrive at the same world position going the same way.
const std::string_view next = map.neighbour_at(player->position);
if (!next.empty()) {
_over = true;
rmp::Scene::change<LevelScene>(std::string(next),
Entry{ true, player->position, player->velocity });
return;
}
// No level there. The sides of the world are walls; below is a fall.
const Rectangle b = map.bounds();
if (player->position.x < b.x || player->position.x > b.x + b.width) {
player->position.x = std::clamp(player->position.x, b.x, b.x + b.width);
player->velocity.x = 0;
}
if (player->position.y > b.y + b.height + 48) {
lose_life();
if (!_over) respawn();
}
}
void LevelScene::lose_life() {
if (_over) return;
Run &r = run();
--r.lives;
camera.shake(5, 0.35f);
rmp::audio::play("hurt");
if (r.lives > 0) return;
_over = true;
rmp::audio::music("lose", false);
rmp::Scene::push<EndScene>(false, false);
}
void LevelScene::respawn() {
if (const auto player = _player.get()) {
player->position = _start;
player->velocity = Vector2{};
}
}
void LevelScene::win() {
if (_over) return;
_over = true;
const bool record = keep_if_best(run().coins, run().seconds);
rmp::audio::music("win", false);
rmp::Scene::push<EndScene>(true, record);
}
// The HUD, in screen space: hearts, coins and the clock down the left, drawn
// from the same tiles as the world and at its scale -- however the window
// stretches it -- and the Pause button at the right.
void LevelScene::_draw() {
const float scale = camera.raylib().zoom; // screen pixels to a pixel of the art
for (int i = 0; i < 3; ++i) {
const int heart = i < run().lives ? tiles::HEART : tiles::HEART_EMPTY;
draw_icon(heart, { (6 + (static_cast<float>(i) * 17)) * scale, 4 * scale },
scale);
}
draw_icon(tiles::COIN, { 6 * scale, 22 * scale }, scale);
draw_icon(tiles::TIMES, { 20 * scale, 22 * scale }, scale);
draw_number(run().coins, { 32 * scale, 22 * scale }, scale);
draw_seconds(run().seconds, { 6 * scale, 40 * scale }, scale);
// A phone has no Escape: the one way to pause there is a finger. The
// interface knows this scene is being played -- the player reads Space,
// the arrows and the A button through rmp::input -- so the button takes
// no focus, and Space jumps rather than pressing it (FrameOptions'
// focus_first, in rmp/ui.h).
rmp::ui::begin({ .placement = rmp::ui::Align::TOP_RIGHT });
if (rmp::ui::button("Pause")) rmp::Scene::push<PauseScene>();
rmp::ui::end();
}
} // namespace gamesrc/scenes/pause.cpp 37 lines
// The pause, pushed on top of the level by the HUD's Pause button, Escape, P
// or a gamepad's Start. The level underneath freezes -- its clock too -- and
// stays on screen, and stops hearing the keyboard: the scene stack's defaults.
// What is here is the menu, and the look of it: the level blurred behind it,
// so the eye goes to Resume.
#include "game.h"
#include <rmp/audio.h>
#include <rmp/input.h>
#include <rmp/ui.h>
namespace game {
void PauseScene::_update(float /*delta*/) {
// The key that paused takes the pause away again.
if (rmp::input::just_pressed("pause")) rmp::Scene::pop();
}
void PauseScene::_draw() {
// A real blur wherever there is a GPU, a plain veil where there is none
// (raylib's software renderer); either way Resume has the focus, so Enter
// and the A button resume too.
rmp::ui::overlay({ .blur = 6, .dim = 0.4f }, [] {
rmp::ui::text("Paused", { .size = rmp::ui::Size::LARGE });
if (rmp::ui::button("Resume")) {
rmp::audio::play("select");
rmp::Scene::pop();
}
if (rmp::ui::button("Menu")) {
rmp::audio::play("select");
rmp::Scene::change<TitleScene>();
}
});
}
} // namespace gamesrc/scenes/title.cpp 65 lines
// The title: the first level behind a three-line menu, the camera drifting
// across it, and the best run so far.
#include "game.h"
#include <rmp/app.h>
#include <rmp/assets.h>
#include <rmp/audio.h>
#include <rmp/ui.h>
#include <cmath>
namespace game {
void TitleScene::_ready() {
// A window of another shape than the [window] size shows more of the
// world rather than bars or a cut: a level that scrolls anyway can show
// further. The first scene says it, for the whole game (rmp/app.h).
rmp::app::set_stretch(rmp::app::Stretch::EXPAND);
// The map with no factories: the level is drawn and nothing in it is
// built. A map costs a scene nothing it does not ask for.
map = rmp::assets::load_map("world.ldtk");
camera.limits = map.bounds();
camera.zoom = ZOOM;
rmp::audio::music("music");
_best = best();
}
void TitleScene::_update(float delta) {
_clock += delta;
const Rectangle b = map.bounds();
// Slowly from one end of the level to the other and back; `limits` keeps
// the view inside it, so the drift needs no arithmetic about the window.
camera.position = { b.x + (b.width / 2) + (std::sin(_clock * 0.15f) * b.width / 2),
b.y + (b.height / 2) };
}
void TitleScene::_draw() {
rmp::ui::begin();
// A dark panel, because the level behind is bright and the theme's text is
// light: the menu itself is the three lines inside it.
rmp::ui::panel({ .background = Color{ 20, 24, 40, 210 } }, [this] {
rmp::ui::text("Pixel Platformer",
{ .size = rmp::ui::Size::LARGE, .wrap = false });
if (_best.coins >= 0) {
rmp::ui::text(
TextFormat("Best: %d coins in %.1f s", _best.coins, _best.seconds),
{ .color = rmp::ui::ColorRole::MUTED, .wrap = false });
}
if (rmp::ui::button("Play")) {
rmp::audio::play("select");
new_run();
rmp::Scene::change<LevelScene>("");
}
// quit() does nothing on iOS, where Apple rejects an app that ends
// itself -- so the button is not there at all rather than dead.
#if !defined(PLATFORM_IOS)
if (rmp::ui::button("Quit")) rmp::app::quit();
#endif
});
rmp::ui::end();
}
} // namespace game