因此,我正在考虑游戏如何处理所有实体的更新,并且我有点困惑(可能是因为我的方法有误)。
所以我决定在这里发布这个问题,展示一下我当前的思考方式,并看看是否有人能建议我更好的做法。
目前,我有一个CEngine类,它接收指向其他需要的类的指针(例如CWindow类、CEntityManager类等)。
我有一个游戏循环,在伪代码中将像这样进行(在CEngine类内部)。
while(isRunning) {
Window->clear_screen();
EntityManager->draw();
Window->flip_screen();
// Cap FPS
}
我的CEntityManager类看起来像这样:
enum {
PLAYER,
ENEMY,
ALLY
};
class CEntityManager {
public:
void create_entity(int entityType); // PLAYER, ENEMY, ALLY etc.
void delete_entity(int entityID);
private:
std::vector<CEntity*> entityVector;
std::vector<CEntity*> entityVectorIter;
};
我的CEntity类看起来像这样:
class CEntity() {
public:
virtual void draw() = 0;
void set_id(int nextEntityID);
int get_id();
int get_type();
private:
static nextEntityID;
int entityID;
int entityType;
};
接下来,我会为敌人创建一个类,并为其添加精灵表、自己的函数等。
例如:
class CEnemy : public CEntity {
public:
void draw(); // Implement draw();
void do_ai_stuff();
};
class CPlayer : public CEntity {
public:
void draw(); // Implement draw();
void handle_input();
};
所有这些对于只是在屏幕上绘制精灵来说都很好用。但接下来我遇到了一个问题,那就是使用存在于一个实体中而不存在于另一个实体中的函数。如上面的伪代码示例中,do_ai_stuff(); 和 handle_input();从我的游戏循环中可以看出,有一个对EntityManager->draw()的调用; 它遍历了entityVector并为每个实体调用了draw()函数 - 这很好用,因为所有实体都有draw()函数。
但是我想知道,如果是一个玩家实体需要处理输入怎么办? 这个该怎么解决呢?
我还没有尝试过,但我认为不能像draw()函数一样循环遍历,因为敌人这样的实体不会有handle_input()函数。
我可以使用if语句来检查实体类型,像这样:
for(entityVectorIter = entityVector.begin(); entityVectorIter != entityVector.end(); entityVectorIter++) {
if((*entityVectorIter)->get_type() == PLAYER) {
(*entityVectorIter)->handle_input();
}
}
但是我不知道人们通常如何编写这些内容,所以我不确定最好的方式是什么。
我写了很多东西,却没有提出任何具体问题,因此我将澄清我在寻找什么:
- 我的代码布局/设计是否可以?是否实用?
- 是否有更好、更高效的方法更新我的实体并调用其他实体可能没有的函数?
- 使用枚举来跟踪实体类型是识别实体的好方法吗?