【问题标题】:sf::Drawable and sf::Transformable array containing sprites, text and shapes包含精灵、文本和形状的 sf::Drawable 和 sf::Transformable 数组
【发布时间】:2016-08-26 05:59:41
【问题描述】:

我想创建一个数组,其中包含将绘制到窗口上的所有精灵、文本和形状,我的问题是如何使这个数组同时具有 sf::Drawable 和 sf::Transformable?

【问题讨论】:

  • 虽然不能解决您的编码问题,但您可能想看看实体系统(例如 EntityX)。这些解决了您在使用继承解决此问题时遇到的问题。

标签: c++ types sfml


【解决方案1】:

您需要创建一个继承DrawableTransformable 的类。然后你就可以创建一个该类的数组了。

class Obj : public sf::Drawable, public sf::Transformable
{
    // class code
}

// somewhere in code...
std::array<Obj, ARRAY_SIZE> arr;

确保正确实现DrawableTransformable


这里是官方文档的链接。

Transformable & Drawable


实现这些类的一种方法是:

class Obj : public sf::Drawable, public sf::Transformable
{
    public:

    sf::Sprite sprite;
    sf::Texture texture;

    // implement sf::Drawable
    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
    {
        target.draw(sprite, states); // draw sprite
    }

    // implement sf::Transformable
    virtual void SetPosition(const MyVector& v) const
    {
        sprite.setPosition(v.x(), v.y());
    }
}

然后在你的代码中你可以直接绘制和转换类。

// somewhere in code
// arr = std::array<Obj, ARRAY_SIZE>
for (auto s : arr) {
    window.draw(s);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 2015-11-07
    • 2022-10-25
    相关资源
    最近更新 更多