printf( "none\n" ); return; } /* check for the presence of each sdlmod value */ /* this looks messy, but there really isn't */ /* a clearer way. */ if( mod & kmod_num ) printf( "numlock " ); if( mod & kmod_caps ) printf( "capslock " ); if( mod & kmod_lctrl ) printf( "lctrl " ); if( mod & kmod_rctrl ) printf( "rctrl " ); if( mod & kmod_rshift ) printf( "rshift " ); if( mod & kmod_lshift ) printf( "lshift " ); if( mod & kmod_ralt ) printf( "ralt " ); if( mod & kmod_lalt ) printf( "lalt " ); if( mod & kmod_ctrl ) printf( "ctrl " ); if( mod & kmod_shift ) printf( "shift " ); if( mod & kmod_alt ) printf( "alt " ); printf( "\n" ); }
游戏式键盘输入
键盘消息仅在键的状态在按下和放开间变化时才触发。
设想你用光标键控制飞船运动以改变眼前看到的太空景象,当你按左键并希望镜头向左转时。看看下面的代码,并注意它为什么是错的。
/* alien screen coordinates */
int alien_x=0, alien_y=0;
.
.
/* initialise sdl and video modes and all that */
.
/* main game loop */
/* check for events */
while( sdl_pollevent( &event ) ){
switch( event.type ){
/* look for a keypress */
case sdl_keydown:
/* check the sdlkey values and move change the coords */
switch( event.key.keysym.sym ){
case sdlk_left:
alien_x -= 1;
break;
case sdlk_right:
alien_x += 1;
break;
case sdlk_up:
alien_y -= 1;
break;
case sdlk_down:
alien_y += 1;
break;
default:
break;
}
}
}
}
问题在于你必须按100次左以便得到100次键盘消息,才能向左转100像素。正确的方法是收到事件时设定标志,根据标志来移动。
例3-12 正确的运动控制
/* alien screen coordinates */
int alien_x=0, alien_y=0;
int alien_xvel=0, alien_yvel=0;
.
.
/* initialise sdl and video modes and all that */
.
/* main game loop */
/* check for events */
while( sdl_pollevent( &event ) ){
switch( event.type ){
/* look for a keypress */
case sdl_keydown:
/* check the sdlkey values and move change the coords */
switch( event.key.keysym.sym ){
case sdlk_left:
alien_xvel = -1;
break;
case sdlk_right:
alien_xvel = 1;
break;
case sdlk_up:
alien_yvel = -1;
break;
case sdlk_down:
alien_yvel = 1;
break;
default:
break;
}
break;
/* we must also use the sdl_keyup events to zero the x */
/* and y velocity variables. but we must also be */
/* careful not to zero the velocities when we shouldn't*/
case sdl_keyup:
switch( event.key.keysym.sym ){
case sdlk_left:
/* we check to make sure the alien is moving */
/* to the left. if it is then we zero the */
/* velocity. if the alien is moving to the */
/* right then the right key is still press */
/* so we don't tocuh the velocity */
if( alien_xvel < 0 )
alien_xvel = 0;
break;
case sdlk_right:
if( alien_xvel > 0 )
alien_xvel = 0;
break;
case sdlk_up:
if( alien_yvel < 0 )
alien_yvel = 0;
break;
case sdlk_down:
if( alien_yvel > 0 )
alien_yvel = 0;
break;
default:
break;
}
break;
default:
break;
}
}
.
.
/* update the alien position */
alien_x += alien_xvel;
alien_y += alien_yvel;
如您所见,我们用了两个变量alien_xvel和alien_yvel来表示飞船的运动,并在响应键盘消息时更新它们。