SFML community forums

Help => Graphics => Topic started by: ggggggggggggggg on May 17, 2015, 03:47:41 pm

Title: Using a base entity class that derives from sf::Drawable for different shapes.
Post by: ggggggggggggggg on May 17, 2015, 03:47:41 pm
I want to make a base object class that can be turned into different shapes.

Example:

class Entity : public sf::Drawable
{

};

class Wall : public sf::RectangleShape, Entity
{

};

class Player : public sf::CircleShape, Entity
{

};

I don't know what to put in my override draw functions for Paddle/Wall. Basically, how do you make it draw itself?
Title: Re: Using a base entity class that derives from sf::Drawable for different shapes.
Post by: Hapax on May 17, 2015, 10:07:06 pm
It might be best to not inherit from RectangleShape and CircleShape. Rather, inherit from Drawable, or even Entity.

If your Wall uses a RectangleShape, it should rather store one than inherit one. As Wall would then be drawable, you could draw the RectangleShape in the Wall's draw function:
e.g.
// during variable declarations
sf::RectangleShape rectangle;

// ...

// inside draw function
target.draw(rectangle); // or target.draw(rectangle, states);

Another option to consider is to inherit from Shape (http://www.sfml-dev.org/tutorials/2.3/graphics-shape.php#custom-shape-types).
Title: Re: Using a base entity class that derives from sf::Drawable for different shapes.
Post by: ggggggggggggggg on May 18, 2015, 06:10:00 am
Oh goodness.. I messed up my example. I fixed it now.

But you're saying to have this to work I need to make my own shapes and make them act like the original rectangle/circle?
Title: Re: Using a base entity class that derives from sf::Drawable for different shapes.
Post by: Hapax on May 18, 2015, 05:08:22 pm
Not exactly. You can make custom entities act similarly to other shapes by inheriting from SFML base classes rather than inheriting from the shapes themselves.

I'm thinking something like this:
class Wall : public sf::Drawable, public sf::Transformable
{
public:
        Wall():
                m_rectangle({ 1.f, 1.f })
        {
        }

private:
        sf::RectangleShape m_rectangle;

        virtual void draw(sf::RenderTarget& target, sf::RenderStates states)
        {
                states.transform *= getTransform();
                states.texture = NULL;
                target.draw(m_rectangle, states);
        }
};

Wall wall;

You can then do window.draw(wall); and wall.rotate(25); etc. and you can also include functions to alter textures or HP (for example).

DISCLAIMER: the above code wasn't tested; it's the idea the counts ;)