我想知道在游戏循环中创建类的对象的正确方法是什么?例如,我有Box,Sphere,Cyllinder类,我想在程序运行的同时在不同的时间创建多个对象,并在将来使用它们。如何保存这些物体的正确方法?将所有类作为向量组合在一个类中?
vector<glm::vec3> initVerts = {/*verts position*/};
class Box
{
vector<glm::vec3> verts;
Box(): verts(initVerts)
void moveBox(glm::vec3 newPos){ /*translate verts*/ }
};
while ( !windowShouldClose())
{
Box box;
box.moveBox(1.0,0.0,0.0); // on the second pass it was another box with initial position
}
答案 0 :(得分:1)
最简单的方法是为每个类类型创建一个向量。开始:
std::vector<Box> boxes;
boxes.reserve(100); // however many you expect to need
Box& box1 = boxes.emplace_back();
while ( !windowShouldClose())
{
box1.moveBox(1.0,0.0,0.0);
}
或者,如果您不需要迭代所有对象的方法,您可以将它们单独存储在循环之外:
Box box1;
while ( !windowShouldClose())
{
box1.moveBox(1.0,0.0,0.0);
}