-1

我开发了一个用 c 编写并使用 SDL 的游戏。在我的主循环中,当我按下一个键时,它处理了不止一次,我想在我打字时及时处理它。我不知道如何解决这个问题 理想情况下,例如,我想每 5 秒限制一次此事件。我怎么能做到这一点?

有我的事件文件

事件.h

    #ifndef __EVENT_H__
    #define __EVENT_H__

#include <SDL/SDL.h>

typedef struct s_event
{
    int mouse_x;
    int mouse_y;
    char    key[SDLK_LAST];
    char    mouse_buttons[8];
    int quit;

}               t_event;

void    loop_events(t_event *input_manager);
void    switcher(SDL_Event *event, t_event *input_manager);
void    event_initialize(t_event *input_manager);


#endif

事件.c

#include "event.h"

void    loop_events(t_event *input_manager)
{
    SDL_Event   event;

    while(SDL_PollEvent(&event))
    {
        switcher(&event, input_manager);
    }
}

void    switcher(SDL_Event *event, t_event *input_manager)
{
        switch (event->type)
        {
        case SDL_KEYDOWN:
            input_manager->key[event->key.keysym.sym]=1;
            break;
        case SDL_KEYUP:
            input_manager->key[event->key.keysym.sym]=0;
            break;
        case SDL_MOUSEMOTION:
            input_manager->mouse_x=event->motion.x;
            input_manager->mouse_y=event->motion.y;
            break;
        case SDL_MOUSEBUTTONDOWN:
            input_manager->mouse_buttons[event->button.button]=1;
            break;
        case SDL_MOUSEBUTTONUP:
            if (event->button.button!=SDL_BUTTON_WHEELUP && event->button.button!=SDL_BUTTON_WHEELDOWN)
                input_manager->mouse_buttons[event->button.button]=0;
            break;
        case SDL_QUIT:
            input_manager->quit = 1;
            break;
        default:
            break;
        }
}

void    event_initialize(t_event *input_manager)
{
    memset(input_manager, 0, sizeof(t_event));
    input_manager->mouse_buttons[SDL_BUTTON_WHEELUP] = 0;
    input_manager->mouse_buttons[SDL_BUTTON_WHEELDOWN] = 0;
}

我的游戏循环

while(!event.key[SDLK_ESCAPE] && !event.quit)
  {
   loop_events(&event);
   move_player(player, &event, world);
   display_world(world, screen);
   fire(player, &event, screen);

   display_player(screen, player, world);
   SDL_Delay(5);
   SDL_Flip(screen);
  }

以及我想在我输入时只处理一次事件的函数

void  fire(t_player *player, t_event *event,  SDL_Surface *screen)
{

  if (event->key[SDLK_SPACE])
  {
    if (count_list(player->weapon_data) == 0)
       weapon_id_counter = 0; 
      t_weapon *new;
       new = malloc(sizeof(t_weapon));
       new->on_launch = bitmap_loader("resources/kirby.bmp");
       new->shape.x = player->shape.x;
       new->shape.y = player->shape.y - player->shape.h;
       new->shape.w = 32;
       new->shape.h = 32;
       printf("FIRRRE");
       new->is_launch = 1;
       new->id =weapon_id_counter++;
       player->weapon_data = add_weapon(new, player->weapon_data);
  }
}
4

1 回答 1

1

第一次按下该键时,保存当前时间。然后,如果在时间限制之前再次按下它,则要么显示错误消息,要么直接忽略该键。

如果时间限制已过,则保存当前时间以进行下一次检查。

于 2013-06-02T15:32:54.133 回答