Sign in to follow this  

clarification of this code

This topic is 2547 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


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

Share this post


Link to post
Share on other sites

This topic is 2547 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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