【问题标题】:SDL2 render texture visibly lags behind mouseSDL2 渲染纹理明显滞后于鼠标
【发布时间】:2013-09-04 12:51:36
【问题描述】:

我在 Windows 上使用 SDL2(我已经测试了 Windows 7 和 Windows 8)。我正在尝试渲染锁定到鼠标坐标的纹理以创建一种“十字准线”效果。

它可以工作,但是纹理明显滞后于鼠标,这在鼠标移动和渲染更新之间造成了尴尬的延迟。老实说,延迟非常小,但对于关心绝对准确性的人来说,这会使人发疯。

我的问题基本上是,这正常吗?我猜测延迟是由于 Windows 将事件传递给 SDL,然后 SDL 将事件传递给我所花费的时间。如何通过 SDL 实现锁定的“十字准线”效果?

我的代码供参考:

#include "SDL.h"

int main( int argc, char* args[] ) 
{ 
    SDL_Init( SDL_INIT_EVERYTHING ); 

    SDL_Window* window = SDL_CreateWindow("SDL", 100, 100, 640, 480, SDL_WINDOW_SHOWN);

    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    SDL_Surface* surface = SDL_LoadBMP("mouse.bmp");

    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
    SDL_FreeSurface(surface);

    bool isExiting = false;
    int x = 0;
    int y = 0;

    while(!isExiting)
    {
        SDL_Event e;
        while(SDL_PollEvent(&e))
        {
            if(e.type == SDL_QUIT)
            {
                isExiting = true;
                break;
            }
            else if(e.type == SDL_MOUSEMOTION)
            {
                x = e.motion.x;
                y = e.motion.y;
            }
        }

        SDL_Rect destRect;
        destRect.h = 19;
        destRect.w = 19;
        destRect.x = x;
        destRect.y = y;

        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, texture, NULL, &destRect);
        SDL_RenderPresent(renderer);
    }

    SDL_Quit(); 

    return 0; 
}

【问题讨论】:

  • 您是否启用了Windows compositor?您的主要while 循环是否总是需要大约 16-17 毫秒才能执行?
  • @genpfault 合成已启用。我会在禁用时进行测试。我还没有为循环计时,所以我也必须尝试一下。
  • 您的SDL_Surface 不会以鼠标位置为中心绘制,改为destRect.x = x - ( destRect.w / 2); destRect.y = y - ( destRect.h / 2);
  • @olevegard 我很欣赏您的回复,但这不是问题所在。在鼠标移动和渲染发生之间存在明显的延迟。调整位置不会影响延迟。
  • @JustinSkiles 是的,我知道。我只是注意到它,所以我想指出它。

标签: c++ windows sdl sdl-2


【解决方案1】:

虽然我无法确定您的循环滞后的原因,但 SDL 支持更改鼠标表面以及您可能感兴趣的其他一些功能。看来您可以充分利用 SDL_CreateColorCursor(SDL_Surface* surface, int hot_x, int hot_y)。以下是鼠标支持 wiki 页面的链接:http://wiki.libsdl.org/CategoryMouse

编码愉快!

【讨论】:

    【解决方案2】:

    在我正在进行的一个项目中,我会这样做:

    (在主游戏循环之外):

    SDL_Texture* cursor = //blah;
    SDL_Rect cursor_hitbox;
    SDL_QueryTexture(cursor, NULL, NULL, &cursor_hitbox.w, &cursor_hitbox.h);
    

    (在主游戏循环中):

    SDL_GetMouseState(&cursor_hitbox.x, &cursor_hitbox.y);
    

    在使用它时,我并没有真正注意到任何输入延迟。也许只是事件类型?

    请注意,这很可能效率不高,因为您将在每一帧都获得鼠标状态,而不仅仅是在移动鼠标时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      相关资源
      最近更新 更多