0

假设我有一个类实体。
然后我有 n 个从 Entity 派生的类,
例如:

class Snake : public Entity{...};  
class Mouse : public Entity{...};

现在我有一个实体类玩家。
我可以创建一个继承自任何类型实体的类播放器吗?例如:

class Player : public Entity -->(but instead of entity be any type of entity)  

这可以做到吗?
这是通过使用模板实现的吗?
我读过模板可以在 cpp 文件中明确指定,即

template class Entity<Snake>;

我正在努力实现以下目标

在我的玩家类中,我有一个 moveCamera 函数,现在只有当玩家移动时,相机才会移动。如果 AI Snake 移动,相机不应该移动。

这是我在实体类中的渲染函数,它是虚拟的

void Entity::Render(float interpolation)
{
  if(currentAnimation != 0){
    float x = this->currLocation.x - (this->currentVelocity.x * (1.0f - interpolation)) - camera->getLocation(L_FACTOR_CURRENT).x;
    float y = this->currLocation.y - (this->currentVelocity.y * (1.0f - interpolation)) - camera->getLocation(L_FACTOR_CURRENT).y;
    currentAnimation->Render(x,y);
  }
}

这是我的 gameUpdate 函数,基本上将实体移动到其各自的世界坐标

void Entity::GameUpdate(float gameUpdateDelta)
{
  this->Move();
}

因此,对于我的播放器的移动函数,我将调用相机的移动函数,然后调用基类的移动函数......现在可以调用基类移动函数的扩展类。
我的移动函数是虚拟的,因此是一条蛇和鼠标可以移动不同..

4

2 回答 2

1

您可能想要编写一个Player继承自 Template 参数的模板类。

template< typename Derived >
class Player: 
    public Derived, // we believe that Derived inherits Entity
    public IPlayer  // makes sense if Player is not a Entity only interface
{
   ... some declaration here ...

   void update(); // some virtual method from Entity interaface
   void player_action(); // some virtual method from IPlayer interaface

}

创建具体类型的播放器时,您可以将其放置在您的场景中。

IPlayer* player1 = new  Player<Snake>("Player1");

Entity* playerEntity = dynamic_cast< Entity* >( player1 );
if( playerEntity ) // test if object can be placed on scene
{
    scene->add( playerEntity );
}

您可能还需要知道如何编写类方法的部分模板特化。此外,您可能会发现boost enable_if是一个强大的玩具。

于 2012-05-22T02:37:14.780 回答
0

如果您可以发布当前设计的接口(仅是类定义),对人们的帮助会更有帮助。看起来你需要让玩家自己的蛇和老鼠。如果您希望某些操作与其他操作相关联,请使用观察者。

于 2012-05-22T04:21:37.377 回答