SDL 在游戏中更流畅的移动 [英] SDL Smoother movement in game

查看:36
本文介绍了SDL 在游戏中更流畅的移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的游戏有一个小问题.

I have got a small problem with my game.

这没什么大不了的,但我很想解决这个问题.

It is not a big deal but I'd love to sort this out.

这是我的输入处理函数:

So this is my input processing function:

void MainGame::processInput()
{
    SDL_Event evnt;

    while (SDL_PollEvent(&evnt)) {
        switch (evnt.type) {
        case SDL_QUIT:
            _gameState = GameState::EXIT;
            break;

        case SDL_MOUSEMOTION:
            break;

        case SDL_KEYDOWN:
            switch (evnt.key.keysym.sym) {
                case SDLK_RIGHT:
                    player.movePlayer(1);
                    break;

                case SDLK_LEFT:
                    player.movePlayer(2);
                    break;
            }
        }
    }
}

它工作得很好,但你可以想象,当我按下一个箭头键时,它移动一次(调用一次 player.movePlayer(); 函数)然后暂停一小部分一秒钟,然后继续读取输入.

and it works just fine, but as you can probably imagine, when I press an arrow key, it moves once (calls the player.movePlayer(); function once) then pauses for a fraction of a second and then continues to read input.

我真的不知道如何表达,但我希望你明白我的意思.

I don't really know how to word it but I hope you know what I mean.

当你在 word 中按住任何字母时也可以看到这种效果.

You can also see this effect when you hold any letter in word.

假设您按 W,它会立即显示第一个 W,然后在几分之一秒后显示剩余的,如下所示:

Let's say you press W, it will display the first W instantly and then remaining ones after a fraction of a second something like that:

w wwwwwwwwwwwwwwwwwwwww

w wwwwwwwwwwwwwwwwwwwww

我真的不知道该怎么解释.

I really don't know how to explain it.

那么问题是,有没有办法从键盘读取原始输入,以便立即连续调用该函数?

So the question is, is there a way to read the raw input from the keyboard so the function will be called continuously straight away?

推荐答案

我经常使用这样的代码:

I often use code like this:

bool keyboard[1<<30]; // EDIT: as noted in the comments this code might not be the most efficient

在事件循环中

while (SDL_PollEvent(&evnt)) {
    switch (evnt.type) {
    case SDL_QUIT:
        _gameState = GameState::EXIT;
        break;

    case SDL_MOUSEMOTION:
        break;

    case SDL_KEYDOWN:
        keyboard[evnt.key.keysym.sym] = true;
        break;
    case SDL_KEYUP:
        keyboard[evnt.key.keysym.sym] = false;
        break;
    }
    step();
}

和阶跃函数:

void step() {
  if(keyboard[SDLK_RIGHT]) player.movePlayer(1);
  else if(keyboard[SDLK_LEFT]) player.movePlayer(2);
}

这篇关于SDL 在游戏中更流畅的移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆