Search This Blog

Monday, 3 December 2012

Android game development : Moving or scrolling background

In game development in android, before we go further let have a look what we had achieved

    1) Basic science of game programming
    2) Creating surface to draw
    3) Creating dynamic object on surface and moving them

But in general , every game does not move their character much . They moves their background. But when a person plays, its seems everything is moving around. In android we draw an background with one bitmap.  And we start slowly moving background. This is important part game development.

Suppose one's want to develop a game in which, one's have one actor who's running all the way. Then real game scenerio will be like that

  • Animate actor on same place
  • Move the background in opposite direction

Moving background is quite simple, we scroll one image to some position and same image's another instance to respective direction to cover the space left by first one. and so on.......
This process need same image to draw continueously two times to fill the gap and never ending scrolling or moving of background

Look at the respective code in which backGround bitmap is background of canvas.....

  * Draws current state of the game Canvas.
 private int mBGFarMoveX = 0;
 private int mBGNearMoveX = 0;

 private void doDrawRunning(Canvas canvas) {
  // decrement the far background
  mBGFarMoveX = mBGFarMoveX - 1;
  // decrement the near background
  mBGNearMoveX = mBGNearMoveX - 4;
  // calculate the wrap factor for matching image draw
  int newFarX = backGround.getWidth() - (-mBGFarMoveX);
  // if we have scrolled all the way, reset to start
  if (newFarX <= 0) {
   mBGFarMoveX = 0;
   // only need one draw
   canvas.drawBitmap(backGround, mBGFarMoveX, 0, null);
  } else {
   // need to draw original and wrap
   canvas.drawBitmap(backGround, mBGFarMoveX, 0, null);
   canvas.drawBitmap(backGround, newFarX, 0, null);


Download Source

Android News and source code