- Online Community Forums » Programming Questions » overhead scrolling

This thread is locked; no one can reply to it. rss feed Print
overhead scrolling
Dr. Locke Z2A
Member #7,503
July 2006

I don't really understand how to implement overhead scrolling in 2D games. From what I understand it works like if I were to press the left arrow key then the camera would move right and the character would move left an equal ammount to show the camera moving but keeping the character in the center of the screen. How correct am I on that? Also, I don't know how moving the camera a given direction would be translated into code, so could someone enlighten me as to how to do that?

Member #6,239
September 2005

That would be paralax scrolling. You've got the general idea right, though. You just need to keep a few variables to keep track of the "camera" x,y position, as well as the background's offset. When you move left or right, the camera's x position is increased/decreased by a rate of 1 * speed, and the offset by a rate of 2 * speed. When drawing, you want to draw everything in relation to the camera.

If you don't understand that, then you might get this. Let's assume your screen is setup in 800*600. Your map goes from 0,0 to 2000,4000. When you move right, the camera's X variable would increase...Let's just say you moved it 100 pixels. If you wanted to draw something in the camera's view, it would be the object's X variable - 100 (camera's X value), right? You should also make sure an object is within the view( > camx && < camx + screen_w ) before trying to draw it, since if it's offscreen it won't be drawn anyways. Likewise, you need to make sure that you do not move the camera below 0, or above 2000, since those are the map's boundaries.

I realize I'm probably rambling a bit, but maybe some code would help.

Move the screen:

1if( key[KEY_RIGHT] )
3 // do animation
4 if( (camx - MOVE_SPEED) < MAP_W )
5 {
6 camx += MOVE_SPEED;
7 bgxoffset = (bgxoffset + 2*MOVE_SPEED) % bgtile->w;
8 }
9 else
10 camx = MAP_W;
12else if( key[KEY_LEFT] )
14 // do animation
15 if( (camx + MOVE_SPEED) > 0 )
16 {
17 camx -= MOVE_SPEED;
18 bgxoffset = (bgxoffset - 2*MOVE_SPEED) % bgtile->w;
19 }
20 else
21 camx = 0;

Draw background:

void DrawBackground(BITMAP *dest, BITMAP *bg)
  // draw a tiled background, offset by camx,camy
  for(int b = 0; b < (SCREEN_H / bg->h); b++)
    for(int a = 0; a < (SCREEN_W / bg->w); a++)
      blit(bg, dest, 0, 0, a * bg->w - (camx % bg->w) + bgxoffset, b * bg->h - (camy % bg->h) + bgyoffset, bg->w, bg->h);

Draw our player

void DrawPlayer(BITMAP *dest, Player *pl)
  masked_blit(pl->Sprite, dest, 0, 0, pl->x - camx, pl->y - camy, pl->Sprite->w, pl->Sprite->h);

My code may contain errors, but you get the rough idea.

SolarStrike Software - MicroMacro home - Automation software.

Go to: