使用 SDL2 渲染平铺地图的最快方法

Fastest way to render a tiled map with SDL2

本文关键字:方法 地图 SDL2 使用      更新时间:2023-10-16

我正在寻找一种非常快速的方法来使用 SDL2 渲染具有三层的平铺地图。我正在使用SDL_RenderCopy但它很慢...

好的,我已经找到了我需要的东西,所以我会在这里解释一下。

实际上有四个图层,我曾经在一个简单的 for 循环中渲染它们。事实上,for 循环并不是渲染平铺地图的好方法。

最好的方法是在主渲染循环之前将每个图层渲染成一个大纹理,然后将每个大纹理渲染到屏幕上。for 循环需要花费大量时间来处理,但是,渲染大纹理非常快。

看看下面的代码,考虑到"bigTexture"是一个图层,而"width"和"height"是该图层的大小。

Uint32 pixelFormat;
SDL_QueryTexture(tileset, &pixelFormat, NULL, NULL, NULL);
SDL_Texture *bigTexture = SDL_CreateTexture(renderer, pixelFormat, SDL_TEXTUREACCESS_TARGET, width, height);
SDL_SetRenderTarget(renderer, bigTexture);
// Put your for loop here

完成后,我们将图层加载到一个大纹理中。让我们看看如何渲染它。

SDL_SetRenderTarget(renderer, NULL);
// Create a SDL_Rect which defines the big texture's part to display, ie the big texture's part visible in the window.
// Display the big texture with a simple SDL_RenderCopy

就这样。现在,您可以非常快速地渲染平铺地图。