I wanna try implement sprite group as in pygame. I acted according to
this article, but I confused. Firstly, I don't understand how to pass Drawable object to group. I typed the code as following:
struct Group : public sf::Drawable {
std::vector<std::reference_wrapper<const sf::Drawable>> sprites;
Group() : sprites{} {}
virtual ~Group() = default;
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const {
for(const auto& sprite : sprites){
target.draw(sprite, states);
}
}
const sf::Drawable& operator[](std::size_t index){
return sprites[index];
}
std::size_t add(const sf::Drawable& sprite){
sprites.push_back(sprite);
return sprites.size() - 1;
}
const sf::Drawable& remove(){
const auto& sprite = sprites.back();
sprites.pop_back();
return sprite;
}
};
struct Box : public sf::Drawable, public sf::Transformable{
sf::Texture texture;
std::vector<sf::Vertex> vertices;
sf::PrimitiveType m_type;
virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const{
states.transform *= getTransform();
states.texture = &texture;
target.draw(&vertices[0], vertices.size(), m_type, states);
}
Box(const std::string path, sf::PrimitiveType type, int length, float *coords){
for(int i = 0; i < length * 2; i++){
vertices.push_back(sf::Vertex(sf::Vector2f(coords[i], coords[i+1]),sf::Vector2f(coords[i], coords[i+1])));
i++;
}
if(!texture.loadFromFile(path)){
std::cerr << "Failed to loading file!" << std::endl;
}
m_type = type;
}
};
float coords[] = {
0.0f, 0.0f,
32.0f, 0.0f,
32.0f, 32.0f,
0.0f, 32.0f,
};
int main()
{
Group spriteGroup;
sf::RenderWindow window(sf::VideoMode(640, 480), "SFML works!");
std::vector<Box> boxes;
for(int i=0; i < 10; i++){
boxes.push_back(Box("../resources/box.png", sf::Quads, 4, coords));
spriteGroup.add(boxes[i]);
}
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear(sf::Color::White);
window.draw(spriteGroup[1]);
window.display();
}
return 0;
}
In addition, I got these runtime errors:
pure virtual method called
terminate called without an active exception
Aborted (core dumped)