首先,我真的很抱歉标题,但我不知道如何正确表达我的问题。无论如何,我正在使用 C++ 和 Allegro 5 创建相同的游戏,只是使用更复杂的技术进行练习。现在我正在尝试使用实体和组件,但我遇到了障碍。
this->entity = new Entity();
this->entity->addComponent(new ComponentTest());
// How I currently access components
ComponentTest *c = (ComponentTest*)this->entity->getComponent("test");
c->setVariable(10);
// This would be cool
this->entity->getComponent("test")->setVariable(10);
// This would be completely rad
this->entity["test"]->setVariable(10);
问题是 Entity::getComponent 返回一个指向 Component 的指针,因此我必须将其显式转换回 ComponentTest 才能使用其方法 ComponentTest::setVariable。
如果有某种方法可以使用我提到的其他两种访问方式,我只是在徘徊。我也愿意接受有关更改代码的建议,以便更轻松地访问实体的组件。
tl;dr:懒得显式转换组件。是否可以通过其他两种方式访问组件?
您可以像这样在 Entity 中定义模板函数:
template<typename T>
T* getComponent(const std::string &componentName)
{
Component *component = getComponent(componentName);
return dynamic_cast<T*>(component);
}
并像提到的@ Jarod42 那样称呼它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句