Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Using a base entity class that derives from sf::Drawable for different shapes.  (Read 2696 times)

0 Members and 1 Guest are viewing this topic.

ggggggggggggggg

  • Newbie
  • *
  • Posts: 36
    • View Profile
    • Email
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?
« Last Edit: May 18, 2015, 06:10:18 am by asusralis »

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
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.
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

ggggggggggggggg

  • Newbie
  • *
  • Posts: 36
    • View Profile
    • Email
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?

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
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 ;)
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*