del*_*vas 6 events sdl key input
我想知道如何在SDL中的while循环中检测按键或释放键.现在,我知道你可以使用像OnKeyPressed,OnKeyReleased,OnKeyHit等SDL获取事件,但我想知道如何构建像'KeyPressed'这样的函数,它返回一个布尔值,而不是一个事件.例:
while not KeyHit( KEY_ESC )
{
//Code here
}
Run Code Online (Sandbox Code Playgroud)
Ken*_*son 12
我知道你已经选择了答案..但这里有一些实际的代码,我通常用一个数组来做.:)
首先在某处定义.
bool KEYS[322]; // 322 is the number of SDLK_DOWN events
for(int i = 0; i < 322; i++) { // init them all to false
KEYS[i] = false;
}
SDL_EnableKeyRepeat(0,0); // you can configure this how you want, but it makes it nice for when you want to register a key continuously being held down
Run Code Online (Sandbox Code Playgroud)
然后,创建一个键盘()函数,它将注册键盘输入
void keyboard() {
// message processing loop
SDL_Event event;
while (SDL_PollEvent(&event)) {
// check for messages
switch (event.type) {
// exit if the window is closed
case SDL_QUIT:
game_state = 0; // set game state to done,(do what you want here)
break;
// check for keypresses
case SDL_KEYDOWN:
KEYS[event.key.keysym.sym] = true;
break;
case SDL_KEYUP:
KEYS[event.key.keysym.sym] = false;
break;
default:
break;
}
} // end of message processing
}
Run Code Online (Sandbox Code Playgroud)
然后当你真的想要使用键盘输入即handleInput()函数时,它可能看起来像这样:
void handleInput() {
if(KEYS[SDLK_LEFT]) { // move left
if(player->x - player->speed >= 0) {
player->x -= player->speed;
}
}
if(KEYS[SDLK_RIGHT]) { // move right
if(player->x + player->speed <= screen->w) {
player->x += player->speed;
}
}
if(KEYS[SDLK_UP]) { // move up
if(player->y - player->speed >= 0) {
player->y -= player->speed;
}
}
if(KEYS[SDLK_DOWN]) { // move down
if(player->y + player->speed <= screen->h) {
player->y += player->speed;
}
}
if(KEYS[SDLK_s]) { // shoot
if(SDL_GetTicks() - player->lastShot > player->shotDelay) {
shootbeam(player->beam);
}
}
if(KEYS[SDLK_q]) {
if(player->beam == PLAYER_BEAM_CHARGE) {
player->beam = PLAYER_BEAM_NORMAL;
} else {
player->beam = PLAYER_BEAM_CHARGE;
}
}
if(KEYS[SDLK_r]) {
reset();
}
if(KEYS[SDLK_ESCAPE]) {
gamestate = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
当然,您可以轻松地完成您想要做的事情
while(KEYS[SDLK_s]) {
// do something
keyboard(); // don't forget to redetect which keys are being pressed!
}
Run Code Online (Sandbox Code Playgroud)
**我网站上的更新版本:**为了不发布大量源代码,您可以在C++中查看支持的完整SDL Keyboard类
http://kennycason.com/posts/2009-09-20-sdl-simple-space-shooter-game-demo-part-i.html(如果您有任何问题,请告诉我)
Ano*_*ous 10
有一个 SDL 函数可以实现此目的:SDL_GetKeyboardState
检查左或右 CTRL 键是否被按下的示例:
const Uint8* state = SDL_GetKeyboardState(nullptr);
if (state[SDL_SCANCODE_LCTRL] || state[SDL_SCANCODE_RCTRL]) {
std::cerr << "ctrl pressed" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)