如何使用 SDL 获得持续的用户输入?

How to get constant User Input with SDL?

提问人:Slykapar 提问时间:10/19/2023 最后编辑:Slykapar 更新时间:10/20/2023 访问量:62

问:

我正在尝试使用 SDL 用 C 编写游戏。问题是键盘输入不是恒定的。如果我按下一个键,玩家会移动一步,暂停,然后流畅地移动。这就像我在文本文档中并按住一个键一样。我尝试使用,我也尝试使用然后做,但两者都有相同的问题。 编辑: 这是我的结构:SDL_GetKeyboardState()SDL_PollEvent()event.key.keysym.sym == ...

typedef struct 
{
  SDL_Rect rect;
  bool alive, large;
  float speed;

} Player;

typedef struct
{
  bool running;
  int width, height;
  SDL_Event event;
  Uint8* keystates;
  Player* player;
} Game;

下面是处理输入的函数:

void update(Game* game)
{
  game->keystates = SDL_GetKeyboardState(NULL);


  // set player speed
  game->player->speed = STD_PLAYERSPEED * (game->player->large ? 2 : 1);

  if( SDL_PollEvent(&game->event) > 0 )
  {
    switch(game->event.type)
    {
      case SDL_QUIT:
        game->running = false;
        break;  
    }

    if(game->keystates[SDL_SCANCODE_W])
    {
      game->player->rect.y -= game->player->speed;
    }
    if(game->keystates[SDL_SCANCODE_S])
    {
      game->player->rect.y += game->player->speed;
    }

    if(game->keystates[SDL_SCANCODE_A])
    {
      game->player->rect.x -= game->player->speed;
    }
    if(game->keystates[SDL_SCANCODE_D])
    {
      game->player->rect.x += game->player->speed;
    }
  }
}
C 输入 SDL 游戏开发

评论

1赞 genpfault 10/19/2023
在一个最小的可重复示例中进行编辑,以展示您的尝试。
1赞 HolyBlackCat 10/19/2023
SDL_GetKeyboardState()是您需要的,假设您每帧轮询它(而不是在事件处理程序中)。
0赞 Slykapar 10/19/2023
我每一帧都这样称呼,但我仍然得到相同的结果。
0赞 HolyBlackCat 10/20/2023
那你就做错了。我们会帮助你调试,但你没有分享你的代码。(回复时请添加,否则不会收到通知。@username
0赞 Slykapar 10/20/2023
对不起,我是 Stackoverflow 的新手。@HolyBlackCat我编辑了我的帖子以添加代码。

答:

0赞 Slykapar 10/20/2023 #1

@HolyBlackCat回答: 首先,SDL_PollEvent必须用作 。其次,必须超出此 while/if。 正确代码:while (SDL_PollEvent(...))', not 'if (SDL_PollEvent())if(game->keystates[SDL_SCANCODE_W])

void update(Game* game)
{
  game->keystates = SDL_GetKeyboardState(NULL);


  // set player speed
  game->player->speed = STD_PLAYERSPEED * (game->player->large ? 2 : 1);

  while( SDL_PollEvent(&game->event) > 0 )
  {
    switch(game->event.type)
    {
      case SDL_QUIT:
        game->running = false;
        break;  
    } 
  }

  if(game->keystates[SDL_SCANCODE_W])
  {
    game->player->rect.y -= game->player->speed;
  }
  if(game->keystates[SDL_SCANCODE_S])
  {
    game->player->rect.y += game->player->speed;
  }
  if(game->keystates[SDL_SCANCODE_A])
  {
    game->player->rect.x -= game->player->speed;
  }
  if(game->keystates[SDL_SCANCODE_D])
  {
    game->player->rect.x += game->player->speed;
  }
}