The scenario
I am working on a HUD class to aid me in development of an OpenGL project. I want to be able to add new elements onto the screen dynamically (positioning will happen automatically) with the use of an add_element(char*, float) method. Here is the said code:
class HUD {
public:
HUD();
~HUD();
private:
int elements,
spacing;
public:
void add_element(char*, float);
};
HUD::HUD() : elements(0), spacing(10) {}
HUD::~HUD() {}
void HUD::add_element(char* string, float value) {
++elements;
// .. render to screen .. //
}
The basic idea is: It will position them vertically for me as I continue to add elements.
The problem
The class gets instantiated inside the main function, and the elements get added and drawn to the screen within and at the end of my game loop. This means, every frame, the element counter gets incremented, when it should only increment the first time a unique element is added. I have thought about adding unique identifiers as an argument, like numbering them manually every time I call the method, but this seems to defeat the purpose I am going for.
I am just looking for some ideas that can solve this type of incrementing inside a loop. I have a few scenarios in which I need to do this, and the HUD is the first one I ran into.
I did a similar thing working on an XNA game (so C#). My class had a list of things to be written on screen:
I did a “write” function which adds a new to_write element to the _logs list
but the actual output on screen happened only during the draw function:
This class’s Update() and Draw() methods were the last that were called allowing every other component to add its own informations to the HUD. You can make things simpler by using a simple array and keeping an array pointer, this way both adding element to write and clearing the list are O(1).