Objects
An object is anything that lives in a scene: the player, an enemy, a bullet, a coin, a platform. They are all the same kind of thing. There is no tree, no hierarchy and no parent: what makes one object a paddle and another a ball is the data you put in it.
auto &ball = spawn({ .position = { 400, 225 }, .shape = rmp::circle(6) });
ball.velocity = { 320, 120 };
ball.edges = rmp::Edge::BOUNCE;That is a ball that bounces around the screen. Nothing else is needed: the scene moves it by its velocity every frame, bounces it off the edges, draws it, and frees it when the scene ends.
Spawning#
spawn() is a method of the
scene, which owns its objects. It makes the object, applies the
options you pass, puts it in the scene, calls its _ready(), and returns a reference to
it:
auto &bullet = spawn({ .position = muzzle, .size = { 4, 10 } });
bullet.velocity = aim * 900;The options are an rmp::ObjectOptions, and each
of its fields sets the object's field of the same name — except size, which is a shorter
way to write a rectangular shape. When both are given, shape wins:
{ .size = { 12, 12 }, .shape = rmp::circle(6) } is a circle.
| Option | Default | Sets |
|---|---|---|
position | { 0, 0 } | Where its centre is, in world units. |
size | { 0, 0 } | A rectangle of this size, when shape is not given. |
shape | none | What it draws and collides as. |
velocity | { 0, 0 } | World units per second. |
scale | { 1, 1 } | Multiplies the shape, the collider and the sprite. |
rotation | 0 | Degrees, as raylib counts them. |
layer | 0 | Draw order: higher draws on top. |
visible | true | false is not drawn and cannot be clicked, but is still updated and collided. |
edges | Edge::NONE | What happens at the edge of bounds. |
bounds | empty | The area edges applies to; empty means the map's, or the camera's view. |
They are written as designated initialisers, and C++20 requires those in the order the fields are declared, which is the order of this table. GCC and MSVC refuse any other order, and the framework turns Clang's warning about it into an error in the CMake build, in Android's native build and in the generated Xcode project, so an order that compiles on your machine compiles on every target. The order is the one they are naturally written in — where, how big, what it looks like, how it moves. Designated initialisers has the reasons.
The reference is good for the frame#
The reference spawn() returns stays valid for the whole frame it was returned in,
whatever else happens in that frame, because objects are only ever freed at the end of a frame.
Kept across frames, it can dangle. What to keep instead is a handle.
Order: options, _ready, then your lines#
The options are applied before _ready() runs, and _ready() runs before
spawn() returns. So inside _ready() the object already has its position and
everything else the options set, and anything you write on the returned reference — like the
bullet's velocity above — comes after _ready().
Its first _update() depends on where in the frame it was spawned, because the
scene's objects are updated in one pass, after the pointer and the scene's own
_update() and before collision:
| Spawned from | First _update() |
|---|---|
the scene's _update(), an on_click or an on_drag | this frame: the pass has not started |
an object's _update(), a behavior's | the next frame: the pass is under way |
a _collision() or an on_collision | the next frame: the pass is over |
Wherever it comes from, its _ready() runs at once, inside the spawn()
call.
Spawning from somewhere else#
Inside an object, scene() is the scene it lives
in, and spawning into it is scene().spawn(...). A
Spawner's on_spawn and a
map's object factory are handed the scene; the other
behavior callbacks, such as a Timer's on_timeout, are handed the object, and
reach the scene through its scene().
auto &spark = scene().spawn({ .position = position, .size = { 3, 3 } });
spark.velocity = { 0, -60 };It
is a reference, because a spawned object always has a scene. An object no scene spawned — a member,
a local — has none of its own: asking it is a mistake in the game, said once in the log, and the
answer is Scene::current(), the scene on top of
the stack.
Your own kind of object#
When an object needs code of its own, derive from rmp::Object
and spawn your type with spawn<T>():
class Coin : public rmp::Object {
public:
int value = 1;
void _ready() override {
shape = rmp::circle(8);
shape.color = GOLD;
}
void _collision(rmp::Object &other) override {
if (other.solid) destroy();
}
};
class Level : public rmp::Scene {
void _ready() override {
auto &coin = spawn<Coin>({ .position = { 300, 200 } });
coin.value = 5;
}
};The type only needs a default constructor. There is no constructor to forward and no
using Object::Object; to write, which is the usual toll of this pattern; what your type
needs goes in its fields, set on the reference spawn() returns, or in its
_ready(). A type that is not an object, or that cannot be default-constructed, is refused
with a sentence instead of a page of template errors:
spawn<Goblin>();include/rmp/scene.h:307:13: error: static assertion failed due to requirement 'std::is_default_constructible_v<Goblin>': spawn<T>() default-constructs T; give it a default constructor and put the rest in fields or in _ready()
307 | std::is_default_constructible_v<T>,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
snippet.cpp:1:1: note: in instantiation of function template specialization 'rmp::Scene::spawn<Goblin>' requested here
1 | spawn<Goblin>();
| ^An object cannot be copied: a copy would be a second object that believes it is in the scene.
The fields#
The fields are public, and reading and writing them directly is the point:
player.flip_x = player.velocity.x < 0; is the API. A getter and a setter in front of
every field would be ceremony between you and the object you touch most often in a day.
Where it is#
| Field | Default | Is |
|---|---|---|
position | { 0, 0 } | The centre of the object, in world units. |
velocity | { 0, 0 } | World units per second. The scene moves the object by it every frame. |
scale | { 1, 1 } | Multiplies the shape, the collider and the sprite. |
rotation | 0 | Degrees, as raylib counts them. It turns a sprite and a filled rectangle as they are drawn; an outlined rectangle is drawn unturned, and collision ignores it. |
mass | 1 | Read only by apply_force and apply_impulse. |
position is the centre, and that is the one place the framework
deliberately disagrees with raylib, which draws from the top-left corner. Rotating about the centre
is what nearly every 2D sprite wants, a shape stays symmetric around its position, and
Vector2Distance(a.position, b.position) means what it looks like. The corner would turn
every rotation and every distance check into a correction by half the size, by hand.
What it looks like#
| Field | Default | Is |
|---|---|---|
sprite | empty | A picture. When it has one, the sprite is what is drawn. |
shape | none | A rectangle or a circle, drawn when there is no sprite. |
flip_x, flip_y | false | Mirror the sprite left to right, or top to bottom. |
visible | true | false is not drawn and cannot be clicked, and is still updated and collided. |
layer | 0 | Draw order. A higher layer draws on top, and objects on the same layer draw in the order they were spawned. |
layer is only about drawing. Which objects collide is collision_layer and
collision_mask, a different pair of fields explained in
Collision.
How it behaves in the world#
| Field | Default | Is |
|---|---|---|
gravity_scale | 0 | How much of the scene's gravity applies to it. Nothing falls until it asks to. |
edges | Edge::NONE | What it does at the edge of its bounds: clamp, bounce, wrap, be destroyed, or leave. |
bounds | empty | The area edges applies to; empty is the map's bounds, or the camera's view without a map. |
collider | none | What it collides as, when that is not its shape or its picture. |
solid, immovable | false | Whether a contact pushes it apart from what it touches, and whether it is the one that gets pushed. |
collision_layer, collision_mask | 1 | Which layers it is on, and which it collides with. |
Gravity belongs to the scene, gravity,
{ 0, 980 } by default, because its direction and strength are a property of the world.
Each object then says how much of it applies to it, and the default of 0 is not negotiable: a
top-down game cannot have things falling over. A gravity nobody uses until they ask is what lets one
kind of object serve a platformer and a game seen from above.
The last four rows are the subject of Collision, and
edges and bounds are explained there too.
Shapes#
A rmp::Shape is a rectangle or a circle around the
object's centre, and there are two kinds and not five. Rectangle against rectangle, circle against
circle and circle against rectangle are the three cases collision can resolve honestly; a capsule
that was drawn as a capsule and collided as a box would be a lie in the API. To draw anything else,
override _draw() and use raylib.
shape = rmp::rect({ 14, 90 }); // a paddle
shape.color = RED;
shape = rmp::circle(7); // a ball
shape.filled = false; // the outline only
shape.offset = { 0, -4 }; // moved from the object's centre| Field | Default | Is |
|---|---|---|
kind | ShapeKind::NONE | RECTANGLE, CIRCLE, or nothing. rmp::rect() and rmp::circle() set it. |
size | { 0, 0 } | A rectangle's width and height. |
radius | 0 | A circle's radius. |
offset | { 0, 0 } | Where it sits relative to the object's centre. |
color | WHITE | The fill, or the outline when not filled. |
filled | true | false draws the outline only. |
thickness | 1 | A rectangle's outline width when not filled; a circle ignores it. |
A circle stays a circle when its object is scaled unevenly: the larger of the two scales applies to its radius, in the drawing, in the box it occupies and in collision alike, because this layer has no ellipses and the three must agree.
Sprites#
An object with a sprite draws the picture in place of
its shape. A sprite is either a loose texture or an Aseprite sheet, which brings its frames, its tags
and the time of each frame:
sprite.texture = rmp::assets::load_texture("ship.png");
sprite.sheet = rmp::assets::load_sheet("player.aseprite"); // a sheet wins over a texture
sprite.play("walk"); // "walk" is a tag in your file| Field | Default | Is |
|---|---|---|
texture | none | A picture with no animation. |
sheet | none | An .aseprite file; used instead of texture when both are set. |
source | empty | The part of the texture to draw; empty is all of it, or the sheet's current frame. |
origin | { 0.5, 0.5 } | Which point of the picture sits on the position, as a fraction of its size: the centre by default, { 0.5, 1 } for the feet. |
size | { 0, 0 } | The size to draw it at; zero is the picture's own size. |
tint | WHITE | Multiplies the picture's colours; white leaves them as they are. |
speed | 1 | Animation speed: 2 is twice as fast, 0 is frozen, -1 runs backwards. |
play(tag) starts a tag of the sheet, looping
unless you pass false. Calling it again with the tag already playing does not restart it,
so playing "walk" every frame while the player walks is correct. A tag that is not in the
sheet is reported once and changes nothing, rather than showing a blank frame or filling the log
sixty times a second. stop(), finished() and playing() do what
they say, and set_frame() with frame_index() is the way to drive the frames
yourself.
The animation advances while the object is updated, after it moves, and not while it is drawn — so an object in a scene that runs under a pause menu without being drawn still keeps time. Sprites has the whole of it.
The hooks#
An object of your own type overrides the hooks it needs; each has an empty default. As with
scenes, a method whose name starts with _ is one the framework calls on your type: you
override it and never call it.
| Hook | Runs |
|---|---|
_ready() | Once, when spawn() has put the object in its scene and applied the options. The place to load what it draws and to add its behaviors. |
_update(float delta) | Every frame it is alive, after its behaviors' _update and before it is moved by its velocity. |
_draw() | Every frame it is visible, after its sprite or shape and its behaviors have drawn, in world units: it is already inside the scene's camera. |
_collision(Object &other) | Once per frame for each object it touches, on both of them, whether or not either is solid. |
_end() | When it is destroyed: drop the loot, tell somebody. |
The frame of an object#
Every frame, in the scene's update, each living object goes through the same steps, in the order they were spawned:
- its behaviors'
_update, in the order they were added; - its own
_update(), so your code has the last word on what the frame leaves behind; - it moves: the forces applied to it and its share of gravity change its velocity, and the velocity moves it — and a solid object that is not immovable is stopped by the map's solid cells on the way;
- its
edgesrule is applied; - its sprite's animation advances;
- its behaviors'
_late_update, for those that correct where it ended up.
When every object of the scene has moved, the collision pass resolves and reports the contacts,
and then the camera follows. In the draw that comes later, objects are drawn in
layer order: each one's sprite or shape, then its behaviors' _draw, then its
own _draw().
Writing position in _update() is a teleport, not a move: the collision
pass sweeps the path an object travelled by its velocity, and does not treat a jump you made by hand
as a path across everything in between.
A frame with no time in it moves nothing by velocity. The first frame of a game has a delta of 0,
and a push applied in _ready() is kept for the first frame that can use it rather than
spent on that one.
Destroying an object#
destroy();destroy() takes effect at once and frees the
memory later. From the moment it is called the object is no longer updated, drawn, collided or
clicked; alive() is false, every handle to it is
empty, and its _end() runs, followed by its behaviors'. Its memory is released at the end
of the frame. Calling it twice is harmless.
The memory waits because most objects are destroyed from inside their own code: a coin in its
_collision(), a bullet when it leaves the screen, an enemy when its health runs out.
Freeing the object there would pull the floor out from under the code that is still running in it,
and under the other object of a collision, which is about to be told about the same contact. So the
other side of a contact always receives a valid object, whose alive() says whether it is
still in the game.
scene.destroy(object) is the same call, from
the scene's side. When a scene leaves the stack, its objects are destroyed after the scene's own
_end(), so a scene that tidies up can still walk what it spawned.
object_count() counts the live ones, and an
object destroyed earlier in the frame is already not counted.
Keeping an object: handles#
Within a frame, a reference. Between frames, a handle. An
rmp::Handle remembers an object and knows when it is gone:
rmp::Handle<rmp::Object> _player;
void _ready() override {
auto &player = spawn({ .position = { 100, 300 }, .size = { 20, 40 } });
_player = player.handle();
}
void _update(float) override {
if (_player) _player->velocity.x = 200; // only while the player exists
}handle() makes one. It converts to
true while the object is alive, -> and * reach it, and
get() returns it as an
rmp::Ref, empty once it is gone. It becomes empty the moment
destroy() is called, not when the memory goes. -> on an empty one is a
mistake in the game, said once in the log, and reaches a stand-in made for the purpose instead of
crashing: ask first, as the if above does. A default-constructed
handle is empty, and two handles compare equal when they point at the same object.
A handle is a slot number and a generation, so checking one costs an integer comparison — and it cannot come back to life. When the slot is reused for a new object the generation no longer matches, and the old handle stays empty instead of pointing at a stranger, which is the classic bug with stored indices.
handle<Goblin>() makes a typed one, whose -> reaches the
goblin's own fields without a cast. That conversion is not checked: get() is a
static_cast, not a dynamic_cast, because nothing in the framework uses
run-time type information and a handle resolved every frame should not pay for the lookup. Take a
typed handle only from an object that is that type; a type that is not an object at all is refused
when it compiles.
Callbacks#
When a subclass is more than you want, an object takes functions instead:
auto &coin = spawn({ .position = { 300, 200 }, .shape = rmp::circle(8) });
coin.on_collision([](rmp::Object &self, rmp::Object &other) {
if (other.solid) {
score += 10;
self.destroy();
}
});
coin.on_click([](rmp::Object &self) { self.scale = { 1.5f, 1.5f }; });| Callback | Is called | With |
|---|---|---|
on_collision | Every frame it touches another object, after the hooks. | Itself and the other object. |
on_click | When the pointer is pressed on it and released on it. | Itself. |
on_drag | Every frame the pointer moves while held, after being pressed on it. | Itself and how far the pointer moved since the last frame, in world units. |
This is the other half of the underscore rule: _name is yours and the framework calls
it, on_name is the framework's and you hand it a function. The two never collide, so an
object can override _collision() and carry an on_collision as well, and both
run. Setting a callback again replaces it; there is no list of them.
The pointer#
A click is a press and a release on the same object, which is what a click means on every
platform, and lets a player change their mind by dragging off before letting go. The mouse and a
finger are the same pointer. Only visible objects that have an on_click or an
on_drag are tested, against what they collide as, in world units through the scene's
camera — so a click lands on what is under it even while the camera shakes. When objects overlap, the
one drawn on top is the one pressed.
The rmp::ui gets first refusal: a press on a button drawn
over the world goes to the button, never to the object under it.
A drag is two lines, because on_drag hands over the movement in world units, the
units of position:
auto &card = spawn({ .position = { 200, 200 }, .size = { 60, 90 } });
card.on_drag([](rmp::Object &self, Vector2 moved) {
self.position.x += moved.x;
self.position.y += moved.y;
});The movement is where the pointer is in the world minus where it was, both taken through the scene's camera — not the pixels divided by the zoom — so the card stays under the finger at any zoom and under a rotated camera too.
rmp::Callback#
What a callback is stored in is an rmp::Callback, and
it is not std::function on purpose. It moves and never copies, so it accepts a lambda
that captures something only movable — a std::unique_ptr, for instance — which
std::function refuses. A function with the wrong arguments is a compile error that says
which signature was expected:
auto &button = spawn({ .size = { 80, 30 } });
button.on_click([](int times) { (void)times; });include/rmp/object.h:221:13: error: static assertion failed due to requirement 'std::is_invocable_v<(lambda at snippet.cpp:2:17) &, rmp::Object &>': the callback does not take the arguments this one is called with -- on_click is void(Object &), on_drag is void(Object &, Vector2), on_collision is void(Object &, Object &)
221 | std::is_invocable_v<Fn &, A...>,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
snippet.cpp:2:8: note: in instantiation of function template specialization 'rmp::Object::on_click<(lambda at snippet.cpp:2:17)>' requested here
2 | button.on_click([](int times) { (void)times; });
| ^
snippet.cpp:2:17: note: candidate function not viable: no known conversion from 'rmp::Object' to 'int' for 1st argument
2 | button.on_click([](int times) { (void)times; });
| ^ ~~~~~~~~~
snippet.cpp:2:17: note: conversion candidate of type 'void (*)(int)'The behaviors' on_ fields — a timer's on_timeout, a spawner's
on_spawn — are the same type, which is why a lambda can be written straight into the
braces that configure one.
Forces and impulses#
Most movement is written straight into velocity, which is what the behaviors do. When
a push is the right way to think about it, there are two kinds, and the difference between them is
the whole physics API: call it every frame and it is a force; call it once and it is an
impulse.
if (rmp::input::pressed("thrust")) apply_force({ 0, -600 }); // every frame it is held
apply_impulse({ 0, -450 }); // once: the jump starts| Call | Does | For |
|---|---|---|
apply_force(f) | Adds up with the other forces of the frame and is spent when the object moves: velocity += f / mass × delta. | Thrust, wind, a magnet — anything sustained. |
apply_impulse(i) | Changes the velocity at once: velocity += i / mass. | A jump, a hit, an explosion, a serve. |
Pong serves its ball with an impulse, because only the direction of the push matters to a ball that keeps its own speed.
Both exist because using the wrong one gives exactly the bug you would expect. A force applied
once barely moves anything, since it is multiplied by one frame's delta; an impulse
applied every frame goes twice as fast at 120 frames a second as at 60. A mass of 0 or
less counts as 1.
Gravity goes through the same path as a force — scene.gravity × gravity_scale is added
to the object's acceleration, without dividing by mass, the way gravity works — so an object with
gravity_scale = 1 that you push upwards does what it would do in the world.