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);How it works
Section titled “How it works”- 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 aPlayer. ThePlayerthat touched it arrives as a parameter.- Objects without a sprite have no box, so they don’t collide.
Variations
Section titled “Variations”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 wallGet 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 enemySolid 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 wallSee also
Section titled “See also”- Collision: all the functions.
- 4. Enemies, in the tutorial.
