Sign in to follow this  
Alan2000

SDL KeyDown and KeyHit functions

Recommended Posts

Alan2000    122
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.

Share this post


Link to post
Share on other sites
Alan2000    122
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Alan2000    122
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?

Share this post


Link to post
Share on other sites
Alan2000    122
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 :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this