How do I cap rendering of tiles in a 2D game with SDL?

Posted by farmdve on Game Development See other posts from Game Development or by farmdve
Published on 2012-12-12T13:17:35Z Indexed on 2012/12/12 17:20 UTC
Read the original article Hit count: 266

Filed under:
|
|
|
|

I have some boilerplate code working, I basically have a tile based map composed of just 3 colors, and some walls and render with SDL. The tiles are in a bmp file, but each tile inside it corresponds to an internal number of the type of tile(color, or wall). I have pretty basic collision detection and it works, I can also detetc continuous presses, which allows me to move pretty much anywhere I want. I also have a moving camera, which follows the object.

The problem is that, the tile based map is bigger than the resolution, thus not all of the map can be displayed on the screen, but it's still rendered. I would like to cap it, but since this is new to me, I pretty much have no idea.

Although I cannot post all the code, as even though I am a newbie and the code pretty basic, it's already quite a few lines, I can post what I tried to do

void set_camera()
{
    //Center the camera over the dot
    camera.x = ( player.box.x + DOT_WIDTH / 2 ) - SCREEN_WIDTH / 2;
    camera.y = ( player.box.y + DOT_HEIGHT / 2 ) - SCREEN_HEIGHT / 2;

    //Keep the camera in bounds.
    if(camera.x < 0 )
    {
        camera.x = 0;
    }
    if(camera.y < 0 )
    {
        camera.y = 0;
    }
    if(camera.x > LEVEL_WIDTH - camera.w )
    {
        camera.x = LEVEL_WIDTH - camera.w;
    }
    if(camera.y > LEVEL_HEIGHT - camera.h )
    {
        camera.y = LEVEL_HEIGHT - camera.h;
    }
}

set_camera() is the function which calculates the camera position based on the player's positions. I won't pretend I know much about it.

Rectangle box = {0,0,0,0};

for(int t = 0; t < TOTAL_TILES; t++)
{
    if(box.x < (camera.x - TILE_WIDTH) || box.y > (camera.y - TILE_HEIGHT))
        apply_surface(box.x - camera.x, box.y - camera.y, surface, screen, &clips[tiles[t]]);

    box.x += TILE_WIDTH;

    //If we've gone too far
    if(box.x >= LEVEL_WIDTH)
    {
        //Move back
        box.x = 0;

        //Move to the next row
        box.y += TILE_HEIGHT;
    }
}

This is basically my render code. The for loop loops over 192 tiles stored in an int array, each with their own unique value describing the tile type(wall or one of three possible colored tiles).

box is an SDL_Rect containing the current position of the tile, which is calculated on render.

TILE_HEIGHT and TILE_WIDTH are of value 80.

So the cap is determined by

if(box.x < (camera.x - TILE_WIDTH) || box.y > (camera.y - TILE_HEIGHT))

However, this is just me playing with the values and see what doesn't break it. I pretty much have no idea how to calculate it.

My screen resolution is 1024/768, and the tile map is of size 1280/960.

© Game Development or respective owner

Related posts about 2d

Related posts about rendering