clarification of this code

Started by
1 comment, last by rev2 13 years, 3 months ago
Hello, this is regarding the motion section of lazyfoo's tutorials, on there under the dot.handleInput() function he's got this


void Dot::handle_input() {
//If a key was pressed
if( event.type == SDL_KEYDOWN ) { //Adjust the velocity
switch( event.key.keysym.sym ) {
case SDLK_UP: yVel -= DOT_HEIGHT / 2; break;
case SDLK_DOWN: yVel += DOT_HEIGHT / 2; break;
case SDLK_LEFT: xVel -= DOT_WIDTH / 2; break;
case SDLK_RIGHT: xVel += DOT_WIDTH / 2; break;
}
}
//If a key was released
else if( event.type == SDL_KEYUP ) { //Adjust the velocity
switch( event.key.keysym.sym ) {
case SDLK_UP: yVel += DOT_HEIGHT / 2; break;
case SDLK_DOWN: yVel -= DOT_HEIGHT / 2; break;
case SDLK_LEFT: xVel += DOT_WIDTH / 2; break;
case SDLK_RIGHT: xVel -= DOT_WIDTH / 2; break;
}
}
}

what I'm wondering is, why do we need to include the SDL_KEYUP section?. Isn't having the SDL_KEYDOWN event enough?. I mean whenever you hold down either arrow key the xvel,yvel variables change and when its no longer pressed the variable doesnt change so what is the point of the SDL_KEYUP section?. lazyfoo has included why this happens but I still don't fully follow as to why he has done this.

please advise
Advertisement
Quote:Original post by rev2
Isn't having the SDL_KEYDOWN event enough?. I mean whenever you hold down either arrow key the xvel,yvel variables change and when its no longer pressed the variable doesnt change so what is the point of the SDL_KEYUP section?. lazyfoo has included why this happens but I still don't fully follow as to why he has done this.
When you push a key down SDL sends an event once. The velocity is updated (once) and remains at the updated value until something else updates the velocity. In this case when the key is released the velocity that was added is canceled out by performing the opposite action when the key is set.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

I see, so effectively setting the xvel and yvel values too 0 so that the next event does not skrew up?.

This topic is closed to new replies.

Advertisement