Skip to content

Custom Drawables

Modar Nasser edited this page Sep 6, 2021 · 5 revisions

Creating a custom Drawable can be handy to group multiples sprites or shapes as one object.

To do so, you have to inherit from sf::Drawable and implement the virtual draw mehtod.

If you want to take advantage of the ySort method of scene Layers, you also have to implement a getPosition method.

Finally, to take advantage of smart rendering, you can implement a getGlobalBounds or getBounds method.

Let's see an example, a custom drawable composed by a circle and a rectangle :

class MyDrawable : public sf::Drawable {
    sf::CircleShape circle;
    sf::RectangleShape rect;
public:
    MyDrawable() {
        circle.setRadius(10);
        circle.setOrigin(10, 10);
        rect.setSize({10, 20});
        setPosition(0, 0);
    }

    void setPosition(float x, float y) {
        circle.setPosition(x, y);
        rect.setPosition(x + 10, y - 10);
    }
    
    sf::Vector2f getPosition() {
        return circle.getPosition();
    }
    
    ns::FloatRect getGlobalBounds() {
        // compute the global bounds of circle and rect union
        return ns::utils::computeBounds({
            circle.getGlobalBounds(),
            rect.getGlobalBounds()
        });
    }

    void draw(sf::RenderTarget& target, sf::RenderStates states) const override {
        target.draw(circle);
        target.draw(rect);
    } 
};

Then, you can add a MyDrawable object to a scene and see the result :

auto* my_drawable = new MyDrawable();
my_drawable->setPosition(50, 50); 
scene.getDefaultLayer().add(my_drawable);