# Objects

> rmp::Object is everything that lives in a scene: how one is spawned, the fields that place and draw it, its hooks, how it is destroyed, and how to keep hold of one across frames.

Source: https://omardev29.github.io/rmp-docs/manual/core/objects.html

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.

```cpp
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()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Scene.html#spawn) is a method of the [scene](https://omardev29.github.io/rmp-docs/manual/core/scenes.html), 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:

```cpp
auto &bullet = spawn({ .position = muzzle, .size = { 4, 10 } });
bullet.velocity = aim * 900;
```

The options are an [`rmp::ObjectOptions`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp.html#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](https://omardev29.github.io/rmp-docs/framework/why/designated-initialisers.html) 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](https://omardev29.github.io/rmp-docs/manual/core/objects.html#keeping-an-object-handles).

### 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()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#scene) is the scene it lives in, and spawning into it is `scene().spawn(...)`. A [`Spawner`'s `on_spawn`](https://omardev29.github.io/rmp-docs/reference/behaviors/Spawner.html#on_spawn) and a map's [object factory](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Tilemap.html#on_object) 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()`.

```cpp
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()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Scene.html#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`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html) and spawn your type with `spawn<T>()`:

```cpp
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:

Does not compile

```cpp
spawn<Goblin>();
```

The compiler refuses it, saying among other things: `give it a default constructor`

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`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#position) | `{ 0, 0 }` | The centre of the object, in world units. |
| [`velocity`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#velocity) | `{ 0, 0 }` | World units per second. The scene moves the object by it every frame. |
| [`scale`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#scale) | `{ 1, 1 }` | Multiplies the shape, the collider and the sprite. |
| [`rotation`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#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`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#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`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#sprite) | empty | A picture. When it has one, the sprite is what is drawn. |
| [`shape`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#shape) | none | A rectangle or a circle, drawn when there is no sprite. |
| [`flip_x`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#flip_x), [`flip_y`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#flip_y) | `false` | Mirror the sprite left to right, or top to bottom. |
| [`visible`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#visible) | `true` | `false` is not drawn and cannot be clicked, and is still updated and collided. |
| [`layer`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#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](https://omardev29.github.io/rmp-docs/manual/core/collision.html#layers-and-masks).

### How it behaves in the world

| Field | Default | Is |
|---|---|---|
| [`gravity_scale`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#gravity_scale) | `0` | How much of the scene's gravity applies to it. Nothing falls until it asks to. |
| [`edges`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#edges) | `Edge::NONE` | What it does at the edge of its bounds: clamp, bounce, wrap, be destroyed, or leave. |
| [`bounds`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#bounds) | empty | The area `edges` applies to; empty is the map's bounds, or the camera's view without a map. |
| [`collider`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#collider) | none | What it collides as, when that is not its shape or its picture. |
| [`solid`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#solid), [`immovable`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#immovable) | `false` | Whether a contact pushes it apart from what it touches, and whether it is the one that gets pushed. |
| [`collision_layer`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#collision_layer), [`collision_mask`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#collision_mask) | `1` | Which layers it is on, and which it collides with. |

Gravity belongs to the scene, [`gravity`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Scene.html#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](https://omardev29.github.io/rmp-docs/manual/core/collision.html), and `edges` and `bounds` are explained there too.

## Shapes

A [`rmp::Shape`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp.html#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.

```cpp
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()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp.html#rect) and [`rmp::circle()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp.html#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`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Sprite.html) 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:

```cpp
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)`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Sprite.html#play) 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](https://omardev29.github.io/rmp-docs/manual/modules/sprites.html) 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()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#_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)`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#_update) | Every frame it is alive, after its behaviors' `_update` and before it is moved by its velocity. |
| [`_draw()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#_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)`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#_collision) | Once per frame for each object it touches, on both of them, whether or not either is solid. |
| [`_end()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#_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:

1. its behaviors' `_update`, in the order they were added;
2. its own `_update()`, so your code has the last word on what the frame leaves behind;
3. 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;
4. its `edges` rule is applied;
5. its sprite's animation advances;
6. 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

```cpp
destroy();
```

[`destroy()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#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()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#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)`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Scene.html#destroy) 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()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Scene.html#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`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Handle.html) remembers an object and knows when it is gone:

```cpp
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()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#handle) makes one. It converts to `true` while the object is alive, `->` and `*` reach it, and [`get()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Handle.html#get) returns it as an [`rmp::Ref`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Ref.html), 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:

```cpp
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`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#on_collision) | Every frame it touches another object, after the hooks. | Itself and the other object. |
| [`on_click`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#on_click) | When the pointer is pressed on it and released on it. | Itself. |
| [`on_drag`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#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`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-ui.html) 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`:

```cpp
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`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Callback.html), 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:

Does not compile

```cpp
auto &button = spawn({ .size = { 80, 30 } });
button.on_click([](int times) { (void)times; });
```

The compiler refuses it, saying among other things: `the callback does not take the arguments this one is called with`

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.**

```cpp
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)`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#apply_force) | 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)`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#apply_impulse) | Changes the velocity at once: `velocity += i / mass`. | A jump, a hit, an explosion, a serve. |

[Pong](https://omardev29.github.io/rmp-docs/examples/games/01_pong.html) 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.
