Getting Started with Game programming (14): Creating a Sprite background

Source: Internet
Author: User
Tags rand

This chapter shows you how to create a common background class for use in the game.

This chapter includes: 4 types of backgrounds How to add a background to the game engine how to use an animated background with animated sprite to simulate an interstellar space

Getting Started with Game programming (13): Implementing Sprite Appearance Animation Understanding the type of game background

The following are 4 main background types : Solid background image background animation background scrolling background solid color background

A solid background is a background with only a solid color and is less used in the game . For example, if you are developing a football game, create a pure green background to indicate that the grass on the field is OK, but using a grass-textured image will do much better, and this does not require more development work.

a solid color background is useful when you are testing a game . For example, if you have a game that contains a complex background image, the sprites are easy to mix together, and it's easier to adjust these sprites when you view them on a simple background. By using a strong contrast-solid background to temporarily replace the background image, you can easily understand the picture and modify the problems of the sprites. Image Background

The image background is a step closer than a solid color background, which uses a bitmap image instead of a solid color to represent the background of the game. Readers have used the image background in the game developed earlier, so they want readers to know what they are for.

the main job of using an image background is to create the image itself , from the programming standpoint that the bitmap bitmap class in the game engine has handled most of the work using the image background.

The problem with image backgrounds is that they are static, which means they don't move. For example, getting started with game programming (7): Using Sprite animation to move an object's planets instance using the galactic background, if the Milky Way can rotate a little, and sometimes produce a meteor, then this background will be more real. One way to improve the image background is to use an animated background. Animation Background

An animated background is a background that changes its appearance over time in a way that resembles an animated sprite. However, the animation background does not necessarily involve a series of frame images . Creating an animated background that animates through custom code is entirely possible.

the key to implementing an animated background is to provide a mechanism to update and draw the background . Scrolling Background

A scrolling background is an image or a group of drawing objects that are fluttering or scrolling on the screen . The best way to understand the scrolling background is to imagine a much larger background than the game screen, which means that the game screen provides a view that looks at a part of the background. To see other parts of the background, you must scroll the view to another part.

The above picture shows a part of the game screen that shows only a larger background. This background is used in a lot of adventure games , and players control a character moving around in a large virtual world. As the reader might think, developing a scrolling background is much more complicated than developing other types of backgrounds because they involve much more game logic. For example, the background must respond when the player moves the role, not to mention that you must also move the sprites so that they appear to scroll with the background. Not only that, the scrolling background often has to be able to surround itself so that the character does not touch the boundary.

one of the most interesting scrolling backgrounds used in 2D games is the background of parallax scrolling, which is a background that scrolls at different rolling speeds, and also requires the use of multilayer background images for parallax scrolling. such as the buildings in the foreground, the trees in the middle view and the mountains in the background. The idea is to give people an illusion of depth by moving each image at different speeds. Therefore, because the mountains are farthest away, they move the slowest, the trees move faster, and the buildings move the fastest. This simulates the moving effect that we observe in the real world as we pass through objects of different distances. Add background support to the game engine

We're not going to create a scrolling background at the moment, so now we just need to combine 3 different backgrounds in the game engine: a solid color background, an image background, and an animated background. It is easy to implement the first two backgrounds in a separate class, but a third background (animation background) requires one of its own custom classes. So, we're going to create two new classes that will be part of the game engine.

The first class is a basic background class that includes a solid background and an image background, while the second class contains a specific animated background type, using a blinking star to display a starry night sky. A background full of stars is enough to show how to create an animated background. Create a basic background class (solid background and image background)

The basic background classes that support solid-color backgrounds and image backgrounds are included in the Background class . The Background class is flexible, and you can use this class to create two backgrounds, which are determined by the constructor used to create which background.

The following is the code for the Backgound class:

Class Background
{
protected:
  //member variable
  int       m_iwidth, m_iheight;//background width and height
  colorref  m_ Crcolor;          Background color
  bitmap*   m_pbitmap;          Background bitmap public

:
  //constructor/destructor
          Background (int iwidth, int iheight, COLORREF crcolor);/solid Background
          Background (bitmap* pbitmap);                          Image background
  virtual ~background ();

  General method
  virtual void  Update ();       Update the background appearance
  virtual void  Draw (HDC HDC);  Draw background

  //access Method
  int getwidth ()  
  {return
      m_iwidth; 
  };
  int getheight () 
  {return 
      m_iheight; 
  }
;};

Here 's a look at the specific code for the Background () constructor and destructor:

Create a solid-color background
background::background (int iwidth, int iheight, COLORREF crcolor)
{
  //Initialize member variable
  m_iwidth = iwidth;
  M_iheight = iheight;
  M_crcolor = Crcolor;
  M_pbitmap = NULL;
}

Create a bitmap background
background::background (bitmap* pbitmap)
{
  //Initialize member variable
  m_crcolor = 0;
  M_pbitmap = Pbitmap;
  M_iwidth = Pbitmap->getwidth ();
  M_iheight = Pbitmap->getheight ();
}

Background::~background ()
{
}

the Background update () and draw () methods are as follows:

-----------------------------------------------------------------
//Background Conventional methods
//--------------- --------------------------------------------------

//update background
void Background::update ()
{
  // Because the basic background doesn't use animations, so don't do anything
}

//Draw background
void Background::D raw (HDC HDC)
{
  if (m_pbitmap!= NULL)   // Bitmap background
    m_pbitmap->draw (hDC, 0, 0);
  else                     //solid background (draw a rectangle with a solid color brush)
  {
    RECT    RECT = {0, 0, m_iwidth, m_iheight};
    Hbrush  hbrush = CreateSolidBrush (m_crcolor);
    FillRect (HDC, &rect, hbrush);
    DeleteObject (Hbrush);
  }
Create an animated background class

we create a specific animated background class, Starrybackground class, which represents the animated background of a starry sky.

The Starrybackground class is derived from the Background class , which means that it inherits the member variables and methods of the Background class. However, the Starrybackground class also requires its own constructors and its own update () and Draw () methods. The Starrybackground class also adds new member variables to manage the flashing stars in the background.

The Starrybackground class is defined as follows:

-----------------------------------------------------------------
//Starry Background star Animation background class
//------ -----------------------------------------------------------
class Starrybackground:background
{
Protected:
  //member variable
  int       m_inumstars;        Number of stars
  int       m_itwinkledelay;    The frequency of the stars flashing, the longer the delay, the more slowly flashing point     m_ptstars[100];     The position of each star
  COLORREF  m_crstarcolors[100];//The colors of each star public

:
  //constructor/destructor
          Starrybackground (int iwidth, int iheight, int inumstars = m,
            int itwinkledelay = x);
  Virtual ~starrybackground ();

  General method
  virtual void  Update ();
  virtual void  Draw (HDC HDC);

the constructors and destructors for the Starrybackground class are as follows:

-----------------------------------------------------------------
//Starrybackground constructors/Destructors
//---- -------------------------------------------------------------
starrybackground::starrybackground (int iwidth , int iheight, int inumstars,
  int itwinkledelay): Background (iwidth, iheight, 0)
{
  //Initialize member variable
  m_ inumstars = min (inumstars);
  M_itwinkledelay = Itwinkledelay;

  Create the Star for
  (int i = 0; i < inumstars i++)
  {
    m_ptstars[i].x = rand ()% Iwidth;
    M_PTSTARS[I].Y = rand ()% Iheight;
    M_crstarcolors[i] = RGB (128, 128, 128);
  }

Starrybackground::~starrybackground ()
{
}

the update () and Draw () methods for Starrybackground are as follows:

-----------------------------------------------------------------
//Starrybackground Conventional methods
//--------- --------------------------------------------------------
void Starrybackground::update ()
{
  // Randomly change the grayscale of the stars so that they blink
  int irgb;
  for (int i = 0; i < m_inumstars i++)
    if ((rand ()% m_itwinkledelay) = = 0)
    {
      Irgb = rand ()% 256;
      M_crstarcolors[i] = RGB (Irgb, Irgb, Irgb); As long as red, blue, green Three colors equal, the stars are
    Gray
}

void Starrybackground::D raw (HDC HDC)
{
  //Draw pure black background
  RECT    rect = {0, 0, m_iwidth, m_iheight};
  Hbrush  hbrush = CreateSolidBrush (RGB (0, 0, 0));
  FillRect (HDC, &rect, hbrush);
  DeleteObject (hbrush);

  Draw stars for
  (int i = 0; i < m_inumstars i++)
    setpixel (HDC, m_ptstars[i].x, M_ptstars[i].y, M_crstarcolors[i) );
}

The draw () method of the Starrybackground class is used to draw the background and then draw each star. The black background is drawn by calling FillRect (). The loop is followed by a call to SetPixel () to draw a single star each moment.

SetPixel () is a Win32 function that sets a single pixel to the specified color. Development Roids Sample

The Roids program simulates a planetary space, displaying several animated planetary sprites on an animated star background.

Note: If a compilation error occurs, add the Msimg32.lib winmm.lib roids directory structure and Effect diagram in the project setup-> connection-> object/library module

roids directory structure:

Roids Effect Chart:
(Planet dynamic Scrolling, background stars flashing)

Write game Code Roids.h

#pragma once

//-----------------------------------------------------------------
//Include files
//--------- --------------------------------------------------------
#include <windows.h>
#include "Resource.h "
#include" "GameEngine.h" #include "Bitmap.h"
#include "Sprite.h"
#include "Background.h"

//-- ---------------------------------------------------------------//
global variable
//---------------------------- -------------------------------------
hinstance         g_hinstance;       Program instance handle
gameengine*       g_pgame;           Game engine pointer
HDC               G_HOFFSCREENDC;    Screen external device Environment
hbitmap           g_hoffscreenbitmap;//bitmap
bitmap*           g_pasteroidbitmap;//planetary bitmap (for creating animated sprites)
starrybackground* G_pbackground;     Star Animation background
Gamestart ()
Start game void Gamestart (HWND hwindow) {//Generate random number generation seed Srand (GetTickCount ());
  Create a screen-outside device environment and bitmap G_HOFFSCREENDC = CreateCompatibleDC (GetDC (Hwindow));
  G_hoffscreenbitmap = CreateCompatibleBitmap (GetDC (Hwindow), G_pgame->getwidth (), G_pgame->getheight ());

  SelectObject (G_HOFFSCREENDC, G_hoffscreenbitmap);
  Create and load a planetary bitmap HDC HDC = GetDC (Hwindow);

  G_pasteroidbitmap = new Bitmap (HDC, idb_asteroid, g_hinstance);

  Create a background full of stars G_pbackground = new Starrybackground (500, 400);
  Create planetary Sprites RECT Rcbounds = {0, 0, 500, 400};
  Sprite* Psprite;
  Psprite = new Sprite (G_pasteroidbitmap, Rcbounds, ba_wrap);
  Psprite->setnumframes (14);
  Psprite->setframedelay (1);
  Psprite->setposition (250, 200);
  Psprite->setvelocity (-3, 1);
  G_pgame->addsprite (Psprite);
  Psprite = new Sprite (G_pasteroidbitmap, Rcbounds, ba_wrap);
  Psprite->setnumframes (14);
  Psprite->setframedelay (2);
  Psprite->setposition (250, 200);
 Psprite->setvelocity (3,-2); G_pgame->addsprite (Psprite);
  Psprite = new Sprite (G_pasteroidbitmap, Rcbounds, ba_wrap);
  Psprite->setnumframes (14);
  Psprite->setframedelay (3);
  Psprite->setposition (250, 200);
  Psprite->setvelocity (-2,-4);
G_pgame->addsprite (Psprite); }

Note that the frame number of each sprite is set to 14, indicating that 14 frames are stored in the image of the planet. In addition, the frame delay settings for each sprite are also different, so that the planets appear to roll at different speeds. Gamepaint ()

Draw game
void Gamepaint (HDC HDC)
{
  //Draw background
  G_pbackground->draw (HDC);

  Draws a sprite
  g_pgame->drawsprites (HDC);
gamecycle ()
Game cycle
void Gamecycle ()
{
  //update background
  g_pbackground->update ();

  Update Sprite
  g_pgame->updatesprites ();

  Get the device environment for redrawing the game
  HWND  Hwindow = G_pgame->getwindow ();
  HDC   HDC = GetDC (Hwindow);

  Draw Game
  Gamepaint (G_HOFFSCREENDC) on the screen outside the device environment;

  Transfer the on-screen bitmap block to the game screen
  BitBlt (hDC, 0, 0, g_pgame->getwidth (), G_pgame->getheight (),
    g_hoffscreendc, 0, 0, srccopy);

  Clear
  ReleaseDC (Hwindow, HDC);
}
Source code Download

Http://pan.baidu.com/s/1ge2Vzr1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.