我目前正在玩SDL来制作游戏,而我遇到了SDL没有发现某些事件的问题。例如,我会按'w'向前移动,同时,我移动鼠标环顾四周。但是,假设我按“a”或“d”,SDL不会选择这些事件,甚至当我发布'w'时,SDL也不会接收KEYUP事件。我首先在Windows中编写了这个代码并且一切正常,但是在切换到ubuntu之后,它不再像预期的那样工作了。这是我调查事件的主循环:
while(Running)
{
while(SDL_PollEvent(&event))
Events(&event);
if( active ){
Loop();
Render();
}
}
这是Events()中的代码:
switch(Event->type)
{
case SDL_QUIT:
Running = false;
break;
case SDL_KEYDOWN:
switch(Event->key.keysym.sym)
{
case SDLK_ESCAPE:
Running = false;
break;
case SDLK_a:
keyStates['a'] = true;
break;
case SDLK_s:
keyStates['s'] = true;
break;
case SDLK_d:
keyStates['d'] = true;
break;
case SDLK_w:
keyStates['w'] = true;
break;
case SDLK_LSHIFT:
camera.setSpeed(2.0f);
break;
}
break;
case SDL_KEYUP:
switch(Event->key.keysym.sym)
{
case SDLK_a:
keyStates['a'] = false;
break;
case SDLK_s:
keyStates['s'] = false;
break;
case SDLK_d:
keyStates['d'] = false;
break;
case SDLK_w:
keyStates['w'] = false;
break;
case SDLK_LSHIFT:
camera.setSpeed(1.0f);
break;
}
break;
case SDL_MOUSEBUTTONDOWN:
switch(Event->button.button)
{
case SDL_BUTTON_MIDDLE:
mouse.middle = true;
break;
}
break;
case SDL_MOUSEBUTTONUP:
switch(Event->button.button)
{
case SDL_BUTTON_MIDDLE:
mouse.middle = false;
break;
}
break;
case SDL_MOUSEMOTION:
if( moving ){
camera.lookat(float(Event->motion.x - winWidth/2),float(Event->motion.y - winHeight/2), MOUSE_SENSITIVITY, dt);
SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
SDL_WarpMouse(winWidth/2, winHeight/2);
SDL_EventState(SDL_MOUSEMOTION, SDL_ENABLE);
}
break;
}
答案 0 :(得分:1)
keyStates ['a'] = true;
这是SDL_GetKeyState
。使用它而不是手动维护数组。
Uint8 keys[SDLK_LAST];
Uint8* sdlKeys = SDL_GetKeyState(0);
memcpy(keys, sdlKeys, sizeof(keys));
bool keyPressed(SDLKey key){
return keys[key] == SDL_PRESSED;
}
同时检查documentation。