On this page
  1. What an object collides as
  2. Being told
  3. Solid and immovable
  4. Layers and masks
  5. The edges of the world
  6. The map's solid cells
  7. Fast objects
  8. Raycasts
    1. The query
    2. What a ray sees
  9. One scene at a time

Collision

Every frame, after a scene's objects have moved, the scene finds the ones that touch, pushes apart the ones that are solid, and tells both sides of every contact. There is no physics world to set up: an object collides as soon as it has a shape, and everything else is a field.

It is arcade collision on purpose. Rectangles and circles, solid or not, layers and masks, a test that catches fast objects, and raycasts — and deliberately not rotation, polygons, friction, bounce coefficients or joints, which are the beginning of a physics engine. A physics engine such as Box2D is a model of the world: adopting it would make an object's position a mirror of a body somewhere else, and would make the simple case harder — a Pong ball would go from one line to a body, a shape, a density, a restitution, a friction and a gravity switched off. A game that genuinely needs rigid bodies can still link one, step it in _update() and write position from it; the fields are public, and nothing stands in the way.

What an object collides as#

An object collides as the first of these it has:

  1. its collider, when one is set;
  2. its shape;
  3. the box of its sprite's current picture.

An object with none of the three is a point, and a point collides with nothing — otherwise every invisible logic object would be a trigger. The collider is there for the most common step up of all: a character's picture includes hair, a cape and air, and nobody wants to collide with the air.

sprite.sheet = rmp::assets::load_sheet("player.aseprite");   // drawn as the picture
collider = rmp::rect({ 20, 44 });                           // collided as a box
collider.offset = { 0, 4 };                                 // a little lower than the centre

A collider is a rmp::Shape, a rectangle or a circle, placed around the object's centre and scaled with it. Rotation does not turn it: collision is axis-aligned, and a rotated rectangle collides as the same rectangle unrotated. A circle collides as a circle, against circles and against rectangles, which is what sends a ball off the corner of a paddle at the right angle.

world_collider() is the box the collider occupies right now, in world units — for drawing it while you debug, or for a query of your own. world_bounds() is the box of what is drawn, the sprite or the shape. Inside an object's _draw(), which is already in world units:

DrawRectangleLinesEx(world_collider(), 1, LIME);

Being told#

When two objects touch, both are told, through the hook and the callback:

class Spikes : public rmp::Object {
    void _collision(rmp::Object &other) override {
        other.velocity.y = -500;   // whatever touched them jumps
    }
};

A touching pair is reported once per frame, on both objects, for as long as they touch. For each pair, in this order: the first object's _collision() and its behaviors', then the second's, then the first's on_collision callback, then the second's. It happens whether or not either one is solid: solid decides whether they are pushed apart, not whether you hear about it.

The reports come after the pushing, so the positions your code reads are the resolved ones and not an overlap that is about to be undone.

Because a contact is reported every frame and not only when it starts, something that should happen once — a coin collected, a hit taken — destroys the object, or remembers that it happened. The Health behavior's invulnerable window is that memory for damage.

Each side is told as long as it was alive when its pair came up, even if the other side has already been destroyed — so a bullet that destroys itself on contact does not stop the enemy's _collision() and on_collision hearing that it was hit. The other object is always valid to read in a report; its alive() says whether it is still in the game. An object destroyed by an earlier pair of the same frame is told nothing more.

Behaviors are the exception. An object's behaviors are walked in the order they were added, and the walk stops after any behavior once either of the two is no longer alive. So if the bullet was destroyed before the enemy's turn — by its own _collision(), or by a Projectile, which destroys it on a hit by default — only the enemy's first behavior is reached. A Health that has to count that hit goes on before any other behavior.

Solid and immovable#

Three fields, three different questions, and keeping them apart is what makes the common case free:

FieldAsksDefault
colliderWhat shape?The shape, or the picture.
solidPushed apart, or only told?false: only told.
immovableWho gets pushed?false: this one can be.

Most objects in a 2D game are not walls — bullets, coins, particles, pickups, triggers — so solid is off by default, and the two that are solid — the ground, and whatever stands on it — are the two you configure:

auto &ground = spawn({ .position = { 400, 430 }, .size = { 800, 40 } });
ground.solid = true;
ground.immovable = true;

auto &player = spawn({ .position = { 400, 100 }, .size = { 24, 40 } });
player.solid = true;
player.gravity_scale = 1;

When two solid objects overlap, they are pushed apart by the shortest move that separates them. Between two rectangles that is along the axis they overlap least on, which is what makes a character land on top of a platform instead of being shoved off its side. If neither is immovable each moves half the way; if one is, the other moves all of it; two immovable objects overlapping are a mistake in the level, and neither is moved.

Whoever is pushed also loses the part of its velocity going into the contact, and nothing else: a box resting on another under gravity is pushed back up every frame, and without this its downward speed would grow every frame too, so that when the one underneath moved away it would drop at whatever all that resting added up to. With it, the box starts falling from rest; a jump off it keeps its jump, because moving away from the contact is not moving into it; and sliding along a wall keeps the slide. The map's solid cells, below, zero the velocity along the axis they stop.

That happens after the reports, so a _collision() or an on_collision reads the velocity the object hit with — to measure an impact, or to bounce. A bounce that turns the velocity round points it away from the contact, and loses nothing:

class Puck : public rmp::Object {
    void _collision(rmp::Object &other) override {
        if (other.solid) velocity.x = -velocity.x;   // still the speed it hit with
    }
};

Layers and masks#

By default everything collides with everything, so the simple case never mentions a layer. Then, in about the fourth game anybody writes, come the three things that cannot be said without them: the player's bullet must not hit the player, the enemies pass through each other but not through the walls, and a trigger sees the player and nothing else. The alternative is an if at the top of every _collision().

FieldDefaultIs
collision_layer1The layers this object is on, one bit each.
collision_mask1The layers it collides with.

Two objects interact when either one's mask includes the other's layer. Name the bits once, in a header of their own:

#pragma once
// ---------------------------------------------------------------------------
// Who is what, in one place.
//
// One bit per kind of thing. Three fields speak these numbers:
// rmp::Object::collision_layer (what I am), rmp::Object::collision_mask (what
// I collide with) and rmp::behavior::Health::hurt_by (what may hurt me). A
// header of its own, because a second scene file would need exactly these.
// ---------------------------------------------------------------------------

namespace layer {
inline constexpr unsigned PLAYER = 1u << 0;
inline constexpr unsigned ENEMY = 1u << 1;
inline constexpr unsigned BULLET = 1u << 2;
inline constexpr unsigned WORLD = 1u << 3;
inline constexpr unsigned TRIGGER = 1u << 4; // the door: it sees the player, nothing else
} // namespace layer

That file is from the top-down game, where each of the three cases above is a pair of fields. Then say what each kind of object is and what it meets:

auto &bullet = spawn({ .size = { 4, 4 } });
bullet.collision_layer = layer::BULLET;
bullet.collision_mask = layer::ENEMY | layer::WORLD;   // not the player who fired it

auto &enemy = spawn({ .size = { 24, 24 } });
enemy.collision_layer = layer::ENEMY;
enemy.collision_mask = layer::WORLD;                   // not the other enemies

auto &floor = spawn({ .size = { 720, 370 }, .layer = -10 });
floor.collision_layer = 0;                             // scenery: in nothing's way
floor.collision_mask = 0;

The bullet still hits the enemy although the enemy's mask leaves bullets out, because the bullet's mask includes enemies: one side is enough, and then both are told. An object on no layer with an empty mask is out of collision entirely.

These collision layers have nothing to do with the plain layer field, which is draw order. Health::hurt_by speaks the same bits, naming the layers whose touch costs a hit point.

The edges of the world#

What an object does when it reaches the edge of its world is one field, edges, because it is five answers to one question:

rmp::EdgeAt the edgeFor
NONENothing: objects may leave, and do. The default.Almost everything.
CLAMPStops at it.A paddle, a player, a cursor.
BOUNCEIs put back inside and its velocity turned around.A Pong or Breakout ball.
WRAPComes back on the other side.Asteroids.
DESTROYIs destroyed once it has left.Bullets and particles.

The edge is that of the object's bounds. Left empty, it is the scene's map when the scene has one, and otherwise the camera's view — the view and not the window, because once the camera has moved away from the start, the window's rectangle is somewhere nothing on screen is. That is the difference between a paddle in a one-screen game, which wants the screen, and a player in a level, which wants the level, and neither has to say so. Any rectangle can be given instead; Pong gives its ball bounds wider than the court, so that the ball bounces off the top and bottom and leaves by the sides to score.

The rules work on the box of what is drawn, world_bounds(), and they run each frame after the object has moved:

  • CLAMP and BOUNCE act as soon as the box crosses an edge. BOUNCE turns the velocity around only when it points out of the world, so an object that starts overlapping an edge leaves instead of shaking against it.
  • WRAP waits until the box is entirely outside, so an asteroid slides off instead of popping, and it comes back just outside the far edge, so it slides back in the way it went out.
  • DESTROY waits until the box is entirely outside — so a bullet fired from a muzzle on the edge of the screen is not destroyed at birth — and only destroys an object that has been inside at some point, so obstacles spawned ahead of the camera, outside the view, are not destroyed on their first frame.

The map's solid cells#

A scene with a map collides against it; Tilemaps is about loading and drawing one. Which cells are solid is decided in the level editor: in LDtk, the cells of an IntGrid painted with the value whose identifier is solid, or tiles tagged solid through the tileset's enum; in Tiled, every tile of a layer whose class is solid, or a tile its tileset marks solid.

An object that is solid and not immovable is stopped by those cells as it moves — not pushed out of them afterwards. The difference is the classic one: pushing a box out of each overlapping tile the shortest way makes a player running along a floor catch on the seam between two tiles, where the shortest way out of the next one is sideways. So the move is made one axis at a time, across and then down, and running only ever meets walls and falling only ever meets floors.

  • A fast object moves in steps no longer than half the smallest cell, or half its own size, so a fall faster than a tile per frame still lands on the floor.
  • The step that would end inside a solid cell is narrowed down to the point of contact, and the velocity along that axis becomes zero: the landing, or the head on the ceiling.
  • An object that starts inside a solid cell — placed in a wall, or pushed into one — is moved out the shortest way, up winning a tie, which is the right answer for something pushed into the floor. One buried too deep to get out within a cell plus its own size stays where it is and stops, visibly stuck rather than falling out of the world.
  • Pushing two solid objects apart never moves one into a solid cell: a push that would is undone, so a moving platform cannot shove the player through a wall.

Objects that are not solid, and immovable ones, pass through the map; they are moved by your code, not by the world. The cells are not objects, so they never appear in _collision(): ask the map instead, with map.solid_at(point) or map.solid_in(rectangle). A rectangle only touching a solid cell is not in it: a box standing on the floor is not in the floor.

Fast objects#

A bullet moving 900 units a second moves 15 units in a frame at 60 frames a second. Against a wall 10 units thick there is no frame on which the two overlap, and a test of where things are would let it through. So an object that moved more than half its own smaller side in one step is tested against the path it travelled, not only where it ended.

When both objects of such a contact are solid, the fast one is put back at the point of contact before they are pushed apart. When either is not, nothing is moved, and both are still told: a trigger learns that something went through it, and it goes through.

Only travel counts as a path. A position written by your code is a teleport, and is not swept across everything between where the object was and where you put it. Two objects that already overlapped when the step began are left to the ordinary test, which separates them on the frame they really overlap. The other half of the answer to tunnelling is [app] max_delta, which stops a stalled frame from turning into one enormous step.

Raycasts#

A ray asks what is along a line: what a shot hits, whether there is ground under the feet, whether an enemy can see the player.

if (rmp::RayHit hit = raycast(muzzle, muzzle + aim * 400)) {
    auto &spark = spawn({ .position = hit.point, .size = { 3, 3 } });
    spark.velocity = hit.normal * 120;
}

raycast() tests the segment from one point to the other against the scene's objects and returns the nearest hit, an rmp::RayHit, which is true when something was hit:

FieldIs
objectWhat was hit, as a handle, so it is safe to keep.
pointWhere, in world units.
normalThe surface's direction there, pointing back at the ray: what orients a spark, a bullet hole or a bounce.
distanceFrom the start of the ray.

A ray that starts inside a rectangle hits it at distance 0, with the normal pointing back along the ray, wherever the ray ends. One that starts inside a circle hits it where it leaves, with the normal pointing outwards there — and misses it altogether when it ends inside the circle too. Two hits at the same distance come back in the order the objects were spawned, so the answer does not change from one run to the next.

The query#

The longer form takes an rmp::RayQuery, and the field that matters most is ignore, because without it the first thing every shot hits is the thing that fired it. It is a handle, so an object shooting names itself with handle():

rmp::RayHit hit = scene().raycast({ .from = position, .to = target,
                                    .mask = layer::ENEMY, .ignore = handle() });
FieldDefaultIs
from, to{ 0, 0 }The segment, in world units; nothing beyond to is hit.
maskevery layerOnly objects on one of these layers are hit.
ignorean empty handleOne object to pass through: normally whoever is shooting. An empty handle, or the handle of an object that is gone, passes through nothing.
solid_onlyfalseOnly solid objects are hit.

solid_only exists for the ground check. A character asking what is under its feet wants the floor and not the coin lying on it, and a mask cannot say that: layers are about who collides with whom, and solid is about whether the contact holds. Filtering the nearest hit afterwards would not do either, because the coin would hide the floor behind it; with solid_only the coin is skipped and the floor is found.

The ray's mask is tested against the objects' layers only — a ray has no layer of its own for an object's mask to match.

raycast_all() writes every hit along the ray into an array of yours, nearest first, as many as it holds, and returns how many it wrote — for a shot that pierces, or a line of sight that has to know everything in the way:

std::array<rmp::RayHit, 8> hits;
const int count = raycast_all({ .from = muzzle, .to = target }, hits);
for (int i = 0; i < count; ++i) {
    if (auto object = hits[i].object.get()) object->destroy();
}

It takes a std::span, so a std::array, a std::vector or a plain array goes in as it is, and the span carries its length: there is no count to pass beside it and get wrong.

Rays hit objects and not the map's cells; for those, ask the map with solid_at(). From inside an object, the scene is scene(): scene().raycast(from, to).

What a ray sees#

Rays are nearly free, because they reuse the grid the collision pass already builds: only the objects in the cells the line crosses are tested, so a ray across a thousand objects touches a handful. The price of sharing is when that grid is rebuilt — whenever the framework moves the world: a spawn, a destroy, the start of each scene's update and of its collision pass. A ray cast right after your code wrote another object's position by hand sees that object where it was at the start of the pass, the way a physics engine with a stepped world does. The ray's own start is whatever you pass, so a character asking about the ground under itself is never the stale half.

One scene at a time#

Objects collide with the other objects of their own scene, and with its map. A pause menu pushed on top has objects of its own, which never meet the frozen world underneath.