0

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?

Edited by nuclear: n/a

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by gusano79
0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.