SDL_KEYDOWN and key recognition not working properly

会有一股神秘感。 提交于 2019-12-02 18:15:50

问题


In my project I am having trouble getting a simple switch statement to work for SDL input. Here is the example:

SDL_Event event;

SDL_PollEvent(&event);


if (event.type == SDL_KEYDOWN)
{

    switch (event.key.keysym.sym)
    {
    case SDLK_a: m_x -= 30;
            break;
    case SDLK_d: m_x += 30;
            break;
    case SDLK_w: m_y -= 30;
            break;
    case SDLK_s: m_y += 30;
            break;
    }
}

When I run this, first off it seems SDL_KEYDOWN isn't being recognized. Nor are my cases. So I switched the code to:

SDL_Event event;

SDL_PollEvent(&event);


if (event.type == 771)
{

    switch (event.key.keysym.sym)
    {
    case SDLK_a: m_x -= 30;
            break;
    case SDLK_d: m_x += 30;
            break;
    case SDLK_w: m_y -= 30;
            break;
    case SDLK_s: m_y += 30;
            break;
    default: m_y += 1;
    }
}

This causes the default case to run when I hold or press any key, so my object moves according to m_y += 1. If I remove the default case and try pressing w,a,s, or d, nothing happens. If i keep m_y += 1, but use SDL_KEYDOWN instead of 771, nothing happens. (I got the 771 code by printing the event.type whenever a key is being pressed).


回答1:


You call SDL_PollEvent() only once, so it gives the event which occurred first which might not be SDL_KEYDOWN.
You must make a main loop to handle your events:

SDL_Event event;
bool quit=false;    
while(!quit)
{
    while(SDL_PollEvent(&event)
    {
        if(event.type==SDL_KEYDOWN)
        {
             ....
        }
        else if(event.type==SDL_QUIT)
        {
            quit=true;
        }
    }
}

This loop takes care of the events which you don't care about(for e.g. MOUSEMOTION).

And you can also use switch with event.type if you are going to handle many different types of events.



来源:https://stackoverflow.com/questions/26664139/sdl-keydown-and-key-recognition-not-working-properly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!