在这里不再放出MyDirectX.h MyDirectX.cpp MyWindows.cpp 代码 只列出修改部分
这一章我们学习使用Direct3D矩阵及一个极为方便D3DX助手函数来旋转、缩放及平移精灵
2D变换
ID3DXSprite可以处理变换矩阵是它的迷人之处。
介绍完成这些功能的变换函数:
D3DXMATRIX *D3DXMatrixTransformation2D(
D3DXMATRIX *pOut,
CONST D3DXVECTOR2 *pScalingCenter,
FLOAT pScalingRotation,
CONST D3DXVECTOR2 *pScaling,
CONST D3DXVECTOR2 *pRotationCenter,
FLOAT Rotation,
CONST D3DXVECTOR2 *pTranslation
);
在DirectX.cpp中增加(在DirectX.h中声明)
void Sprite_Transform_Draw(LPDIRECT3DTEXTURE9 image, int x, int y, int width, int herght, int frame, int columns, float rotation, float scaling, D3DCOLOR color) {
D3DXVECTOR2 scale(scaling, scaling);
D3DXVECTOR2 trans(x, y);
D3DXVECTOR2 center((float)(width*scaling) / 2, (float)(herght*scaling) / 2);
D3DXMATRIX mat;
D3DXMatrixTransformation2D(&mat, NULL, 0, &scale, ¢er, rotation, &trans);
spriteobj->SetTransform(&mat);
int fx = (frame % columns) * width;
int fy = (frame / columns) * herght;
RECT srcRect = { fx,fy,fx + width,fy + herght };
spriteobj->Draw(image, &srcRect, NULL, NULL, color);
}
MyGame.cpp
#include "MyDirectX.h"
using namespace std;
const string APPTITLE = "Sprite Rotation and Scaling Demo";
const int SCREENW = 1024;
const int SCREENH = 768;
LPDIRECT3DTEXTURE9 sunflower;
D3DCOLOR color;
int frame = 0, columns,width,height,startframe,endframe, starttime = 0, dalay;
LPD3DXSPRITE spriteobj = NULL; //定义为null
bool Game_Init(HWND window) {
//initalize Direct3d;
Direct3D_Init(window, SCREENW, SCREENH, false);
DirectInput_Init(window);
sunflower = LoadTexture("F:/sunflower.png");
return true;
}
void Game_Run(HWND window) {
static float scale = 0.001f;
static float r = 0;
static float s = 1.0f;
if (!d3ddev)return;
DirectInput_Update();
d3ddev->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 100), 1.0f, 0);
if (d3ddev->BeginScene()) {
spriteobj->Begin(D3DXSPRITE_ALPHABLEND);
r = timeGetTime() / 600.f;
s += scale;
if (s<0.1 || s>1.24f)scale *= 1;
width = height = 512;
frame = 0;
columns = 1;
color = D3DCOLOR_XRGB(255, 255, 255);
Sprite_Transform_Draw(sunflower, 300, 150, width, height, frame, columns, r, s, color);
spriteobj->End();
d3ddev->EndScene();
d3ddev->Present(NULL, NULL, NULL, NULL);
}
if (Key_Down(VK_ESCAPE))gameover = true;
if (controllers[0].wButtons&XINPUT_GAMEPAD_BACK) gameover = true;
}
void Game_End() {
sunflower->Release();
DirectInput_Shutdown();
Direct3D_Shutdown();
}