【发布时间】:2020-03-26 15:29:31
【问题描述】:
我正在开发一个游戏项目,发现自己陷入了以下问题:
我有一个名为Game : public sf::Drawable 的类,我用来(除其他外)在我的游戏中绘制所有内容。 Game 包含一个名为Player : public Entity 的类,它又是Entity : public sf::Drawable 的子类。
这些类略有简化,但受影响的功能是一样的:
实体
class Entity : public sf::Drawable
{
private:
sf::Sprite eSprite;
sf::Texture eTex;
std::string texpath;
public:
virtual Entity(std::string texpath, sf::IntRect intrect){
this->texpath = texpath;
eTex.loadFromFile(texpath, intrect);
eSprite.setTexture(eTex); }
virtual ~Entity(){}
virtual void draw(sf::RenderTarget target, sf::RenderStates states)const{
target.draw(this->eSprite);}
//Lots of other functions
}
播放器
class Player : public Entity¨
{
public:
~Player(){}
Player(std::string texpath, sf::IntRect spriteintrect)
:Entity(texpath, spriteintrect){}
void draw(sf::RenderTarget target, sf::RenderStates states){
Entity::draw(target, states); }
}
游戏
#define PLAYER_START "../filepath/image.png",
sf::IntRect{0,0,40,60,}, sf::Vector2f(320.0f, 200.0f) //Ease of access
class Game : public sf::Drawable
{
private:
Player player;
public:
Game() { player = Player(PLAYER_START); };
~Game() {};
void draw(sf::RenderTarget &target, sf::RenderStates states)const { target.draw(player); }
};
为了让问题易于理解,我创建了以下代码示例:
int main(){
sf::RenderWindow window(sf::VideoMode(640, 480), "Game Test");
sf::Event event = sf::Event{};
Game game;
while (window.isOpen())
{
while (window.pollEvent(event))
if (event.type == sf::Event::Closed)
window.close();
window.clear();
window.draw(game);
window.display();
}
}
此代码生成一个白色方块。
我试过了:
- 在
Game之外创建Player并在其上调用window.draw(player);。这行得通。 - 通过赋值运算符和绘图创建一个新的
Player。这行得通。 - 通过复制构造函数和绘图创建一个新的
Player。这行得通。 - 将
Player插入Game类并绘制它。这不起作用,我用上面的代码说明了这一点
我意识到这个问题可以(可能)通过将sf::Sprite 和sf::Texture 移动到Player 类来解决,但是由于我想最终从实体基类派生Coin 和Enemy,我更愿意按原样解决问题。*
感谢您的帮助 /传说
【问题讨论】:
标签: c++ inheritance sfml