Here is another example,
Create a texture / .bmp file that contains 2x tiles that are 32 * 32 pixels each
Your .bmp file dimensions should be 64 X 32
#include <SDL2/SDL.h>
static SDL_Texture* loadTexture(SDL_Renderer *renderer, const char* filePath) {
SDL_Surface* surface(SDL_LoadBMP(filePath));
if (surface) {
SDL_Texture* texture(SDL_CreateTextureFromSurface(renderer, surface));
if (texture) {
printf("Texture loaded successfully: %s\n", filePath);
return texture;
}
printf("Failed to create texture: %s\n", filePath);
return nullptr;
}
printf("Cannot find texture file: %s\n", filePath);
return nullptr;
}
int main(int argc, char* args[] ) {
bool quit = false;
const int32_t kRow = 5;
const int32_t kCol = 10;
const int32_t tileSize = 32;
SDL_Texture* texture = nullptr;
int32_t level[kRow][kCol] = {
{1,0,1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0,1,0}
};
SDL_Init( SDL_INIT_EVERYTHING );
SDL_Window* window = SDL_CreateWindow( "", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 320, 160, 0 );
SDL_Renderer* renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED );
// You may need to change the filepath to point to where your texture is located
texture = loadTexture(renderer, "../tex.bmp");
SDL_Event e;
while (!quit) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
quit = true;
}
}
SDL_RenderClear(renderer);
for (int32_t r = 0; r < kRow; ++r) {
for (int32_t c = 0; c < kCol; ++c) {
// Gets the tile position
const SDL_Rect dstRect = {c * tileSize, r * tileSize, tileSize, tileSize};
// Gets tileID from the texture we need to draw
const SDL_Rect srcRect = {level[r][c] * tileSize, 0, tileSize, tileSize};
SDL_RenderCopy(renderer, texture, &srcRect, &dstRect);
}
}
SDL_RenderPresent(renderer);
}
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}