Skip to content
Download

Collisions

You want to know when one object touches another: the shot and the enemy, the player and the coin, the player and the wall.

The simplest way is to register, in onSpawn, what to do when they touch:

#include <brasa/brasa.hpp>
using namespace brasa;
class Coin : public Entity {
public:
void onSpawn() override {
onCollide<Player>([this](Player& player) {
destroy(); // the player picked up the coin
});
}
};
BRASA_ENTITY(Coin);
  • Each sprite has a collision box, which you adjust in the sprite editor. Two objects collide when the boxes overlap.
  • onCollide<Player>(...) registers a lambda that Brasa calls on every step in which this object is touching a Player. The Player that touched it arrives as a parameter.
  • Objects without a sprite have no box, so they don’t collide.

Ask before moving. collidesAt<T>(x, y) tells whether the object would touch a T if it were at another position:

if (!collidesAt<Wall>(x + 2, y)) x += 2; // only moves if there is no wall

Get who is there. findAt<T>(x, y) returns the instance it found, or nullptr:

if (Enemy* enemy = findAt<Enemy>(x, y + 1)) enemy->destroy(); // stomped on the enemy

Solid walls. Check Sólido (solid) in the Inspector of the wall object. Then placeFree(x, y) tells whether the position is free of solids, and moveAndStop(dx, dy) moves until it touches one:

moveAndStop(); // moves by hspeed/vspeed and stops at the wall