游戏编程入门之精灵旋转和缩放(旋转行走的向日葵、行走的人物)
代码:
MyDirectX.h:
1 #pragma once 2 //header files 3 #define WIN32_EXTRA_LEAN 4 #define DIRECTINPUT_VERSION 0x0800 5 #include <windows.h> 6 #include <d3d9.h> 7 #include <d3dx9.h> 8 #include <dinput.h> 9 #include <xinput.h> 10 #include <ctime> 11 #include <iostream> 12 #include <iomanip> 13 using namespace std; 14 15 //libraries 16 #pragma comment(lib,"winmm.lib") 17 #pragma comment(lib,"user32.lib") 18 #pragma comment(lib,"gdi32.lib") 19 #pragma comment(lib,"dxguid.lib") 20 #pragma comment(lib,"d3d9.lib") 21 #pragma comment(lib,"d3dx9.lib") 22 #pragma comment(lib,"dinput8.lib") 23 #pragma comment(lib,"xinput.lib") 24 25 //program values 26 extern const string APPTITLE; 27 extern const int SCREENW; 28 extern const int SCREENH; 29 extern bool gameover; 30 31 //macro to detect key presses 32 #define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0) 33 34 //Direct3D objects 35 extern LPDIRECT3D9 d3d; 36 extern LPDIRECT3DDEVICE9 d3ddev; 37 extern LPDIRECT3DSURFACE9 backbuffer; 38 extern LPD3DXSPRITE spriteobj; 39 40 //Direct3D functions 41 bool Direct3D_Init(HWND hwnd, int width, int height, bool fullscreen); 42 void Direct3D_Shutdown(); 43 LPDIRECT3DSURFACE9 LoadSurface(string filename); 44 void DrawSurface(LPDIRECT3DSURFACE9 dest, float x, float y, LPDIRECT3DSURFACE9 source); 45 D3DXVECTOR2 GetBitmapSize(string filename); 46 LPDIRECT3DTEXTURE9 LoadTexture(string filename, D3DCOLOR transcolor = D3DCOLOR_XRGB(0, 0, 0)); 47 void Sprite_Draw_Frame(LPDIRECT3DTEXTURE9 texture, int destx, int desty, int framenum, int framew, int frameh, int columns); 48 void Sprite_Animate(int &frame, int startframe, int endframe, int direction, int &starttime, int delay); 49 50 //DirectInput objects, devices, and states 51 extern LPDIRECTINPUT8 dinput; 52 extern LPDIRECTINPUTDEVICE8 dimouse; 53 extern LPDIRECTINPUTDEVICE8 dikeyboard; 54 extern DIMOUSESTATE mouse_state; 55 extern XINPUT_GAMEPAD controllers[4]; 56 57 //DirectInput functions 58 bool DirectInput_Init(HWND); 59 void DirectInput_Update(); 60 void DirectInput_Shutdown(); 61 bool Key_Down(int); 62 int Mouse_Button(int); 63 int Mouse_X(); 64 int Mouse_Y(); 65 void XInput_Vibrate(int contNum = 0, int amount = 65535); 66 bool XInput_Controller_Found(); 67 68 //game functions 69 bool Game_Init(HWND window); 70 void Game_Run(HWND window); 71 void Game_End(); 72 void Sprite_Transform_Draw(LPDIRECT3DTEXTURE9 image, int x, int y, int width, int height, int frame = 0, int columns = 1, float rotation = 0.0f, float scaling = 1.0f, D3DCOLOR color = D3DCOLOR_XRGB(255, 255, 255));
MyDirectX.cpp:
1 #include "MyDirectX.h" 2 #include <iostream> 3 using namespace std; 4 5 //Direct3D variables 6 LPDIRECT3D9 d3d = NULL; 7 LPDIRECT3DDEVICE9 d3ddev = NULL; 8 LPDIRECT3DSURFACE9 backbuffer = NULL; 9 LPD3DXSPRITE spriteobj; 10 11 //DirectInput variables 12 LPDIRECTINPUT8 dinput = NULL; 13 LPDIRECTINPUTDEVICE8 dimouse = NULL; 14 LPDIRECTINPUTDEVICE8 dikeyboard = NULL; 15 DIMOUSESTATE mouse_state; 16 char keys[256]; 17 XINPUT_GAMEPAD controllers[4]; 18 19 20 bool Direct3D_Init(HWND window, int width, int height, bool fullscreen) 21 { 22 //initialize Direct3D 23 d3d = Direct3DCreate9(D3D_SDK_VERSION); 24 if (!d3d) return false; 25 26 //set Direct3D presentation parameters 27 D3DPRESENT_PARAMETERS d3dpp; 28 ZeroMemory(&d3dpp, sizeof(d3dpp)); 29 d3dpp.hDeviceWindow = window; 30 d3dpp.Windowed = (!fullscreen); 31 d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; 32 d3dpp.EnableAutoDepthStencil = 1; 33 d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8; 34 d3dpp.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL; 35 d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; 36 d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8; 37 d3dpp.BackBufferCount = 1; 38 d3dpp.BackBufferWidth = width; 39 d3dpp.BackBufferHeight = height; 40 41 //create Direct3D device 42 d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, window, 43 D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev); 44 if (!d3ddev) return false; 45 46 47 //get a pointer to the back buffer surface 48 d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer); 49 50 //create sprite object 51 D3DXCreateSprite(d3ddev, &spriteobj); 52 53 return 1; 54 } 55 56 void Direct3D_Shutdown() 57 { 58 if (spriteobj) spriteobj->Release(); 59 60 if (d3ddev) d3ddev->Release(); 61 if (d3d) d3d->Release(); 62 } 63 64 void DrawSurface(LPDIRECT3DSURFACE9 dest, float x, float y, LPDIRECT3DSURFACE9 source) 65 { 66 //get width/height from source surface 67 D3DSURFACE_DESC desc; 68 source->GetDesc(&desc); 69 70 //create rects for drawing 71 RECT source_rect = { 0, 0, (long)desc.Width, (long)desc.Height }; 72 RECT dest_rect = { (long)x, (long)y, (long)x + desc.Width, (long)y + desc.Height }; 73 74 //draw the source surface onto the dest 75 d3ddev->StretchRect(source, &source_rect, dest, &dest_rect, D3DTEXF_NONE); 76 77 } 78 79 LPDIRECT3DSURFACE9 LoadSurface(string filename) 80 { 81 LPDIRECT3DSURFACE9 image = NULL; 82 83 //get width and height from bitmap file 84 D3DXIMAGE_INFO info; 85 HRESULT result = D3DXGetImageInfoFromFile(filename.c_str(), &info); 86 if (result != D3D_OK) 87 return NULL; 88 89 //create surface 90 result = d3ddev->CreateOffscreenPlainSurface( 91 info.Width, //width of the surface 92 info.Height, //height of the surface 93 D3DFMT_X8R8G8B8, //surface format 94 D3DPOOL_DEFAULT, //memory pool to use 95 &image, //pointer to the surface 96 NULL); //reserved (always NULL) 97 98 if (result != D3D_OK) return NULL; 99 100 //load surface from file into newly created surface 101 result = D3DXLoadSurfaceFromFile( 102 image, //destination surface 103 NULL, //destination palette 104 NULL, //destination rectangle 105 filename.c_str(), //source filename 106 NULL, //source rectangle 107 D3DX_DEFAULT, //controls how image is filtered 108 D3DCOLOR_XRGB(0, 0, 0), //for transparency (0 for none) 109 NULL); //source image info (usually NULL) 110 111 //make sure file was loaded okay 112 if (result != D3D_OK) return NULL; 113 114 return image; 115 } 116 117 118 D3DXVECTOR2 GetBitmapSize(string filename) 119 { 120 D3DXIMAGE_INFO info; 121 D3DXVECTOR2 size = D3DXVECTOR2(0.0f, 0.0f); 122 123 HRESULT result = D3DXGetImageInfoFromFile(filename.c_str(), &info); 124 125 if (result == D3D_OK) 126 size = D3DXVECTOR2((float)info.Width, (float)info.Height); 127 else 128 size = D3DXVECTOR2((float)info.Width, (float)info.Height); 129 130 return size; 131 } 132 133 LPDIRECT3DTEXTURE9 LoadTexture(std::string filename, D3DCOLOR transcolor) 134 { 135 LPDIRECT3DTEXTURE9 texture = NULL; 136 137 //get width and height from bitmap file 138 D3DXIMAGE_INFO info; 139 HRESULT result = D3DXGetImageInfoFromFile(filename.c_str(), &info); 140 if (result != D3D_OK) return NULL; 141 142 //create the new texture by loading a bitmap image file 143 D3DXCreateTextureFromFileEx( 144 d3ddev, //Direct3D device object 145 filename.c_str(), //bitmap filename 146 info.Width, //bitmap image width 147 info.Height, //bitmap image height 148 1, //mip-map levels (1 for no chain) 149 D3DPOOL_DEFAULT, //the type of surface (standard) 150 D3DFMT_UNKNOWN, //surface format (default) 151 D3DPOOL_DEFAULT, //memory class for the texture 152 D3DX_DEFAULT, //image filter 153 D3DX_DEFAULT, //mip filter 154 transcolor, //color key for transparency 155 &info, //bitmap file info (from loaded file) 156 NULL, //color palette 157 &texture); //destination texture 158 159 //make sure the bitmap textre was loaded correctly 160 if (result != D3D_OK) return NULL; 161 162 return texture; 163 } 164 165 166 bool DirectInput_Init(HWND hwnd) 167 { 168 //initialize DirectInput object 169 DirectInput8Create( 170 GetModuleHandle(NULL), 171 DIRECTINPUT_VERSION, 172 IID_IDirectInput8, 173 (void**)&dinput, 174 NULL); 175 176 //initialize the keyboard 177 dinput->CreateDevice(GUID_SysKeyboard, &dikeyboard, NULL); 178 dikeyboard->SetDataFormat(&c_dfDIKeyboard); 179 dikeyboard->SetCooperativeLevel(hwnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND); 180 dikeyboard->Acquire(); 181 182 //initialize the mouse 183 dinput->CreateDevice(GUID_SysMouse, &dimouse, NULL); 184 dimouse->SetDataFormat(&c_dfDIMouse); 185 dimouse->SetCooperativeLevel(hwnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND); 186 dimouse->Acquire(); 187 d3ddev->ShowCursor(false); 188 189 return true; 190 } 191 192 void DirectInput_Update() 193 { 194 //update mouse 195 dimouse->Poll(); 196 if (!SUCCEEDED(dimouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouse_state))) 197 { 198 //mouse device lose, try to re-acquire 199 dimouse->Acquire(); 200 } 201 202 //update keyboard 203 dikeyboard->Poll(); 204 if (!SUCCEEDED(dikeyboard->GetDeviceState(256, (LPVOID)&keys))) 205 { 206 //keyboard device lost, try to re-acquire 207 dikeyboard->Acquire(); 208 } 209 210 //update controllers 211 for (int i = 0; i< 4; i++) 212 { 213 ZeroMemory(&controllers[i], sizeof(XINPUT_STATE)); 214 215 //get the state of the controller 216 XINPUT_STATE state; 217 DWORD result = XInputGetState(i, &state); 218 219 //store state in global controllers array 220 if (result == 0) controllers[i] = state.Gamepad; 221 } 222 } 223 224 225 int Mouse_X() 226 { 227 return mouse_state.lX; 228 } 229 230 int Mouse_Y() 231 { 232 return mouse_state.lY; 233 } 234 235 int Mouse_Button(int button) 236 { 237 return mouse_state.rgbButtons[button] & 0x80; 238 } 239 240 bool Key_Down(int key) 241 { 242 return (bool)(keys[key] & 0x80); 243 } 244 245 246 void DirectInput_Shutdown() 247 { 248 if (dikeyboard) 249 { 250 dikeyboard->Unacquire(); 251 dikeyboard->Release(); 252 dikeyboard = NULL; 253 } 254 if (dimouse) 255 { 256 dimouse->Unacquire(); 257 dimouse->Release(); 258 dimouse = NULL; 259 } 260 } 261 262 bool XInput_Controller_Found() 263 { 264 XINPUT_CAPABILITIES caps; 265 ZeroMemory(&caps, sizeof(XINPUT_CAPABILITIES)); 266 XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &caps); 267 if (caps.Type != 0) return false; 268 269 return true; 270 } 271 272 void XInput_Vibrate(int contNum, int amount) 273 { 274 XINPUT_VIBRATION vibration; 275 ZeroMemory(&vibration, sizeof(XINPUT_VIBRATION)); 276 vibration.wLeftMotorSpeed = amount; 277 vibration.wRightMotorSpeed = amount; 278 XInputSetState(contNum, &vibration); 279 } 280 void Sprite_Draw_Frame(LPDIRECT3DTEXTURE9 texture, int destx, int desty, int framenum, int framew, int frameh, int columns) 281 { 282 D3DXVECTOR3 position((float)destx, (float)desty, 0); 283 D3DCOLOR white = D3DCOLOR_XRGB(255, 255, 255); 284 285 RECT rect; 286 rect.left = (framenum % columns) * framew; 287 rect.top = (framenum / columns) * frameh; 288 rect.right = rect.left + framew; 289 rect.bottom = rect.top + frameh; 290 291 spriteobj->Draw(texture, &rect, NULL, &position, white); 292 } 293 294 void Sprite_Animate(int &frame, int startframe, int endframe, int direction, int &starttime, int delay) 295 { 296 if ((int)GetTickCount() > starttime + delay) 297 { 298 starttime = GetTickCount(); 299 300 frame += direction; 301 if (frame > endframe) frame = startframe; 302 if (frame < startframe) frame = endframe; 303 } 304 } 305 void Sprite_Transform_Draw(LPDIRECT3DTEXTURE9 image, int x, int y, int width, int height, int frame, int columns, float rotation, float scaling, D3DCOLOR color) 306 { 307 //create a scale vector 308 D3DXVECTOR2 scale(scaling, scaling); 309 //create a translate vector 310 D3DXVECTOR2 trans(x, y); 311 //set center by dividing width and height by two 312 D3DXVECTOR2 center((float)(width * scaling) / 2, (float)(height * scaling) / 2); 313 //create 2D transformation matrix 314 D3DXMATRIX mat; 315 D3DXMatrixTransformation2D(&mat, NULL, 0, &scale, ¢er, rotation, &trans); 316 317 //tell sprite object to use the transform 318 spriteobj->SetTransform(&mat); 319 //calculate frame location in source image 320 int fx = (frame % columns) * width; 321 int fy = (frame / columns) * height; 322 RECT srcRect = { fx, fy, fx + width, fy + height }; 323 //draw the sprite frame 324 spriteobj->Draw(image, &srcRect, NULL, NULL, color); 325 }
MyGame.cpp:
1 #include "MyDirectX.h" 2 3 const string APPTITLE = "Sprite Rotation and Scaling Demo"; 4 const int SCREENW = 1024; 5 const int SCREENH = 768; 6 LPDIRECT3DTEXTURE9 sunflower; 7 D3DCOLOR color; 8 int frame = 0, columns, width, height; 9 int starttime = 0, startframe, endframe, delay; 10 11 bool Game_Init(HWND window) 12 { 13 //initialize Direct3D 14 if (!Direct3D_Init(window, SCREENW, SCREENH, false)) 15 { 16 MessageBox(0, "Error initializing Direct3D", "ERROR", 0); 17 return false; 18 } 19 20 //initialize DirectInput 21 if (!DirectInput_Init(window)) 22 { 23 MessageBox(0, "Error initializing DirectInput", "ERROR", 0); 24 return false; 25 } 26 //load the sprite images 27 sunflower = LoadTexture("sunflower.bmp"); 28 return true; 29 } 30 31 void Game_Run(HWND window) 32 { 33 static float scale = 0.001f; 34 static float r = 0; 35 static float s = 1.0f; 36 //make sure the Direct3D device is valid 37 if (!d3ddev) return; 38 39 //update input devices 40 DirectInput_Update(); 41 42 //clear the scene 43 d3ddev->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 100), 1.0f, 0); 44 45 //start rendering 46 if (d3ddev->BeginScene()) 47 { 48 //begin sprite rendering 49 spriteobj->Begin(D3DXSPRITE_ALPHABLEND); 50 //set rotation and scaling 51 r = timeGetTime() / 600.0f; 52 s += scale; 53 if (s<0.1 || s>1.25f) scale *= -1; 54 //draw sprite 55 width = height = 512; 56 frame = 0; 57 columns = 1; 58 color = D3DCOLOR_XRGB(255, 255, 255); 59 Sprite_Transform_Draw(sunflower, 300, 150, width, height, frame, columns, r, s, color); 60 //stop sprite rendering 61 spriteobj->End(); 62 63 //stop rendering 64 d3ddev->EndScene(); 65 d3ddev->Present(NULL, NULL, NULL, NULL); 66 } 67 68 //Escape key ends program 69 if (KEY_DOWN(VK_ESCAPE)) gameover = true; 70 71 //controller Back button also ends 72 if (controllers[0].wButtons & XINPUT_GAMEPAD_BACK) 73 gameover = true; 74 } 75 76 void Game_End() 77 { 78 //free memory and shut down 79 sunflower->Release(); 80 81 DirectInput_Shutdown(); 82 Direct3D_Shutdown(); 83 }
MyWindows.cpp:
1 #include "MyDirectX.h" 2 using namespace std; 3 bool gameover = false; 4 5 6 LRESULT WINAPI WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) 7 { 8 switch (msg) 9 { 10 case WM_DESTROY: 11 gameover = true; 12 PostQuitMessage(0); 13 return 0; 14 } 15 return DefWindowProc(hWnd, msg, wParam, lParam); 16 } 17 18 19 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) 20 { 21 //initialize window settings 22 WNDCLASSEX wc; 23 wc.cbSize = sizeof(WNDCLASSEX); 24 wc.style = CS_HREDRAW | CS_VREDRAW; 25 wc.lpfnWndProc = (WNDPROC)WinProc; 26 wc.cbClsExtra = 0; 27 wc.cbWndExtra = 0; 28 wc.hInstance = hInstance; 29 wc.hIcon = NULL; 30 wc.hCursor = LoadCursor(NULL, IDC_ARROW); 31 wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); 32 wc.lpszMenuName = NULL; 33 wc.lpszClassName = APPTITLE.c_str(); 34 wc.hIconSm = NULL; 35 RegisterClassEx(&wc); 36 37 //create a new window 38 HWND window = CreateWindow(APPTITLE.c_str(), APPTITLE.c_str(), 39 WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 40 SCREENW, SCREENH, NULL, NULL, hInstance, NULL); 41 if (window == 0) return 0; 42 43 //display the window 44 ShowWindow(window, nCmdShow); 45 UpdateWindow(window); 46 47 //initialize the game 48 if (!Game_Init(window)) return 0; 49 50 // main message loop 51 MSG message; 52 while (!gameover) 53 { 54 if (PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) 55 { 56 TranslateMessage(&message); 57 DispatchMessage(&message); 58 } 59 60 //process game loop 61 Game_Run(window); 62 } 63 64 //shutdown 65 Game_End(); 66 return message.wParam; 67 }
运行结果:
如果将MyWindows.cpp改成下面:
1 #include "MyDirectX.h" 2 3 const string APPTITLE = "Sprite Rotation and Animation Demo"; 4 const int SCREENW = 1024; 5 const int SCREENH = 768; 6 LPDIRECT3DTEXTURE9 paladin = NULL; 7 D3DCOLOR color = D3DCOLOR_XRGB(255, 255, 255); 8 float scale = 0.004f; 9 float r = 0; 10 float s = 1.0f; 11 int frame = 0, columns, width, height; 12 int starttime = 0, startframe, endframe, delay; 13 14 bool Game_Init(HWND window) 15 { 16 //initialize Direct3D 17 if (!Direct3D_Init(window, SCREENW, SCREENH, false)) 18 { 19 MessageBox(0, "Error initializing Direct3D", "ERROR", 0); 20 return false; 21 } 22 23 //initialize DirectInput 24 if (!DirectInput_Init(window)) 25 { 26 MessageBox(0, "Error initializing DirectInput", "ERROR", 0); 27 return false; 28 } 29 //load the sprite sheet 30 paladin = LoadTexture("paladin_walk.png"); 31 if (!paladin) { 32 MessageBox(window, "Error loading sprite", "ERROR", 0); 33 return false; 34 } 35 return true; 36 } 37 38 void Game_Run(HWND window) 39 { 40 //make sure the Direct3D device is valid 41 if (!d3ddev) return; 42 43 //update input devices 44 DirectInput_Update(); 45 46 //clear the scene 47 d3ddev->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 100), 1.0f, 0); 48 49 //start rendering 50 if (d3ddev->BeginScene()) 51 { 52 //begin sprite rendering 53 spriteobj->Begin(D3DXSPRITE_ALPHABLEND); 54 //set rotation and scaling 55 s += scale; 56 if (s<0.5f || s>6.0f) scale *= -1; 57 //set animation properties 58 width = height = 96; 59 startframe = 24; 60 columns = 8; 61 endframe = 31; 62 delay = 90; 63 Sprite_Animate(frame, startframe, endframe, 1, starttime, delay); 64 //transform and draw sprite 65 Sprite_Transform_Draw(paladin, 300, 200, width, height, frame, columns, 0, s, color); 66 //stop sprite rendering 67 spriteobj->End(); 68 69 //stop rendering 70 d3ddev->EndScene(); 71 d3ddev->Present(NULL, NULL, NULL, NULL); 72 } 73 74 //Escape key ends program 75 if (KEY_DOWN(VK_ESCAPE)) gameover = true; 76 77 //controller Back button also ends 78 if (controllers[0].wButtons & XINPUT_GAMEPAD_BACK) 79 gameover = true; 80 } 81 82 void Game_End() 83 { 84 //free memory and shut down 85 paladin->Release(); 86 87 DirectInput_Shutdown(); 88 Direct3D_Shutdown(); 89 }
那么: