Advertisement

multiple keyboard inputs with opengl

Started by April 14, 2005 12:46 AM
4 comments, last by zedzeek 20 years ago
Hi, I'm a relative newcomer to opengl and am writing and Honours level Thesis on a simple game i'm developing. I'm using straight C to code. I'm hoping this is the right place to post this question! Anyway for keyboard input im using glutKeyboardFunc(keyb); which prototypes like this: void keyb(unsigned char key, int x, int y); Now within this function i've got a whole heap of stuff that looks like this: if(key == 'q') exit(0); Now my problem is this, i want to be able to capture if the user is holding two keys down at the same time, I.E. 'w' and 'a' for accelarate and steer left. I thought this might be difficult as my function is only being passed one keystroke variable. Is this possible and am i on the right track? Thanks
You can quickly get a key state with GetAsyncKeyState(). If you need to check if a key is pressed of not you can just run through a bunch of those for the keys you need. A beter way to do it would either be using DirectInput, or taking care of the keys yourself using Windows Messages (WM_KEYDOWN/WM_KEYUP), but both of those are kind of tricky and you're still using glut I see, so I wouldnt use them just yet...
Advertisement
The easiest way is to have an something like the following:
bool keyArray[128];void keyb(unsigned char key, int x, int y){	keyArray[key] = !keyArray[key];}// in your init functionvoid init(){// ...	memset(keyArray, false, sizeof(bool)*128); // initially there are no keys pressed, so set all to false	glutKeyboardFunc(keyb);// ...}// then in your update funcvoid update(){// ...	if (keyArray['q'])		exit(0);// ...}


Anyway, this is the way I do it, so hope it helps,

SwiftCoder

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

Thanks for that
GetAsyncKeyState() worked a treat

poho
I maintain a buffer (i.e. u32 keys[256] ) with the state of every key (i.e. up or down). The callbacks that I registered with glutKeyboardFunc() AND glutKeyboardUpFunc() make sure that the buffer is updated every time a key is pressed/released.

I know this works because I am also using OpenGL/GLUT for a project and the user-controlled actors in a scene can do lots of things at once without a glitch (e.g. move forward, move up, strafe left whilst turning with the mouse).
using a buffer is a better method than GetAsyncKeyState()

This topic is closed to new replies.

Advertisement