954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

SDL key event question

I was watching a tutorial that says that we first need to check if any direction key was pressed, and only then we check which key was pressed, like this:

while( running == true )
	{
		while( SDL_PollEvent(&event) )
		{
			if ( event.type == SDL_KEYDOWN ) //checking if any key was pressed
			{
				switch( event.key.keysym.sym ) //checking for specific 
				{
				case SDLK_UP: yC -= 10; break; // yC -coordinates of a surface
				case SDLK_DOWN: yC +=10; break;
				}
			}
			else
				if ( event.type == SDL_QUIT )
				{
					running = false;
				}
		}


But then i tried to do it wihouth checking if any key was pressed and just jump to the specific key that was pressed:

while( running == true )
	{
		while( SDL_PollEvent(&event) )
		{
			if ( event.key.keysym.sym == SDLK_UP )
			{
				yC -= 10;
			}
			else
				if ( event.key.keysym.sym == SDLK_DOWN )
				{
					yC += 10;
				}
			else
				if ( event.type == SDL_QUIT )
				{
					running = false;
				}
		}


And the thing is that for some reason when i use the tutorial method it works just fine, but when i use my method the surface moves when i press the button and when i let go of it. Why do we even need to check if any key was pressed?

nuclear
Junior Poster in Training
94 posts since Aug 2011
Reputation Points: 2
Solved Threads: 3
 

I was watching a tutorial that says that we first need to check if any direction key was pressed, and only then we check which key was pressed, like this:

But then i tried to do it wihouth checking if any key was pressed and just jump to the specific key that was pressed:

And the thing is that for some reason when i use the tutorial method it works just fine, but when i use my method the surface moves when i press the button and when i let go of it. Why do we even need to check if any key was pressed?

if ( event.type == SDL_KEYDOWN ) //checking if any key was pressed


The comment "checking if any key was pressed" is misleading. Really it's checking if the specific key event we're responding to is a "key down" event. Without this line, your code executes on all key events, including "key up"--this is why it behaves the way you describe.

gusano79
Posting Pro
521 posts since May 2004
Reputation Points: 182
Solved Threads: 77
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: