动画子画面是通过循环播放一系列帧图像来获得动画效果。为了向引擎添加动画子画面,修改代码如下。
向Bitmap.cpp添加DrawPart()方法,该方法允许只绘制子画面位图图像的一部分,从而支持帧动画。
- void Bitmap::DrawPart(HDC hDC, int x, int y, int xPart, int yPart,
- int wPart, int hPart, BOOL bTrans, COLORREF crTransColor)
- {
- if (m_hBitmap != NULL)
- {
- // Create a memory device context for the bitmap
- HDC hMemDC = CreateCompatibleDC(hDC);
- // Select the bitmap into the device context
- HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, m_hBitmap);
- // Draw the bitmap to the destination device context
- if (bTrans)
- TransparentBlt(hDC, x, y, wPart, hPart, hMemDC, xPart, yPart,
- wPart, hPart, crTransColor);
- else
- BitBlt(hDC, x, y, wPart, hPart, hMemDC, xPart, yPart, SRCCOPY);
- // Restore and delete the memory device context
- SelectObject(hMemDC, hOldBitmap);
- DeleteDC(hMemDC);
- }
- }
须保持原来程序的可用性,修改Draw()方法。
- void Bitmap::Draw(HDC hDC, int x, int y, BOOL bTrans, COLORREF crTransColor)
- {
- DrawPart(hDC, x, y, 0, 0, GetWidth(), GetHeight(), bTrans, crTransColor);
- }
增加Sprite.h的成员变量。
- int m_iNumFrames,m_iCurFrame; //帧数,当前帧
- int m_iFrameDelay,m_iFrameTrigger; //帧延迟,帧触发器
Sprite()构造函数初始化这些成员变量。
- m_iNumFrames=1; //默认帧数为1
- m_iCurFrame=m_iFrameDelay=m_iFrameTrigger=0;
Sprite.h中增加一些成员函数。
- //设置子画面的帧数
- inline void Sprite::SetNumFrames(int iNumFrames)
- {
- //设置帧数
- m_iNumFrames = iNumFrames;
- //重新计算位置
- RECT rect = GetPosition();
- rect.bottom = rect.top + ((rect.bottom - rect.top)/iNumFrames);
- SetPosition(rect);
- }
- //更新子画面的当前动画帧
- inline void Sprite::UpdateFrame()
- {
- if((m_iFrameDelay>=0)&&(--m_iFrameTrigger<=0))
- {
- //重置帧触发器
- m_iFrameTrigger = m_iFrameDelay;
- //将帧加1
- if(++m_iCurFrame>=m_iNumFrames)
- m_iCurFrame=0;
- }
- }
- //设置帧延迟
- void SetFrameDelay(int iFrameDelay) { m_iFrameDelay = iFrameDelay; };
- //新的GetHeight()方法
- int GetHeight() { return ( m_pBitmap->GetHeight()/m_iNumFrames );}
自然同时要修改Sprite.cpp
- SPRITEACTION Sprite::Update()
- {
- //更新帧
- UpdateFrame();
- ...
- }
- void Sprite::Draw(HDC hDC)
- {
- // Draw the sprite if it isn't hidden
- if (m_pBitmap != NULL && !m_bHidden)
- {
- //如有必要,绘制适当的帧
- if(m_iNumFrames==1)
- m_pBitmap->Draw(hDC, m_rcPosition.left, m_rcPosition.top, TRUE);
- else
- m_pBitmap->DrawPart(hDC,m_rcPosition.left,m_rcPosition.top,
- 0,m_iCurFrame*GetHeight(),GetWidth(),GetHeight(),TRUE);
- }
- }