sf::Drawable 和 sf::Transformable 包含精灵、文本和形状的数组
sf::Drawable and sf::Transformable array containing sprites, text and shapes
我想创建一个数组,其中包含将绘制到 window 上的所有精灵、文本和形状,我的问题是如何使这个数组同时包含 sf::Drawable 和 sf::Transformable?
您需要创建一个 class 继承 Drawable
和 Transformable
。然后你就可以创建一个 class.
的数组
class Obj : public sf::Drawable, public sf::Transformable
{
// class code
}
// somewhere in code...
std::array<Obj, ARRAY_SIZE> arr;
确保正确实施 Drawable
和 Transformable
。
这里是link官方文档。
实现这些 classes 的一种方法是:
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());
}
}
然后在您的代码中您可以直接绘制和转换 class。
// somewhere in code
// arr = std::array<Obj, ARRAY_SIZE>
for (auto s : arr) {
window.draw(s);
}
我想创建一个数组,其中包含将绘制到 window 上的所有精灵、文本和形状,我的问题是如何使这个数组同时包含 sf::Drawable 和 sf::Transformable?
您需要创建一个 class 继承 Drawable
和 Transformable
。然后你就可以创建一个 class.
class Obj : public sf::Drawable, public sf::Transformable
{
// class code
}
// somewhere in code...
std::array<Obj, ARRAY_SIZE> arr;
确保正确实施 Drawable
和 Transformable
。
这里是link官方文档。
实现这些 classes 的一种方法是:
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());
}
}
然后在您的代码中您可以直接绘制和转换 class。
// somewhere in code
// arr = std::array<Obj, ARRAY_SIZE>
for (auto s : arr) {
window.draw(s);
}