Jump to content
A 2021 backup has been restored. Forums are closed and work in progress. Join our Discord server for more updates! ×
SoaH City Message Board

[C/C++] Scrolling engines - advice sought.


Recommended Posts

Looking at working on a basic (hah!) 8-way scrolling engine in C/C++. Using SDL here (SDL, SDL_gfx, SDL_image, SDL_Mixer).

Of course, some questions here:

1 - how to actually do the scrolling?

2 - How to then translate the co-ordinates scrolled to on to screen?

3 - how to just display what's needed on screen without rendering the entire level out-of-sight, if feasible?

Not sure if I'm explaining myself clearly enough here...

Link to comment
Share on other sites

To convert from world space coordinates to screen coordinates, it's a matter of simple the substraction of the top-left coordinates of the camera to the object/tile position.

ScreenX = ObjectX - CameraX;
ScreenY = ObjectY - CameraY;

However, when it comes down to determine the visibility of tiles, since they're stored in a 2D array where each tile has the same size, you can easily know wich ranges in the array are visible by translating the world coordinates into tile coordinates

TileMinX = CameraX / TileSize;
TileMaxX = (CameraX + ScreenWidth) / TileSize;
TileMinY = CameraY / TileSize;
TileMaxY = (CameraY + ScreenHeight) / TileSize;

So those are the coordinates wich you need to render on screen. Of course, depending on the scroll values, it might interesting to add 1 to the MaxX so you also render tiles that are in between.

Code example for a simple scroller:

#define MAX_WIDTH  Whatever
#define MAX_HEIGHT Whatever
#define MAX_TILES  Whatever
#define TILE_SIZE  Whatever

unsigned short LevelWidth;
unsigned short LevelHeight;
unsigned short Level[MAX_HEIGHT][MAX_WIDTH];
SDL_Surface * Tileset[MAX_TILES];

void RenderMap(SDL_Surface * Output, int CameraX, int CameraY)
{
    // Determine ranges
    int MinX = CameraX / TILE_SIZE;
    int MinY = CameraY / TILE_SIZE;
    int MaxX = (CameraX+Output->width) / TILE_SIZE + 1;
    int MaxY = (CameraY+Output->height) / TILE_SIZE + 1;

    // Clip if out of range
    if (MinX < 0) MinX = 0;
    if (MinY < 0) MinY = 0;
    if (MaxX >= LevelWidth) MaxX = LevelWidth - 1;
    if (MaxY >= LevelHeight) MaxY = LevelHeight - 1;

    // Iterate through the level array
    for (int y = MinY; y < MaxY; y++)
    {
        for (int x = MinX; x < MaxX; x++)
        {
            // Determine if the tile we're about to draw is the transparent tile. If so, skip.
            if (Level[y][x] == 0) continue;

            // Render
            RenderImage(Tileset[Level[y][x]], Output, x * TILE_SIZE - CameraX, y * TILE_SIZE - CameraY);
        }
    }
}

void RenderImage(SDL_Surface * Input, SDL_Surface * Output, int x, int y)
{
    ....
}

  • Like 1
Link to comment
Share on other sites

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...