我在使用SDL2渲染纹理时遇到问题。在我的程序中,有一堆像素在屏幕上移动,但它们明显闪烁。这是我的代码:
Source.cpp
frameStart = SDL_GetTicks();
screen.update();
// Makes the screen black
for (int x = 0; x < Screen::SCREEN_WIDTH; x++)
{
for (int y = 0; y < Screen::SCREEN_HEIGHT; y++) {
screen.setPixel(x, y, 0, 0, 0);
}
}
// Draw + Update people (Code should be separated and moved)
for (Person &p : people) {
if (p.isAlive == true) {
p.Update(p);
cout << p.x << ", " << p.y << endl;
screen.setPixel(p.x, p.y, 255, 0, 0);
}
else {
screen.setPixel(p.x, p.y, 0, 0, 0);
}
}
// Manage events
if (screen.processEvents() == false) {
break;
}
frameTime = SDL_GetTicks() - frameStart;
if (frameDelay > frameTime) {
SDL_Delay(frameDelay - frameTime);
}
}
Screen.update点在这里:
void Screen::update() {
SDL_UpdateTexture(m_texture, NULL, m_buffer, SCREEN_WIDTH * sizeof(Uint32) );
SDL_RenderCopy(m_renderer, m_texture, NULL, NULL);
SDL_RenderPresent(m_renderer);
SDL_RenderClear(m_renderer);
}
我的渲染器和纹理设置如下:
m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_PRESENTVSYNC);
m_texture = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_STATIC, SCREEN_WIDTH, SCREEN_HEIGHT);
我已经弄乱了很多渲染器和纹理的标志但是没有找到阻止闪烁的解决方案。任何帮助都会非常感激。
答案 0 :(得分:1)
您应遵循的顺序是:
你正在做的基本上是渲染和清晰的方式。 如果你这样做可能工作得很好
frameStart = SDL_GetTicks();
SDL_RenderClear(m_renderer);
/* Do you rendering */
/*Manage your events*/
SDL_RenderPresent(m_renderer);
frameTime = SDL_GetTicks() - frameStart;
if (frameDelay > frameTime) {
SDL_Delay(frameDelay - frameTime);
}
关于渲染像素,在清除纹理时,应该使用更快的memset。但你的方式仍然有效
memset(pixels,0,h*pitch);