How to Create a Sprite using MFC

Objectives

  1. Create a Bitmap
  2. Create a DC in MFC VC++
  3. Tell the DC to draw the bitmap

Technical Points

  1. Load the Bitmap into a Bitmap class
  2. The Bitmap class stores the Original DC Bitmap which will be restored when the class is destoried.
  3. The BitBlt function performs a 1:1 copy of pixels in the Source DC to the Target DC.
  4. StretchBlt function maps the Source DC to fit the dimensions of the Target DC.

OnCreate Event

  pDC = new CClientDC(this);
   
   HDC hdcWindow = pDC->GetSafeHdc();
                     
    // let our class handle the details of loading the bitmaps!
       g_bmpBackground.Load(hdcWindow, "ch2p7_bg.bmp");
   g_bmpSprite.Load(hdcWindow, "ch2p7_purball.bmp");
   g_bmpSpriteMask.Load(hdcWindow, "ch2p7_purball_mask.bmp");

   // release the DC we obtained
   ReleaseDC(pDC);
   delete pDC;
   
   //Set the Milliseconds for each timer event
   SetTimer(1,500,0);


OnDraw Event

 StretchBlt(hdcWindow,
   0, 0, 640, 480,
   g_bmpBackground.GetBitmapDC(), 0, 0,
   g_bmpBackground.GetWidth(),
   g_bmpBackground.GetHeight(), SRCCOPY);


On Timer Event

    CDC *pDC;

     int randomx = RandomNumber(0,640);
     int randomy = RandomNumber(0,480);

    pDC = new CClientDC(this);

    HDC hdcWindow = pDC->GetSafeHdc();

    //redraw the background
    StretchBlt(hdcWindow,0, 0, 640, 480,
    g_bmpBackground.GetBitmapDC(), 0, 0, 640, 480, SRCCOPY);

     // first blit the mask, using SRCAND.
     BitBlt(hdcWindow, randomx, randomy, 640, 480,
       g_bmpSpriteMask.GetBitmapDC(), 0, 0, SRCAND);

     // then blit the image using the OR operator (SRCPAINT).
     BitBlt(hdcWindow, randomx, randomy, 640, 480,
       g_bmpSprite.GetBitmapDC(), 0, 0, SRCPAINT);

      ReleaseDC(pDC);
     delete pDC;

You might also like...

Comments

David Nishimoto NishiSoft provides Part I of the Information Technology Project collaboration. Sign up and list your IT project tasks, assign task too friends, and get percent complete task. Part will include a wo...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Some people, when confronted with a problem, think "I know, I’ll use regular expressions." Now they have two problems.” - Jamie Zawinski