Here you can find the latest version of cglib in response to requests and comments from students. The latest version is recommended.

Here you can find the latest version of cglib in response to requests and comments from students. The latest version is recommended.

Should I use the cg::KeyBuffer singleton or implement the cg::IKeyboardListener interface?

The answer depends on how you use the keyboard in that particular module of the application.

If we want to detect a key, we generally implement the IKeyboarddListener interface, and describe the behavior we pretend in the onKeyPressed, onSpecialKeyReleased, etc. methods. This approach is most appropriate when we assume the button is only pressed from time to time (e.g. ESC to quit the application). In such case, we leave to the cglib the responsibility to warn us when this happens (i.e. a purely passive perspective).

Now imagine that we expect the user to be constantly pressing the cursor keys to control an element of the application (e.g. a vehicle in a racing game). In this case, we should detect when a cursor key is pressed (in onSpecialKeyPressed) or released (in onSpecialKeyReleased) and maintain a internal variable (e.g. boolean) keeping the state of the button. In other words, the GLUT (through cglib) only sends a signal when the button is pressed or released, and it is the application responsability to maintain the state during consecutive frames (note: it is actually a bit more complicated, but that's the main idea. For more information, consult the GLUT manual).

As this type of behavior is quite common in interactive graphical applications, we added the class cg::KeyBuffer to the cglib to maintain this boolean value for each key. These variables can be accessed through methods such as isSpecialKeyDown. Thus, in the previous example, at each cycle of the application (i.e. in the update(unsigned long elapsed_millis) method of the entity), we should check whether the button is pressed using cg::KeyBuffer::instance()->isSpecialKeyDown and act in accordance with the result. This mechanism also allows to work with combinations of keys simultaneously (within the limits imposed by GLUT). Finally, it is important to note that, in this case, you do not need to implement the interface cg::IKeyboardListener.