OpenglNoob OpenglNoob - 2 months ago 17
C++ Question

Creating class object in the game loop

I'm wondering how is the proper way to create objects of classes in the game loop once? For example I've Box, Sphere, Cyllinder classes and I want to create several objects at different time while the program is running and work with them in the future. How is the proper way to preserve this objects? Combine all of classes as vector in one class?

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
}

Answer Source

The simplest way will be to create one vector per class type. To start:

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);
}

Or if you don't need a way to iterate over all your objects, you can just store them individually outside the loop:

Box box1;

while ( !windowShouldClose())
{
    box1.moveBox(1.0,0.0,0.0);
}