提问人:Slykapar 提问时间:10/19/2023 最后编辑:Slykapar 更新时间:10/20/2023 访问量:62
如何使用 SDL 获得持续的用户输入?
How to get constant User Input with SDL?
问:
我正在尝试使用 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;
}
}
}
答:
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;
}
}
上一个:动态更改输入到输出
评论
SDL_GetKeyboardState()
是您需要的,假设您每帧轮询它(而不是在事件处理程序中)。@username