Handles
Pointers such as Enemy*, returned by spawn, findAt and closest, are valid only within the current step. If the instance is destroyed, the pointer you kept starts pointing at garbage, and using it crashes the game.
A handle is a safe reference: when the instance goes away, it simply becomes empty.
class Turret : public brasa::Entity {public: void onSpawn() override { if (Player* p = closest<Player>()) target_ = p->handle<Player>(); } void onUpdate() override { if (Player* p = target_.get()) { // nullptr if the player was destroyed angle = -angleTo(*p); } }
private: brasa::Handle<Player> target_;};| Function | What it does |
|---|---|
Handle<T> handle<T>() const |
Creates a handle to this instance. |
T* get() const |
The instance, or nullptr if it has already been destroyed. |
if (handle) |
The handle is true while the instance exists. |
The camera uses handles to follow an instance: scene().camera.follow(handle());.
