# Behaviors

> A behavior is a plain struct that makes an object move or act a certain way: adding, reading, pausing and removing them, the catalogue in rmp::behavior, configuring them from the editor, and writing your own.

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

A behavior is a piece of how an object acts — moving like a platformer character, bouncing like a Pong ball, disappearing after two seconds — that you add to an object instead of writing it again. Add one and the object moves like that game; change its fields and it moves differently, while the game runs.

```cpp
auto &player = spawn({ .position = { 200, 225 }, .size = { 26, 26 } });
player.add<rmp::behavior::TopDown>({ .speed = 240 });
```

## What a behavior is

A behavior is any struct with a function `void _update(rmp::Object &self, float delta)`. It inherits from nothing, has no virtual functions and is registered nowhere:

```cpp
struct Spin {
    float degrees_per_second = 90;

    void _update(rmp::Object &self, float delta) {
        self.rotation += degrees_per_second * delta;
    }
};
```

and it is added to an object with its fields written in braces:

```cpp
auto &coin = spawn({ .position = { 300, 200 }, .shape = rmp::circle(8) });
coin.add<Spin>({ .degrees_per_second = 180 });
```

That is the whole model, and leaving out a base class is not a matter of taste. A struct with virtual functions is not an aggregate in C++20, and then `{ .speed = 320 }` no longer compiles against it. The usual way round — a nested options struct and a constructor that takes it — turns every later read into `get<TopDown>()->options.speed`. Without one, the fields *are* the configuration.

And the behaviors in [`rmp::behavior`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-behavior.html) are structs exactly like that one. There is no extension API to learn, because there is nothing to extend: one of yours and one of the framework's are the same kind of thing, added, read and removed the same way.

## Adding, reading, removing

| Call | Does |
|---|---|
| [`add<B>({ ... })`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#add) | Attaches a `B` made from the braces, runs its `_ready` if it has one, and returns a reference to it. |
| [`get<B>()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#get) | The object's `B`, as an [`rmp::Ref`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Ref.html): empty when it has none. |
| [`has<B>()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#has) | Whether it has one. |
| [`remove<B>()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#remove) | Takes it off, running its `_end` if it has one. |
| [`enable<B>(on)`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#enable) | Pauses it with `false` and resumes it with `true`, keeping its fields and its `ours`. |
| [`enabled<B>()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#enabled) | Whether it has one and it is not paused. |

The fields stay live after the behavior is added. A power-up is one line:

```cpp
auto &player = spawn({ .size = { 26, 26 } });
player.add<rmp::behavior::TopDown>({ .speed = 240 });

if (auto walk = player.get<rmp::behavior::TopDown>()) walk->speed = 400;
```

`get()` answers with an optional reference, and the `if` is how you ask it: true when the object has a `TopDown`, and then `->` reaches it. Reaching into an empty one without asking is a mistake in the game: it is said once in the log, and the line writes to a stand-in instead of crashing. The reference `add()` returns and the one `get()` returns stay valid for as long as the behavior is attached: a behavior lives in memory of its own and never moves.

An object carries at most one behavior of each type. Adding a type it already has replaces the old one — its `_end` runs, then the new one's `_ready` — because two of the same is never what anybody means, and `get()` could only ever return one of them.

Behaviors run in the order they were added. One added from inside an `_update` gets its `_ready` at once and its first `_update` on the next frame. One removed from inside an `_update` — its own included, which is what a one-shot effect does — is taken off without costing any other behavior its turn in that frame.

A paused behavior gets no hooks — no `_update`, `_late_update`, `_draw` or `_collision` — until it is enabled again; it still gets its `_end` when it is removed or the object dies. It is how one behavior takes over from another for a while without either losing where it was: a `Chase` pauses the `Patrol` it interrupts, and a `StateMachine`'s states say which behaviors run while each is on. Pausing a behavior the object has not got does nothing, and adding one again replaces it with an enabled one.

```cpp
auto &guard = spawn({ .size = { 16, 16 } });
guard.add<rmp::behavior::Patrol>();
guard.enable<rmp::behavior::Patrol>(false);   // stands still, and remembers where it was going
if (!guard.enabled<rmp::behavior::Patrol>()) guard.enable<rmp::behavior::Patrol>();
```

When the object is destroyed, its own `_end()` runs first and then each behavior's `_end`, while everything the object owns is still there.

## The hooks a behavior can have

The framework finds a behavior's hooks when it is compiled, from their names and arguments, so a hook a behavior does not declare costs nothing at all.

| Hook | Runs |
|---|---|
| `_update(Object &self, float delta)` | Every frame, before the object's own `_update()` and before it moves, so it can set the velocity the move will use. |
| `_late_update(Object &self, float delta)` | Every frame, after the object has moved, been held to its edges and had its animation advanced. |
| `_ready(Object &self)` | Once, when it is added. |
| `_draw(Object &self)` | Every frame the object is drawn, after its sprite or shape and before its own `_draw()`, in world units. |
| `_collision(Object &self, Object &other)` | Once per frame for each object the object touches, right after the object's own `_collision()`. The walk stops after any behavior once either of the two is no longer alive: the behaviors after one that destroyed either object hear nothing, and if one was destroyed before the walk began, only the first behavior hears it. See [Collision](https://omardev29.github.io/rmp-docs/manual/core/collision.html#being-told). |
| `_end(Object &self)` | When it is removed, replaced, or the object is destroyed. |

A behavior needs `_update` or `_late_update`; every other hook is optional. `_late_update` exists because behaviors run before the move, which is what lets them write the velocity — so a behavior whose job is to correct where the object *ended up* needs a place after it. [`GridSnap`](https://omardev29.github.io/rmp-docs/reference/behaviors/GridSnap.html) is that: rounding the position the object had before it moved would round the wrong number.

A struct with neither, or one with virtual functions, is refused with a sentence that says why:

Does not compile

```cpp
auto &coin = spawn({ .size = { 8, 8 } });
coin.add<Score>({ .points = 10 });
```

The compiler refuses it, saying among other things: `a behavior needs`

## What a behavior keeps: ours

A behavior that has to remember something between frames — the time since a jump was pressed, whether it is standing on the ground — keeps it in one public member called `ours`:

```cpp
struct Blink {
    float every = 0.5f;   // seconds between switches

    void _update(rmp::Object &self, float delta) {
        ours.elapsed += delta;
        if (ours.elapsed >= every) {
            ours.elapsed -= every;
            self.visible = !self.visible;
        }
    }

    void _end(rmp::Object &self) { self.visible = true; }

    struct {
        float elapsed = 0;
    } ours;
};
```

It is public and not private because a struct with a private member is not an aggregate, and then `{ .every = 0.2f }` stops compiling — which is the whole design. The name is the fence: you can read what is in `ours`, and it is not yours to write. The catalogue follows the same rule, and where a value in it is worth reading it has a function that says so — [`Platformer::grounded()`](https://omardev29.github.io/rmp-docs/reference/behaviors/Platformer.html#grounded) reads `ours` for you. [`rmp::Sprite`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Sprite.html) keeps its animation state the same way.

## None of them chooses for you

A behavior contributes how something moves, not what the game intends. Which way the Pong ball is served is a rule of the game, so a `Ball` starts still; a `Projectile` travels the way you pushed it; a `Follow` chases the handle you give it; and the character behaviors read the input actions you name, or the standard ones when you name none — [the actions example](https://omardev29.github.io/rmp-docs/examples/input/01_actions.html) shows how one is defined.

The catalogue is the pieces a game would otherwise write again: moving like a character (`TopDown`, `Platformer`, `Runner`), moving on its own (`Ball`, `Projectile`, `Follow`, `Tween`, `Patrol`, `Orbit`, `Pathfind`, `Chase`), the places and things a level is made of (`Area`, `Hitbox`, `Collectible`, `Shooter`, `Spawner`, `Timer`, `Lifespan`, `Health`), and the rest (`GridSnap`, `Parallax`, `Animator`, `Draggable`, `StateMachine`). A Tetris piece, a formation of invaders and a paddle are not in it: each of those is a game with another name on it.

## The catalogue

Each one has a page in the reference with every field and its default. All of them come with `rmp/behavior.h`.

### TopDown

```cpp
auto &hero = spawn({ .size = { 16, 16 } });
hero.add<rmp::behavior::TopDown>({ .speed = 180, .eight_way = false });
```

[`TopDown`](https://omardev29.github.io/rmp-docs/reference/behaviors/TopDown.html) walks in eight directions, seen from above, at `speed` units per second, reading the standard `move_left`, `move_right`, `move_up` and `move_down` actions unless you name others. Going diagonally is not faster, because the [input](https://omardev29.github.io/rmp-docs/manual/modules/input.html) it reads is normalised. With `eight_way = false` it walks in four, and the direction pushed harder wins. `acceleration`, 0 by default, is instant; a value is how fast it reaches its speed, in units per second squared. `direction()` is the last way it moved, for aiming a weapon where the character looks.

It also picks the animation. With a sheet on the object's sprite, moving plays `walk_<direction>` when the sheet has such a tag and `walk` mirrored with `flip_x` when it does not, and standing still plays `idle`. So a sheet drawn in two, four or eight directions works with nothing configured. The names are yours — they are the tags in your file — and `idle`, `walk` and the direction suffixes are fields you can change. Without a sheet it only sets `flip_x`.

The mirroring assumes one thing about your art: **what has no direction of its own faces right**. `flip_x` is set while the object faces left, so a plain `walk`, `idle` and a sprite with no sheet must be drawn facing east to come out facing west. A tag with a direction suffix is drawn for that direction, so it plays unflipped: `walk_w` is your west-facing art, shown as you drew it.

### Platformer

```cpp
auto &hero = spawn({ .size = { 14, 22 } });
hero.add<rmp::behavior::Platformer>({ .speed = 200, .jump = 650, .air_jumps = 1 });
```

[`Platformer`](https://omardev29.github.io/rmp-docs/reference/behaviors/Platformer.html) runs left and right, falls, and jumps, reading `move_left`, `move_right` and `ui_accept` unless you name others. `jump` is the upward speed a jump starts with, `gravity` its own pull while in the air, and `air_jumps = 1` is a double jump. It makes the object solid when it is added, and applies its own gravity instead of the scene's, so a jump reaches the same height whatever the scene's `gravity` is.

That is why adding it sets the object's [`gravity_scale`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#gravity_scale) to 0. A heavier character is its own field, `get<rmp::behavior::Platformer>()->gravity = 3000`; setting `gravity_scale` again afterwards does not replace the behavior's gravity but adds the scene's on top of it, and the character falls with both.

Two fields separate a platformer that feels right from one that does not, and players never name either — they only notice when they are missing. `coyote_time` keeps a jump available for a moment after walking off a ledge, and `jump_buffer` remembers a jump pressed just before landing and fires it on landing. `grounded()` says whether it was standing on something at its last update: a solid object, or a solid cell of the map, just under its feet, while not moving up.

### Runner

```cpp
auto &runner = spawn({ .size = { 20, 36 } });
runner.add<rmp::behavior::Runner>({ .speed = 300, .accelerate = 8, .duck_action = "duck" });
```

[`Runner`](https://omardev29.github.io/rmp-docs/reference/behaviors/Runner.html) runs forward on its own, faster and faster: `speed` grows by `accelerate` every second up to `max_speed`, and it jumps on `ui_accept` unless you name another action. `distance()` is how far it has run — in an endless runner that is both the score and the clock the difficulty hangs off. `ducking()` says whether `duck_action` is held, and that is all ducking does here: a smaller collider or another animation is the game's to set. [The endless runner](https://omardev29.github.io/rmp-docs/examples/games/05_endless_runner.html) is one, with a `Spawner` measuring by its distance.

### Ball

```cpp
auto &ball = spawn({ .position = { 400, 225 }, .shape = rmp::circle(7) });
ball.add<rmp::behavior::Ball>({ .speed = 340 });
ball.apply_impulse({ 1, 0.35f });   // the serve, and it is the game's
```

[`Ball`](https://omardev29.github.io/rmp-docs/reference/behaviors/Ball.html) bounces off the edges of its bounds and off whatever it collides with, and keeps its pace: every frame its velocity is set back to `speed` in whatever direction it is going. That one rule is what makes the serve a single push — only its direction survives — and what makes `velocity = {}` a stable stop between points. Where it hits a paddle tilts the bounce, up to `max_bounce_deg` at the very end, which is half of why Pong feels like Pong. `speed_up` multiplies the speed on every bounce off something solid, and it compounds: Breakout's is 1.01, which makes the ball about twice its serve by the last of its fifty bricks; 1.03 makes it four times its serve by the thirtieth, faster than the paddle can follow. It sets the object to bounce at its edges and to be not solid itself, so it never pushes a paddle out of the way. [Pong](https://omardev29.github.io/rmp-docs/examples/games/01_pong.html) and [Breakout](https://omardev29.github.io/rmp-docs/examples/games/02_breakout.html) are both a `Ball`.

### Projectile

```cpp
auto &shot = spawn({ .position = muzzle, .size = { 4, 4 } });
shot.velocity = aim;
shot.add<rmp::behavior::Projectile>({ .speed = 600 });
```

[`Projectile`](https://omardev29.github.io/rmp-docs/reference/behaviors/Projectile.html) travels the way it was pushed, at `speed` — or at whatever velocity it was given, when `speed` is 0 — and is destroyed when it leaves its bounds and, with `destroy_on_hit`, when it touches anything it collides with. Which things those are is its layers' business. With `destroy_on_wall` it is destroyed too when its centre is in a solid cell of the map, which an object that is not `solid` otherwise passes through.

### Follow

```cpp
auto &bat = spawn({ .size = { 12, 8 } });
bat.add<rmp::behavior::Follow>({ .target = player_handle, .speed = 90, .stop_distance = 20 });
```

[`Follow`](https://omardev29.github.io/rmp-docs/reference/behaviors/Follow.html) chases a `target` at `speed`, and stops within `stop_distance` of it. The target is a handle and not a pointer because the thing being chased is exactly the thing most likely to die while being chased: when it is gone, the follower keeps its velocity, the way a homing missile whose target explodes keeps flying.

### Tween

```cpp
auto &lift = spawn({ .position = { 200, 300 }, .size = { 64, 12 } });
lift.add<rmp::behavior::Tween>({
    .property = rmp::behavior::Property::POSITION_X,
    .from = 200,
    .to = 500,
    .seconds = 3,
    .ping_pong = true,
});
```

[`Tween`](https://omardev29.github.io/rmp-docs/reference/behaviors/Tween.html) moves one property of its object from `from` to `to` over `seconds`, along an [`Ease`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-behavior.html#Ease): `LINEAR`, or `IN`, `OUT` and `IN_OUT`, the default, which start slow, end slow, or both. The [`Property`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-behavior.html#Property) is the x or y of the position, the x or y of the scale, the rotation in degrees, or the alpha of the shape's colour and the sprite's tint, from 0 to 255. `loop` starts again from `from`, `ping_pong` turns back at each end forever, and with neither it stops exactly on `to` — not a hair short of it, which on a platform is a gap — and `finished()` turns true. `restart()` runs it again.

A Tween writes its property every frame it runs, and an object carries one behavior of each type, so one object animates one property with it.

### GridSnap

```cpp
auto &piece = spawn({ .size = { 24, 24 } });
piece.add<rmp::behavior::GridSnap>({ .cell = { 24, 24 } });
```

[`GridSnap`](https://omardev29.github.io/rmp-docs/reference/behaviors/GridSnap.html) rounds the object's position to the nearest point of a grid of `cell` spacing, starting at `offset`, after everything else has moved it — so a puzzle piece never rests on half a pixel. A cell of 0 on one axis leaves that axis alone.

### Parallax

```cpp
auto &sky = spawn({ .layer = -10 });
sky.add<rmp::behavior::Parallax>({ .texture = "sky.png", .factor = 0.2f });
```

[`Parallax`](https://omardev29.github.io/rmp-docs/reference/behaviors/Parallax.html) draws a background strip that repeats sideways with no seam and scrolls at its own rate as the camera moves. It loads the `texture` by name from `resources/`. `factor` 0 is pinned to the screen, like a far sky; 1 stands still in the world, like the ground; in between, the smaller the farther away it looks. `speed` adds a drift of its own, for clouds; `y` is where the top of the strip sits; `tint` colours it. The object it is on needs no shape of its own, and its `layer` puts the strip behind or in front of the rest.

### Spawner

```cpp
auto &source = spawn({ .position = { 900, 380 } });
source.add<rmp::behavior::Spawner>({
    .every_seconds = 1.5f,
    .jitter = 0.4f,
    .max_alive = 5,
    .on_spawn = [](rmp::Scene &scene, Vector2 at) {
        auto &rock = scene.spawn({ .position = at, .size = { 30, 30 }, .velocity = { -200, 0 } });
        rock.add<rmp::behavior::Lifespan>({ .seconds = 6 });
    },
});
```

[`Spawner`](https://omardev29.github.io/rmp-docs/reference/behaviors/Spawner.html) calls `on_spawn` every `every_seconds`, or every `every_distance` units travelled, handing it the scene and the position the distance is measured at. Distance is not the same as time, and the difference is why this is not a timer: in an endless runner the speed climbs, so "every two seconds" spaces the obstacles further and further apart and the game gets easier the faster it goes. The distance is measured on the object `track` names, or on the spawner itself.

`jitter` moves each interval after the first by a random amount up to that much either way, drawn from [`rmp::random`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-random.html). Intervals are counted from when the last one was due, not from the frame it fired on, so they do not drift. `max_alive` caps how many of the objects it made are alive *at once* — everything `on_spawn` spawns counts — and `alive()` says how many that is now. It is a cap and not a quota: when one dies, another can be made. One spawner keeps track of at most [`rmp::behavior::MAX_SPAWNED`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-behavior.html#MAX_SPAWNED) objects, and a larger `max_alive` is reported once and held to that.

### Timer

```cpp
auto &cannon = spawn({ .position = { 100, 100 }, .size = { 20, 20 } });
cannon.add<rmp::behavior::Timer>({
    .seconds = 0.8f,
    .on_timeout = [](rmp::Object &self) { self.rotation += 45; },
});
```

[`Timer`](https://omardev29.github.io/rmp-docs/reference/behaviors/Timer.html) calls `on_timeout` every `seconds`, with the object it is on; with `repeat = false` it calls once and is spent. A frame longer than the interval calls it once for each interval the frame covered, so a countdown keeps time on a slow machine — up to a thousand calls in one frame, past which it drops the rest and says so once.

### Lifespan

```cpp
auto &spark = spawn({ .size = { 3, 3 } });
spark.add<rmp::behavior::Lifespan>({ .seconds = 0.5f });
```

[`Lifespan`](https://omardev29.github.io/rmp-docs/reference/behaviors/Lifespan.html) destroys its object after `seconds`: particles, bullets, a message that fades.

### Health

```cpp
auto &hero = spawn({ .size = { 26, 26 } });
hero.add<rmp::behavior::Health>({
    .hp = 5,
    .invulnerable_for = 0.8f,
    .destroy_on_death = false,
    .on_death = [](rmp::Object &) { TraceLog(LOG_INFO, "game over"); },
    .hurt_by = layer::ENEMY,
});
```

[`Health`](https://omardev29.github.io/rmp-docs/reference/behaviors/Health.html) is hit points, a window of invulnerability after each hit, and death. `damage()` takes points off and returns whether it landed — during the window it does not, which is what stops one spike costing three hearts in three frames — and the object blinks `blink_hz` times a second while the window is open. `on_damage` is told how much landed; `on_death` is called once when the points run out, even if two lethal hits land in the same frame, and then the object is destroyed unless `destroy_on_death` is off. `heal()` adds points up to `max_hp`, which is the starting `hp` unless set, and does nothing after death.

Nothing hurts by default: `hurt_by` names the [collision layers](https://omardev29.github.io/rmp-docs/manual/core/collision.html#layers-and-masks) whose touch costs `damage_on_hit` points, so contact damage is one field instead of an `if` at the top of every `_collision()`. A `Health` with nothing in `hurt_by` is a counter that only `damage()` reduces. An object that carries a [`Hitbox`](https://omardev29.github.io/rmp-docs/manual/core/behaviors.html#hitbox) is never counted by `hurt_by`: the Hitbox decides, so one touch never costs twice. [The top-down game](https://omardev29.github.io/rmp-docs/examples/games/04_top_down.html) gives its player a `TopDown` and a `Health` hurt by the enemies.

### Area

```cpp
auto &door = spawn({ .position = { 400, 200 }, .size = { 32, 48 } });
door.collision_layer = 0;
door.collision_mask = layer::PLAYER;
door.add<rmp::behavior::Area>({
    .on_enter = [](rmp::Object &, rmp::Object &who) { TraceLog(LOG_INFO, "welcome"); (void)who; },
    .on_exit = [](rmp::Object &, rmp::Object &) { TraceLog(LOG_INFO, "goodbye"); },
});
```

[`Area`](https://omardev29.github.io/rmp-docs/reference/behaviors/Area.html) is a region that says who comes and goes: a trigger, a door's sensor, a pit, a shop counter. It sees exactly what its object collides with — its collider and its [layers](https://omardev29.github.io/rmp-docs/manual/core/collision.html#layers-and-masks) — and whether the object is `solid` is the object's business (a trigger is not, the default). Each moment is told with the area and the other object:

| Callback | When |
|---|---|
| `on_enter` | The first frame the other touches it. |
| `on_stay` | Every frame after that it still does. |
| `on_exit` | The frame after the first one it no longer does. |
| `on_inside` | Its collider is wholly inside the area's, from a frame it was not. |
| `on_outside` | It is no longer wholly inside: part of it is out, or it left. A jump from wholly inside to gone is `on_outside` and then `on_exit`. |

`overlapping()` is who touched it in the last collision pass, as [handles](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Handle.html), and `contains(other)` asks about one object. An object destroyed while it touches the area leaves `overlapping()` and is told nothing: it is gone, and there is no object to hand over.

### Hitbox

```cpp
auto &spikes = spawn({ .position = { 300, 300 }, .size = { 32, 8 } });
spikes.collision_layer = layer::TRAP;
spikes.add<rmp::behavior::Hitbox>({ .damage = 1, .hits = layer::PLAYER, .knockback = 250 });
```

[`Hitbox`](https://omardev29.github.io/rmp-docs/reference/behaviors/Hitbox.html) is what hurts: a sword's swing, a spike, a bullet, an explosion. On touching an object with a `Health` on one of the layers it `hits`, it calls that Health's `damage()` — the invulnerable window, `on_damage` and the one death all apply — and pushes it away by `knockback` (an impulse, away from the hitbox). `destroy_on_hit` discards it after its first hit, landed or not, which is a bullet; `once_per_target` hits each object once at most, which is one swing of a sword; `on_hit` is told the hitbox and who it hurt, when the damage landed.

A Hitbox decides for itself, so a Health's `hurt_by` does not count an object that has one: one touch never costs twice. `hurt_by` is the quick way for plain contact damage; a Hitbox is the way when the damage, the push or the rule belongs to what hurts.

### Collectible

```cpp
auto &coin = spawn({ .position = { 200, 200 }, .shape = rmp::circle(5) });
coin.add<rmp::behavior::Collectible>({
    .collected_by = layer::PLAYER,
    .sound = "coin",
    .magnet = 40,
    .on_collect = [](rmp::Object &, rmp::Object &) { ++coins; },
});
```

[`Collectible`](https://omardev29.github.io/rmp-docs/reference/behaviors/Collectible.html) is a coin, a key, a heart. Touched by an object on a layer of `collected_by`, it calls `on_collect` once, plays `sound` through [`rmp::audio`](https://omardev29.github.io/rmp-docs/manual/modules/audio.html), stops colliding, and vanishes — it rises, grows and fades for `vanish_seconds` — before it is destroyed. Within `magnet` units of a collector it flies to it at `magnet_speed` first. What a pickup is worth is the game's: `on_collect` is where it counts, and there is no counter of the framework's to keep in step with yours. `collected()` says whether it has been picked up.

### Shooter

```cpp
auto &turret = spawn({ .position = { 400, 120 }, .size = { 16, 16 } });
turret.add<rmp::behavior::Shooter>({
    .automatic = true,
    .every = 1.2f,
    .target = player_handle,
    .range = 220,
    .speed = 180,
    .count = 3,
    .spread = 30,
});
```

[`Shooter`](https://omardev29.github.io/rmp-docs/reference/behaviors/Shooter.html) fires: while its `action` is held, on its own every `every` seconds with `automatic`, or at a `target` — and with a target, only within `range`. Without one it aims along `direction`, or the way the object faces when that is {0, 0}. A volley is `count` bullets spread over `spread` degrees (360 is all around, evenly), and `rotate_per_shot` turns the whole pattern after each volley, which is how a spiral is made. `fire()` fires now if `every` has passed, and `shots()` counts the volleys.

The bullet is a circle of `bullet_radius` in `bullet_color` with a `Hitbox` of `damage`, a `Projectile` that ends at a wall or a hit, and a `Lifespan` of `bullet_life`; it hits the layers of `hits`, or the shooter's own mask less its own layer. Or it is whatever `on_shoot` makes, handed the scene, where it leaves from and its velocity:

```cpp
auto &archer = spawn({ .size = { 16, 16 } });
archer.add<rmp::behavior::Shooter>({
    .action = "fire",
    .on_shoot = [](rmp::Scene &s, Vector2 at, Vector2 velocity) {
        auto &arrow = s.spawn({ .position = at, .size = { 10, 2 }, .velocity = velocity });
        arrow.add<rmp::behavior::Lifespan>({ .seconds = 1.5f });
    },
});
```

### Orbit

```cpp
for (int i = 0; i < 3; ++i) {
    auto &blade = spawn({ .size = { 6, 6 } });
    blade.add<rmp::behavior::Orbit>({ .centre = player_handle, .radius = 40,
                                      .degrees_per_second = 180,
                                      .face = rmp::behavior::Face::OUTWARD,
                                      .index = i, .of = 3 });
}
```

[`Orbit`](https://omardev29.github.io/rmp-docs/reference/behaviors/Orbit.html) circles a `centre` handle, or a `point` without one, at `radius`, turning `degrees_per_second` (negative the other way) from `angle`, where it is now. Several on one centre spread evenly with `index` and `of`, and `face` turns each to look at the centre or away from it. It runs after everything has moved, so the centre's movement this frame is already in.

### Animator

```cpp
auto &hero = spawn({ .size = { 16, 16 } });
hero.sprite.sheet = rmp::assets::load_sheet("hero.aseprite");
hero.add<rmp::behavior::Animator>({ .run = "walk" });
hero.get<rmp::behavior::Animator>()->rules.push_back(
    { .tag = "dash", .when = [](rmp::Object &) { return dashing; } });
```

[`Animator`](https://omardev29.github.io/rmp-docs/reference/behaviors/Animator.html) plays the tag that fits what the object is doing: `die` once its `Health` is dead (once, not looped), `hurt` while it is invulnerable after a hit, `jump` and `fall` in the air (with gravity), `run` while it moves faster than `moving_at` and `idle` while it does not — and with `flip` it sets `flip_x` while it moves left, so the art faces right. The names are fields: the tags of your .aseprite. A tag the sheet lacks is skipped for the next that fits, and without a sheet only `flip_x` is set. Its `rules` are asked first, in order: an [`AnimationRule`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-behavior.html#AnimationRule) is a `tag` and a `when`. `playing()` is the tag it chose last.

### Draggable

```cpp
auto &slot = spawn({ .position = { 500, 300 }, .size = { 40, 40 } });
slot.add<rmp::behavior::Area>();

auto &gem = spawn({ .position = { 200, 300 }, .shape = rmp::circle(8) });
gem.add<rmp::behavior::Draggable>({
    .on_drop = [](rmp::Object &, rmp::Object &) { TraceLog(LOG_INFO, "socketed"); },
});
```

[`Draggable`](https://omardev29.github.io/rmp-docs/reference/behaviors/Draggable.html) is picked up with the pointer and put down somewhere: an inventory, a puzzle piece, a card. It takes the object's `on_drag`. Let go over an object with an `Area` — on a layer of `drop_on`, and `accepts` saying yes — it is dropped there: `on_drop`, and put on its centre with `centre_on_drop`. Anywhere else, `on_reject`, and back where it was picked up with `return_if_rejected` — or it stays, snapped to `snap`, and with `throwable` keeps the pointer's speed and slides to a stop at `friction`. `bounds` keeps it inside a rectangle, `on_pick` is told the first time it moves, `held()` says whether the pointer has it, and `drop()` lets go of it as the pointer would. `accepts` is an [`rmp::Condition`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Condition.html): a callback that answers, and an empty one answers no.

### Patrol

```cpp
auto &guard = spawn({ .position = { 100, 100 }, .size = { 16, 16 } });
guard.add<rmp::behavior::Patrol>({
    .waypoints = { { 100, 100 }, { 300, 100 }, { 300, 220 } },
    .speed = 60,
    .wait = 0.5f,
    .ping_pong = true,
});
```

[`Patrol`](https://omardev29.github.io/rmp-docs/reference/behaviors/Patrol.html) goes from waypoint to waypoint — round in a loop, or back and forth with `ping_pong` — waiting `wait` seconds at each; `heading_for()` is the one it is going to. Waypoints are for what flies or walks top-down: it moves straight to each, on both axes. With no waypoints it walks the floor instead, left and right at `speed`, turning at a wall, at anything that stops it, and, with `turn_at_ledges`, before a drop — a platformer's goomba, with gravity the object's own. The way it goes sets `flip_x`, and its sheet plays `walk` and `idle` when it has them, unless the object has an `Animator`, which then chooses.

### Pathfind

```cpp
auto &rat = spawn({ .size = { 10, 10 } });
rat.add<rmp::behavior::Pathfind>({ .target = player_handle, .speed = 90, .clearance = 5 });
```

[`Pathfind`](https://omardev29.github.io/rmp-docs/reference/behaviors/Pathfind.html) walks to a `target`, or to a `goal` point without one, around the map's walls: it asks `rmp::find_path()` again every `repath_every` seconds while it walks and follows the way at `speed`, on both axes. With neither it leaves the velocity to whoever else moves the object. `path()` is the cells still ahead, the last one the goal; `arrived()` says it is there, or that there is no way. A `Chase` on the same object steers it.

[`rmp::find_path(map, from, to)`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp.html#find_path) is the search itself, for a game that wants the way without walking it: A* over the map's cells, around its solid ones, eight directions — or four, with `.diagonal = false` — and a diagonal step never cuts a solid cell's corner. `.clearance` keeps that far from every wall: half the walker's width. The answer is the centres of the cells to walk through, ending on `to` itself and without `from`; it is empty when there is no way, when either end is outside the map or in a wall, and for a map with no cells.

```cpp
const auto way = rmp::find_path(map, { 40, 40 }, { 400, 300 }, { .diagonal = false });
if (way.empty()) TraceLog(LOG_INFO, "walled in");
```

### Chase

```cpp
auto &hound = spawn({ .position = { 300, 200 }, .size = { 14, 14 } });
hound.add<rmp::behavior::Patrol>({ .waypoints = { { 300, 200 }, { 420, 200 } } });
hound.add<rmp::behavior::Pathfind>();
hound.add<rmp::behavior::Chase>({
    .target = player_handle,
    .speed = 110,
    .sight = 160,
    .fov = 120,
    .on_spot = [](rmp::Object &, rmp::Object &) { TraceLog(LOG_INFO, "there you are"); },
});
```

[`Chase`](https://omardev29.github.io/rmp-docs/reference/behaviors/Chase.html) sees a target and goes after it. It sees it within `sight` units (0 is any distance), inside a cone of `fov` degrees around the way it faces, and — with `line_of_sight` — when no solid map cell stands between them. While it chases, a `Patrol` on the same object is paused (with [`enable<Patrol>(false)`](https://omardev29.github.io/rmp-docs/manual/core/behaviors.html#enable)) and a `Pathfind`, when there is one, finds the way; without one it runs straight at the target, stopping within `stop_distance`. After `lose_after` seconds without seeing it, it gives up: `on_lose`, back to where it started with `return_home`, and the patrol resumes. `chasing()` and `sees()` say where it is.

### StateMachine

```cpp
auto &boss = spawn({ .size = { 32, 32 } });
boss.add<rmp::behavior::Pathfind>({ .target = player_handle });
boss.add<rmp::behavior::Shooter>({ .automatic = true, .count = 8, .spread = 360 });

rmp::behavior::StateMachine mind;
mind.states.push_back({ .name = "hunt", .enables = rmp::behavior::kinds<rmp::behavior::Pathfind>() });
mind.states.push_back({ .name = "volley",
                        .on_enter = [](rmp::Object &self) { self.velocity = {}; },
                        .enables = rmp::behavior::kinds<rmp::behavior::Shooter>() });
mind.transitions.push_back({ .from = "hunt", .to = "volley", .when = [](rmp::Object &self) {
    return self.get<rmp::behavior::StateMachine>()->seconds_in_state() > 3;
} });
mind.transitions.push_back({ .from = "volley", .to = "hunt", .when = [](rmp::Object &self) {
    return self.get<rmp::behavior::StateMachine>()->seconds_in_state() > 2;
} });
boss.add(std::move(mind));
```

[`StateMachine`](https://omardev29.github.io/rmp-docs/reference/behaviors/StateMachine.html) is named states and the moves between them: an enemy that idles, patrols, chases and flees; a boss's phases. A [`State`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-behavior.html#State) has a `name`, `on_enter`, `on_update` (handed the delta) and `on_exit`, and `enables`: the behaviors that run while it is on, written `rmp::behavior::kinds<Patrol, Animator>()`. Every behavior some state names is paused in the states that do not name it. It starts in `initial` (the first state when that is empty) at its first update, and every frame asks its [`transitions`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-behavior.html#Transition) in order: the first whose `from` matches (empty is any state) and whose `when` says yes is taken. `go("name")` moves by name at its next update, `state()` is the state it is in and `seconds_in_state()` how long it has been. A name it does not have is said once and changes nothing.

## From the editor

The behaviors a level designer places — `Patrol`, `Chase`, `Orbit`, `Shooter`, `Hitbox`, `Collectible` — read their fields from an entity of the map with `B::from(const MapObject &)`, which takes each field the entity has by the name below and leaves the rest at their defaults. Put the fields on the entity in LDtk (or as custom properties in Tiled), and the factory is one line:

```cpp
map.on_object("Bat", [](rmp::Scene &s, const rmp::MapObject &o) {
    auto &bat = s.spawn({ .position = o.position, .size = { 12, 8 } });
    bat.add(rmp::behavior::Patrol::from(o));
});
```

| Behavior | Fields it reads |
|---|---|
| `Patrol` | `path` (Array<Point>; the entity's own position is the first waypoint), `speed`, `wait`, `ping_pong` |
| `Chase` | `speed`, `sight`, `fov` |
| `Orbit` | `radius`, `speed` (degrees_per_second), `angle` |
| `Shooter` | `every`, `speed`, `count`, `spread`, `rotate` (rotate_per_shot), `range` |
| `Hitbox` | `damage`, `knockback` |
| `Collectible` | `magnet` |

What is not a number — a target, a callback, a sound — the factory sets, as anything it would set on a behavior of its own. [The dungeon](https://omardev29.github.io/rmp-docs/examples/games/08_dungeon.html) is built this way: every monster, trap and pickup is an entity with these fields, and its code is which behaviors each one carries.

## Writing your own

A behavior of your own is the same struct as the ones above. Write its configuration as fields with defaults, in the order they will be written in the braces; give it `_update`, or `_late_update` when it corrects where the object ended up; add only the hooks it needs; and keep what it remembers in `ours`. A callback field is an [`rmp::Callback`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Callback.html), so a lambda can go straight into the braces:

```cpp
#include <cmath>

// Bobs in place until something on one of the `by` layers touches it, then
// tells on_pick who took it and goes away.
struct Pickup {
    unsigned by = 1;                                     // the collision layers that collect it
    rmp::Callback<rmp::Object &, rmp::Object &> on_pick;  // the pickup, and who took it

    void _ready(rmp::Object &self) { ours.rest_y = self.position.y; }

    void _update(rmp::Object &self, float delta) {
        ours.clock += delta;
        self.position.y = ours.rest_y + std::sin(ours.clock * 3) * 2;
    }

    void _collision(rmp::Object &self, rmp::Object &other) {
        if ((other.collision_layer & by) == 0) return;
        on_pick(self, other);
        self.destroy();
    }

    struct {
        float clock = 0;
        float rest_y = 0;
    } ours;
};

namespace layer { constexpr unsigned PLAYER = 1u << 0; }

class Level : public rmp::Scene {
    int _coins = 0;

    void _ready() override {
        auto &coin = spawn({ .position = { 300, 200 }, .shape = rmp::circle(6) });
        coin.add<Pickup>({
            .by = layer::PLAYER,
            .on_pick = [this](rmp::Object &, rmp::Object &) { ++_coins; },
        });
    }
};
```

A behavior is the right shape when the same few lines would otherwise be written into several kinds of object. When something belongs to one kind of object only, its own `_update()` is simpler.
