SDL KeyDown and KeyHit functions

Started by
7 comments, last by Alan2000 16 years ago
Hi, I'm having problems creating the above functions to return true if a particular key has been pressed? These functions need to behave in the same manor as the functions in a popular game engine Blitbasic, so if someone writes: if(KeyDown(SDLK_RIGHT)) playerY += 1; and you could also have a game loop set to exit if a particular key was hit while(!KeyHit(SDLK_ESCAPE)) // run app This way you give the user the option to choose thier own keys for tasks :) Thanks.
Advertisement
SDL_GetKeyState would be a good place to start.
Thanks for the reply, yes I have taken this avenue before but struggled to actually write the function using this method? I will take another look but it's not looking great so far.
A KeyDown() function might look like this (you could also add in array bounds checking if you like).

bool KeyDown(int key){	Uint8 *KeyboardState = SDL_GetKeyState(0);	return 1 == KeyboardState[key] ? true : false;}


As for KeyHit(), is that to test if a key was pressed and then released? If so simply compare the current key state with the previous key state (if key_was_down and key_is_now_up then key_hit).

Edit: Don't forget, SDL_PumpEvents() to update the keyboard state etc.
Progress is born from the opportunity to make mistakes.

My prize winning Connect 4 AI looks one move ahead, can you beat it? @nickstadb
Thanks for that, it still returns true, this is the problem, it doesn't matter what method I do it always returns true :(
Are you using SDL_PumpEvents() in your game loop somewhere?
Progress is born from the opportunity to make mistakes.

My prize winning Connect 4 AI looks one move ahead, can you beat it? @nickstadb
Yeah I've got a listen function which is called in the loop, in here you could put keyState = SDL_GetKeyState(NULL);
if(keyState[SDK_ESCAPE]==1))
exit(0)

And this would work. So in here I have PumpEvents() does it need to be (NULL) or (0)? Or would that make no difference?
It would make no difference - NULL is zero.
Got it going, thank InsaneBoarder, I had this in the main loop
doReciever(){	while(SDL_PollEvent(&event)) {		switch(event.type){			case SDL_QUIT:				exit(0);				break;		}	}}

then the function
KeyDown(int key){	Uint8 *KeyboardState = SDL_GetKeyState(0);	return 1 == KeyboardState[key] ? true : false;}


Thanks again :)

This topic is closed to new replies.

Advertisement