简体   繁体   English

C ++和SDL:SDL事件不断重复

[英]C++ & SDL: SDL event repeats endlessly

I have this code which is a part of a simple SDL-based game: 我有以下代码,这是一个基于SDL的简单游戏的一部分:

    SDL_PollEvent(&event);
    switch (event.type){
        case SDL_QUIT:
            quit = true;
            break;

        case SDL_KEYDOWN: //Det här är för när en knapp trycks ner...
            switch (event.key.keysym.sym){
                case SDLK_RIGHT:  
                    player1.x_vel = 5.5;
                    std::cout<<"OOOO\n";
                    break;

                case SDLK_DOWN:
                    player2_sprite.src.x = 58;
                    break;
            }

            break;

        case SDL_KEYUP: //Det här är för när en knapp släpps upp..
            switch (event.key.keysym.sym){
                case SDLK_UP:
                    std::cout<<"haaaaa\n";
                    if(player1.canJump){
                        player1.y_vel = -7.5;
                        player1.canJump = false;
                    }
                    break;

                case SDLK_DOWN:
                    std::cout<<"BBBB\n";
                    player2_sprite.src.x = 0;
                    break;
            }

            break;
    }

Now, upon the release of the UP or DOWN arrow key, the release-event keeps triggering forever until any other event is handled. 现在,在释放UP或DOWN箭头键后,释放事件将永远触发,直到处理了其他任何事件为止。 What am I doing wrong here? 我在这里做错了什么?

You should be checking the return value of SDL_PollEvent . 您应该检查SDL_PollEvent的返回值。 It returns 1 if there is an event to handle, and 0 if there is not. 如果有要处理的事件,则返回1,否则返回0。 Normally, you handle events in a loop like this (copied from the documentation here ): 通常,您可以像这样循环处理事件(从此处的文档中复制):

while (1) {
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
         // handle your event here
    }
    // do some other stuff here -- draw your app, etc.
}

What is probably happening in your case, is you are handling the event even when SDL_PollEvent returns 0. The event object is left unmodified in that case, so you keep handling the most recent event over and over. 在您的情况下可能发生的事情是,即使SDL_PollEvent返回0,您也正在处理事件。在这种情况下,事件对象保持不变,因此您一遍又一遍地处理最近的事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM