Home Game Development sdl2 – Updating object positions after screen moves. Is there a better way?

sdl2 – Updating object positions after screen moves. Is there a better way?

0
sdl2 – Updating object positions after screen moves. Is there a better way?

[ad_1]

To solve this, you could create a texture the size of your entire map. SDL2 can then render to a texture instead of rendering directly to the screen. Store every object’s position (player, enemies and whatnot) in absolute terms (from the top-left corner of the map), and render everything. Once this is done, you can then render a portion of the map texture to the screen, using SDL_RenderCopy[Ex]:

// at the beginning of the game:
SDL_Texture* world = SDL_CreateTexture(
    renderer,
    PIXEL_FORMAT,
    SDL_TEXTUREACCESS_TARGET, // the most important, allows you to render to this texture.
    worldWidth,
    worldHeight);
SDL_Rect camera = {0, 0, cameraWidth, cameraHeight}; // change x and y to center the camera wherever you'd like it to be

//
// in your game loop
//
SDL_SetRenderTarget(renderer, world); // render everything to the world texture

// render your enemies, player and all
SDL_RenderCopy(renderer, player, NULL, player_rect); // player_rect should hold the position on the map

SDL_SetRenderTarget(render, NULL); // switch back the renderer so that it targets the screen
SDL_RenderCopy(renderer, world, camera, NULL); // this will render only the portion of world that is bound by the camera rectangle.
SDL_RenderPresent(renderer);

this way, you don’t have to offset the position of everything depending on where you camera is. You just render as if the whole map was displayed, and then copy a tiny portion of this.

The only problem with that method is that you will render objects that, in the end, are outside the camera and will not be displayed. to solve that, you can check if an object’s Rect lies in the camera rect with SDL_HasIntersection(&camera, &object_rect);. If not, just by pass SDL_RenderCopy for that object.

[ad_2]