我已经和SDL玩了几天了,虽然我觉得我已经掌握了它,但是我遇到了一个菜单问题。更具体地说,菜单中的按钮。当鼠标移动速度不快时,它们可以完美地工作,但是当我加快速度时(在按钮之间移动光标,不断地将按钮从“普通”精灵重绘为“鼠标悬停精灵”),它会滞后后面,有时根本不更新,小错误开始出现。
这是关于按钮和事件管理的所有代码:
while(!Exit)
{
while(SDL_PollEvent(&Ev))
{
curTime = SDL_GetTicks();
if((ControlVar == 1 && Ev.type == SDL_MOUSEMOTION) || (ControlVar == 1 && Ev.type == SDL_MOUSEBUTTONDOWN) || (ControlVar == 1 && Ev.type == SDL_MOUSEBUTTONUP)) {
But1.doAction();
But2.doAction();
But3.doAction();
if(curTime > lastTime + 25) {
SDL_RenderClear(Screen);
ApplyImage("Menu.png");
But1.Draw();
But2.Draw();
But3.Draw();
SDL_RenderPresent(Screen);
lastTime = SDL_GetTicks();
}
}
if(Ev.type == SDL_QUIT)
Exit = true;
}
SDL_Delay(10);
}
和
class Button {
int Id;
int Clip;
SDL_Rect box;
std::string Filepath;
public:
Button::Button(int number, int X, int Y, std::string filename)
{
Id = number;
Clip = 0;
box.x = X;
box.y = Y;
box.w = 300;
box.h = 40;
Filepath = filename;
}
void Draw()
{
SDL_Texture *tex = nullptr;
SDL_Rect targetRec;
tex = IMG_LoadTexture(Screen, Filepath.c_str());
targetRec.h = 40;
targetRec.w = 300;
targetRec.x = 0;
targetRec.y = Clip * 40;
SDL_RenderCopy(Screen, tex, &targetRec, &box);
SDL_DestroyTexture(tex);
}
void doAction()
{
if(Ev.motion.x > box.x && Ev.motion.x < box.x+box.w && Ev.motion.y > box.y && Ev.motion.y < box.y+box.h)
{
if(Ev.type == SDL_MOUSEMOTION && Clip != 2)
Clip = 1;
if(Ev.type == SDL_MOUSEBUTTONDOWN && Ev.button.button == SDL_BUTTON_LEFT)
Clip = 2;
if(Ev.type == SDL_MOUSEBUTTONUP && Ev.button.button == SDL_BUTTON_LEFT)
Clip = 1;
}
else if(Clip != 0)
Clip = 0;
}
};
答案 0 :(得分:4)
尝试在SDL_RenderPresent(Screen);
循环之外移动while(SDL_PollEvent(&Ev))
。通过调用SDL_RenderPresent,您可能每秒仅轮询60个事件(如果启用了vsync,则每帧一个),导致您看到的延迟。
如果在事件循环之外移动SDL_RenderPresent,您将能够处理队列中可用的任意数量的事件,并在完成后呈现帧并等待vsync。