OpenGL with Cocoa: Part 3
Another part to my series of guides for programming in OpenGL with Cocoa. Yesterday I showed you how to actively render in OpenGL with Cocoa: Part 2.
This entry however will show you how to make the OpenGL view the first responder to 'messages', so that you can get key input and control turning of the triangle. All of the new functions with the exception of "keyAction" are overloaded and so a part of the Cocoa view system.
The new attribute "m_keys" will be used for storing the status of the key being pressed, true if it is pressed, false if it isn't.
Now when the application is started, we need to reset the values for "m_keys" to false so that we don't have uninitialized data. We can do this within the functions "awakeFromNib" or "initWithCoder" but I have chose to do it within "initWithFrame".
With that done we need to implement our new functions. For "acceptsFirstResponder", "becomeFirstResponder" and "resignFirstResponder" we return "YES" so that the OpenGL view class we are using gets the messages first instead of the main window.
For "keyDown" and "keyUp" we check to see if there is any input and then forward the information onto one of our own classes, "keyAction" with a value which specifies if the key is pressed or not. This is they set to the Boolean array a the appropriate index.
We could just use the "keyAction" function to control the triangle, however we would be limited in update cycles depending on the repeat rate of messages during a key press.
Now during the "drawRect" function, we check the status of key presses within the Boolean array. If the key 'A' is pressed, we rotate the triangle left by one degree per frame. However if 'D' is pressed, it will rotate the triangle right by one degree per frame. And if neither are pressed, nothing will happen.
As before we are not using glLoadIdentity() so the resultant matrix from the last frame is being modified, not a new one which we would have to store and increment a rotational value for.
With the new changes, build and run the application, and pressed 'A' and 'D' to watch the triangle rotate differently. In the previous guide it rotated constantly, however now it requires key input of specific keys to rotate it, and you have control over the direction of rotation.
Thats all for OpenGL with Cocoa for the moment. Still working out some of the bugs in my own applications as I convert them from GLUT, so hopefully the next guide will show you how to switched between window and fullscreen modes.
Download Source: CocoaGL Source (Part 3)