Home > OS >  How to set `sf::Drawable` positions sfml
How to set `sf::Drawable` positions sfml

Time:07-12

I'm trying to declare a sf::Drawable * property inside my class body.

the code i already wrote:

#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>

class View{
protected:
    sf::Drawable *view;
};

and inside the class constructor, I want to use the view properties:

class View{
public:
    View(){ view->...}
protected:
    sf::Drawable *view;
}

but I cannot access any of the sf::Drawable methods. I get the No member named 'setPosition' in 'sf::Drawable' warning from IDE.

the only code suggestion i get from code completer is:

draw(RenderTarget& target, RenderStates states)

CodePudding user response:

Indeed, sf::Drawable doesn't have a setPosition method. You could instead use sf::Transformable*, which does have setPosition.

If you need to have drawable properties, then...

  1. If all your items are either shapes/sprites/texts, consider walking down the inheritance chain and use sf::Shape, sf::Sprite, or sf::Text.
  2. Make a separate class for each (ShapeView, SpriteView, TextView).
  3. Use dynamic_cast, as suggested by TheMedicineSeller. But this will incur a small runtime cost.

CodePudding user response:

You cannot set the positions of view inside the constructor of View() as sf::Drawable is a purely Abstract class that is meant only for inheritance.

One way to overcome this is by casting between the derived times at runtime but this method is definitely not recommended and can get ugly.

Another is to have the setPosition() function as virtual and consider a separate class say RectangleView which inherits the Base View class which implements the position setting

class View {
  protected:
    sf::Drawable* view;
    virtual void SetPosition() = 0;
};

class RectangleView : public View {
  public:
   SetPosition();
};

If u ask me, id consider whatever you are trying to do as a bit of overengineering and would advise to not using abstact classes and virtual functions at all for this purpose. Just have specific classes and functions for your sprites and rects.

  • Related