Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making custom types drawable with SFML

Tags:

c++

sfml

I picked up using SFML recently, and I decided as a learning experience I would make a pong clone using it. I've defined a class called Ball which draws uses SFML to draw a RectangleShape. When I try to draw this custom type to the screen with the window.draw() function however, I get errors because Ball isn't an sf::Drawable. I would appreciate help with this, being new to SFML.

like image 254
Terrance8D Avatar asked Apr 27 '26 07:04

Terrance8D


1 Answers

To use window.draw(object) object's class must inherit the drawable interface and implement the abstract sf::Drawable::draw function.

It sounds like the sf::RectangleShape is a member of Ball. SFML knows how to render the shape, but not Ball itself. Ball's class declaration should look like this:

class Ball : public sf::Drawable //,...
{
    //...
    private:
    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
    //...
};

And draw should be implemented like this:

void Ball::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
    //assuming m_shape is the sf::RectangleShape
    target.draw(m_shape, states);
}
like image 131
Conduit Avatar answered Apr 29 '26 19:04

Conduit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!