Download as pdf or txt
Download as pdf or txt
You are on page 1of 130

9/2/2012

Mn hc: Lp trnh GAME


i hc Bch khoa Tp.HCM Khoa Khoa hc v K thut My tnh GV: Nguyn Chnh Thnh
(Chanh.Thanh@Yahoo.Com.Vn, 090 845 0063)
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 1

Yu cu chung
Hnh thc tnh im
Tng im bi tp 70%: bt1: 5%, bt2: 15%, bt3: 20%, bt4: 20%, bt5: 35%, bt6: 5% im bi thi cui k 30%

Mt s lu :
V hng cho sinh vin nm bt k thut cn bn nht ca ngnh lp trnh game, nn mong mun mi sinh vin s lm c tt c cc bi tp nu ra. Nn s i theo hng c nhn 45 tit/mn, 3 tit/bui --> Tun hc 1 bui l thuyt (a s thi gian l thc hnh nh). Bi thi cui k lm trn giy

Yu cu i vi sinh vin:
hon tt 2 mn: Cu trc d liu & gii thut, ha my tnh (chn tng im trung bnh 2 mn t trn xung) Ti a 25 sv / lp Phi c my tnh c nhn (v thc hnh nh l chnh).
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 2

9/2/2012

M rng
Sinh vin c th dng cc ngn ng lp trnh thc hin bi tp / thc hnh
Java C# VB.Net C++ MFC C++ SDK (mc nh dng trong bi ging ny)

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

Bi tp / Thc hnh

Microsoft Office Word 97 - 2003 Document

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

References - Books
Beginning Game Programming, Second Edition, Jonathan S. Harbour, Thomson Course Technology, 2007 Advanced 2D Game Development, Jonathan S. Harbour, Course Technology, 2009 Introduction to 3D Game Programming with DirectX 9.0, Frank D. Luna, Wordware Publishing, Inc, 2003. Game Programming All in One, Bruno Miguel Teixeira de Sousa, Premier Press, 2002 Beginning C# Game Programming, Thomson Course Technology PTR, 2005 3D Game Engine Design, David H. Eberly, Morgan Kaufmann Publisher
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 5

Reference - Internet
http://www.gamedev.net/ http://nehe.gamedev.net/ http://www-csstudents.stanford.edu/~amitp/gameprog.html https://sites.google.com/site/sbskit/gamefornewbie http://www.cprogramming.com/tutorial/game_programmi ng http://devmaster.net/posts

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

Content
Windows Programming
Environment Introduction Windows Programming Windows Messaging & Event Handling The Real-Time Game Loop

Advanced Topics
Building a 2D Game Engine 2D Rendering Animation Physics Math

Game with DirectX Programming


DirectX Graphics Program Bitmaps and Surfaces Drawing Animated Sprites Advanced Sprite Programming Jamming with DirectX Audio Handling Input Devices Tile-Based Scrolling Backgrounds

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

WINDOWS PROGRAMMING

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

Environment Introduction

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

Visual C++ 6.0

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

10

9/2/2012

Visual C++ .Net

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

11

Compilation process
Taking a source code file, compiles it, and then linking it into an executable.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

12

9/2/2012

DirectX Working

What DirectX does to simplify the hardware interface is countered by an extremely large and complex set of features
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 13

Multi-Tasking
Non-preemptive multi- Preemptive multitasking tasking

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

14

9/2/2012

Multi-Threading

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

15

Direct X

The primary components of DirectX 9 DirectX, an alternative to the slow GDI, still relies on the Windows API
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 16

9/2/2012

Windows Programming

Creating a Win32 Understanding WinMain The Complete WinMain

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

17

Creating a Win32 app (1)

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

18

9/2/2012

Creating a Win32 app (2)

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

19

Creating a Win32 app (3)

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

20

10

9/2/2012

Creating a Win32 app (4)


// HelloWorld program #include <windows.h> int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { MessageBox(NULL, "Motoko Kusanagi has hacked your system!", "Public Security Section 9", MB_OK | MB_ICONEXCLAMATION); }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

21

Understanding WinMain (1)

WinMain and WinProc work hand-in-hand to handle application events (such as painting the screen and responding to mouse clicks).
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 22

11

9/2/2012

Understanding WinMain (2)


int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
hInstance tells the program which instance is trying to run. hPrevInstance identifies the previous instance of the program and is related to the first parameter. If hPrevInstance is NULL, then this is the first instance of the program lpCmdLine is a string that contains the command-line parameters passed to the program. This could be used to tell the program to use certain options, such as debug, which might be used to dump program execution to a text file. nCmdShow specifies how the program window is to be displayed.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

23

The Complete WinMain


The while loop in this part of WinMain will
int WINAPI WinMain(HINSTANCE hInstance, continue to run forever unless a message to HINSTANCE hPrevInstance, LPSTR lpCmdLine, kill the program comes along. int nCmdShow) { // declare variables BOOL GetMessage(LPMSG lpMsg, HWND hWnd, MSG msg; UINT wMsgFilterMin, UINT wMsgFilterMax): // register the class - lpMsg: is a long pointer to a MSG structure MyRegisterClass(hInstance); which handles the message information. // initialize application - hWnd: is a handle to a specific windows if (!InitInstance (hInstance, nCmdShow)) messages. If NULL is passed, then GetMessage return FALSE; will return all of the messages for the current // main message loop instance of the program. while (GetMessage(&msg, NULL, 0, 0)) -wMsgFilterMin and wMsgFilterMax: tell Get{ Message to return messages in a certain range. TranslateMessage(&msg); DispatchMessage(&msg); The GetMessage call is the most crucial line of } return msg.wParam; code in the entire Windows program! Without } this single line in WinMain, your program will be

9/2/2012

sensory-deprived, unable to respond to the world. Khoa Khoa hc v K thut My tnh HBK Tp.HCM

24

12

9/2/2012

Windows Messaging & Event Handling

Understanding InitInstance Understanding MyRegisterClass Understanding WinProc

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

25

WindowTest program
Source code at below

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

26

13

9/2/2012

Understanding InitInstance
BOOL InitInstance( HINSTANCE hInstance, int nCmdShow )
hInstance is passed by WinMain with the program instance that it receives from Windows. InitInstance will check this with the global instance to see if the new instance needs to be killed (the usual procedure in Windows). When this happens, the main instance of the program is set as the foreground window. To the user, it will seem as if running the program again just brought the original instance forward. nCmdShow is passed to InitInstance by WinMain, which receives the parameter from Windows. The most common values for this parameter include SW_HIDE and SW_SHOW, and are often sent by Windows based on events in the operating system (such as a power down).
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 27

Understanding MyRegisterClass
ATOM MyRegisterClass(HINSTANCE hInstance) { //create the window class structure WNDCLASSEX wc; wc.cbSize = sizeof(WNDCLASSEX); //fill the struct with info wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC)WinProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(WHIT E_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = APPTITLE; wc.hIconSm = NULL; //set up the window with the class info return RegisterClassEx(&wc); }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

28

14

9/2/2012

Understanding WinProc
LRESULT CALLBACK WinProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
hWnd is the window handle. Typically in a game, you will create a new handle to a device context, known as a hDC, using the hWnd as a parameter. Before DirectX came along, this was once crucial in the development of Windows games. message is the message that is being sent to the window callback procedure. The message could be anything, and you might not even need to use it. For this reason, there is a way to pass the message along to the default message handler (discussed in the next section). wParam and lParam are the high and low bit value parameters passed along with certain command messages.
Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

29

The Real-Time Game Loop

Real-Time Game Loop The GameLoop Project Source Code for the GameLoop Program

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

30

15

9/2/2012

Real-Time Game Loop (1)

The standard WinMain is not friendly to a real-time game loop.

The newly modified WinMain is much more friendly to a real-time game loop.

9/2/2012

PeekMessage: this function can look at incoming messages without Khoa Khoa hcof v the K thu t My tnh queue necessarily retrieving them out message
HBK Tp.HCM

31

Real-Time Game Loop (2)


BOOL PeekMessage(LPMSG lpMsg, HWND hWnd ,UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg);
lpMsg is a pointer to the message structure that describes the message (type, parameters, and so on). hWnd is a handle to the window that is associated with the event. wMsgFilterMin is the first message that has been received. wMsgFilterMax is the last message that has been received. wRemoveMsg is a flag that determines how the message will be handled after it has been read. This can be PM_NOREMOVE to leave the message in the message queue, or PM_REMOVE to remove the message from the queue after it has been read.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

32

16

9/2/2012

Real-Time Game Loop (3)


Plugging PeekMessage into WinMain while (TRUE) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { //look for quit message if (msg.message = = WM_QUIT) break; //decode and pass messages on to WndProc TranslateMessage(&msg); DispatchMessage(&msg); } //process game loop regardless of Windows messages! Game_Run(); }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

33

The GameLoop Project (1)


Creating a new Win32 Application project called GameLoop

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

34

17

9/2/2012

The GameLoop Project (2)


Adding the winmain.cpp file to the project

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

35

The GameLoop Project (3)


#include <windows.h> #include <winuser.h> #include <stdio.h> #include <stdlib.h> #include <time.h> //the window event callback function LRESULT CALLBACK WinProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hWnd, message, wParam, lParam); } //helper function to set up the window properties ATOM MyRegisterClass(HINSTANCE hInstance) { //set up the window with the class info return RegisterClassEx(&wc); } //helper function to create the window and refresh it BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { //display the window ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } //entry point for a Windows program int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int done = 0; MSG msg; // register the class MyRegisterClass(hInstance); // initialize application if (!InitInstance (hInstance, nCmdShow)) return FALSE; //initialize the game Game_Init(); // main message loop while (!done) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { //look for quit message if (msg.message == WM_QUIT) done = 1; //decode and pass messages on to WndProc TranslateMessage(&msg); DispatchMessage(&msg); } //process game loop Game_Run(); } //do cleanup Game_End(); return msg.wParam; }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

36

18

9/2/2012

The GameLoop Project (4)


void Game_Init() { //initialize the game... //load bitmaps, meshes, textures, sounds, etc. //initialize the random number generator srand(time(NULL)); } void Game_End() { } void Game_Run() { //this is called once every frame //do not include your own loop here! int x = 0, y = 0; RECT rect; GetClientRect(global_hwnd, &rect); if (rect.right > 0) { x = rand() % (rect.right - rect.left); y = rand() % (rect.bottom - rect.top); DrawBitmap(global_hdc, "c.bmp", x, y); } }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

37

The GameLoop Project (5)


void DrawBitmap(HDC hdcDest, char *filename, int x, int y) { HBITMAP image; BITMAP bm; HDC hdcMem; //load the bitmap image image = (HBITMAP)LoadImage(0,"c.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); //read the bitmaps properties GetObject(image, sizeof(BITMAP), &bm); //create a device context for the bitmap hdcMem = CreateCompatibleDC(global_hdc); SelectObject(hdcMem, image); //draw the bitmap to the window (bit block transfer) BitBlt( global_hdc, //destination device context x, y, //x,y location on destination bm.bmWidth, bm.bmHeight, //width,height of source bitmap hdcMem, //source bitmap device context 0, 0, //start x,y on source bitmap SRCCOPY); //blit method //delete the device context and bitmap DeleteDC(hdcMem); DeleteObject((HBITMAP)image); }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

38

19

9/2/2012

The GameLoop Project (6)

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

39

GAMES WITH DIRECTX PROGRAMMING


Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

40

20

9/2/2012

DirectX Graphics Program

The Direct3D Interfaces Creating the Direct3D Object Taking Direct3D for a Spin Direct3D in Fullscreen Mode

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

41

The Direct3D Interfaces


IDirect3D9 is an interface; LPDIRECT3D9 is a long pointer to this interface. IDirect3DDevice9 is an interface, LPDIRECT3DDEVICE9 is a long pointer to this interface. Using #include <d3d9.h> Creating the variables like this:
LPDIRECT3D9 d3d = NULL; LPDIRECT3DDEVICE9 d3ddev = NULL;
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 42

21

9/2/2012

Creating the Direct3D Object


d3d = Direct3DCreate9(D3D_SDK_VERSION); d3d->CreateDevice( D3DADAPTER_DEFAULT, //use default video card D3DDEVTYPE_HAL, //use the hardware renderer hWnd, //window handle D3DCREATE_SOFTWARE_VERTEXPROCESSING, //do not use T&L (for compatibility) &d3dpp, //presentation parameters &d3ddev); //pointer

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

43

Direct3D Presentation Parameters

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

44

22

9/2/2012

Taking Direct3D for a Spin (1)


The Project Properties dialog for the d3d_windowed project in Microsoft Visual C++

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

45

Taking Direct3D for a Spin (2)


Opening the Link tab in the Project Properties dialog

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

46

23

9/2/2012

Taking Direct3D for a Spin (3)


Adding d3d9.lib to the Additional Dependencies field.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

47

Taking Direct3D for a Spin (4)


#include <d3d9.h> #include <time.h> LRESULT WINAPI WinProc(HWND,UINT,WPARAM,LPARAM); ATOM MyRegisterClass(HINSTANCE); int Game_Init(HWND); void Game_Run(HWND); void Game_End(HWND); LPDIRECT3D9 d3d = NULL; LPDIRECT3DDEVICE9 d3ddev = NULL; //entry point for a Windows program int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { //initialize the game if (!Game_Init(hWnd)) return 0; // main message loop int done = 0; while (!done) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { //look for quit message if (msg.message == WM_QUIT) { MessageBox(hWnd, "Received WM_QUIT message", "WinMain", MB_OK); done = 1; } //decode and pass messages on to WndProc TranslateMessage(&msg); DispatchMessage(&msg); } else //process game loop (else prevents running after window is closed) Game_Run(hWnd); } return msg.wParam; }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

48

24

9/2/2012

Taking Direct3D for a Spin (5)


int Game_Init(HWND hwnd) { //display init message MessageBox(hwnd, "Program is about to start", "Game_Init", MB_OK); //initialize Direct3D d3d = Direct3DCreate9(D3D_SDK_VERSION); if (d3d == NULL) { MessageBox(hwnd, "Error initializing Direct3D", "Error", MB_OK); return 0; } //set Direct3D presentation parameters D3DPRESENT_PARAMETERS d3dpp; ZeroMemory(&d3dpp, sizeof(d3dpp)); d3dpp.Windowed = TRUE; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; //create Direct3D device d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING , &d3dpp, &d3ddev); if (d3ddev == NULL) { MessageBox(hwnd, "Error creating Direct3D device", "Error", MB_OK); return 0; } //set random number seed srand(time(NULL)); //return okay return 1; }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

49

Taking Direct3D for a Spin (6)


void Game_Run(HWND hwnd) { //make sure the Direct3D device is valid if (d3ddev == NULL) return; //clear the screen with a green color d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,255,255), 1.0f, 0); //start rendering if (d3ddev->BeginScene()) { //do something here! //stop rendering d3ddev->EndScene(); } //display the back buffer on the screen d3ddev->Present(NULL, NULL, NULL, NULL); }
9/2/2012

void Game_End(HWND hwnd) { //display close message MessageBox(hwnd, "Program is about to end", "Game_End", MB_OK); //release the Direct3D device if (d3ddev != NULL) d3ddev->Release(); //release the Direct3D object if (d3d != NULL) d3d->Release(); }

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

50

25

9/2/2012

Direct3D in Fullscreen Mode (1)


screen resolution
#define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 480

macros to read the keyboard asynchronously


#define KEY_DOWN(vk_code) ((GetAsyncKeyState (vk_code) & 0x8000) ? 1 : 0) #define KEY_UP(vk_code)((GetAsyncKeyState (vk_code) & 0x8000) ? 1 : 0)

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

51

Direct3D in Fullscreen Mode (2)


create a new window hWnd = CreateWindow( APPTITLE, //window class APPTITLE, //title bar WS_EX_TOPMOST | WS_VISIBLE | WS_POPUP, //window style CW_USEDEFAULT, //x position of window CW_USEDEFAULT, //y position of window SCREEN_WIDTH, //width of the window SCREEN_HEIGHT, //height of the window NULL, //parent window NULL, //menu hInstance, //application instance NULL); //window parameters

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

52

26

9/2/2012

Direct3D in Fullscreen Mode (3)


Changing the Presentation Parameters
d3dpp.Windowed = TRUE; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;

Example
d3dpp.Windowed = FALSE; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8; d3dpp.BackBufferCount = 1; d3dpp.BackBufferWidth = SCREEN_WIDTH; d3dpp.BackBufferHeight = SCREEN_HEIGHT; d3dpp.hDeviceWindow = hwnd;
Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

53

Direct3D in Fullscreen Mode (4)


check for escape key (to exit program)
if (KEY_DOWN(VK_ESCAPE)) PostMessage(hwnd, WM_DESTROY, 0, 0);

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

54

27

9/2/2012

Bitmaps and Surfaces

Introduction The Create_Surface Example Loading Bitmaps from Disk The Load_Bitmap Program

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

55

Introduction

The monitor displays the linear array of pixels sent to it by the video card

A typical monitor The frame buffer in VRAM contains the image that is rendered on the monitor
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 56

28

9/2/2012

Surfaces
Both the front and back buffers are created for you when you configure the presentation parameters and call CreateDevice Primary Surfaces
front buffer, which makes sense in that the back buffer is copied to it during each frame

Secondary / Offscreen Surfaces


just an array in memory that looks like a bitmap (where it has a header and then data representing pixels) these surfaces are copied to the screen in a process called bit-block transfer.
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 57

Creating a Surface
LPDIRECT3DSURFACE9 surface = NULL; d3ddev->ColorFill(surface, NULL, D3DCOLOR_XRGB(255,0,0)); HRESULT ColorFill(IDirect3DSurface9 *pSurface, CONST RECT *pRect, D3DCOLOR color);

9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 58

29

9/2/2012

Drawing the Surface (Blitting) (1)


d3ddev->StretchRect(surface, NULL, backbuffer, NULL, D3DTEXF_NONE); rect.left = 100; rect.top = 90; rect.right = 200; rect.bottom = 180; d3ddev->StretchRect(surface, NULL, backbuffer, &rect, D3DTEXF_NONE); HRESULT StretchRect(IDirect3DSurface9 *pSourceSurface, CONST RECT *pSourceRect, IDirect3DSurface9 *pDestSurface, CONST RECT *pDestRect, D3DTEXTUREFILTERTYPE Filter );
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 59

Drawing the Surface (Blitting) (2)


LPDIRECT3DSURFACE9 backbuffer = NULL; d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer); HRESULT GetBackBuffer(UINT iSwapChain, UINT BackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9 **ppBackBuffer);

9/2/2012

The Create_Surface program copies random rectangles from an offscreen surface to the screen
Khoa Khoa hc v K thut My tnh HBK Tp.HCM 60

30

9/2/2012

The Create_Surface Example (1)


//header files to include #include <d3d9.h> #include <time.h> //screen resolution #define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 480 int Game_Init(HWND); void Game_Run(HWND); void Game_End(HWND); //Direct3D objects LPDIRECT3D9 d3d = NULL; LPDIRECT3DDEVICE9 d3ddev = NULL; LPDIRECT3DSURFACE9 backbuffer = NULL; LPDIRECT3DSURFACE9 surface = NULL; //window event callback function LRESULT WINAPI WinProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {} //helper function to set up the window properties ATOM MyRegisterClass(HINSTANCE hInstance) { } //entry point for a Windows program int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {}

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

61

The Create_Surface Example (2)


int Game_Init(HWND hwnd) { HRESULT result; //initialize Direct3D d3d = Direct3DCreate9(D3D_SDK_VERSION); if (d3d == NULL) { MessageBox(hwnd, "Error initializing Direct3D", "Error", MB_OK); return 0; } //set Direct3D presentation parameters D3DPRESENT_PARAMETERS d3dpp; ZeroMemory(&d3dpp, sizeof(d3dpp)); d3dpp.Windowed = FALSE; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8; d3dpp.BackBufferCount = 1; d3dpp.BackBufferWidth = SCREEN_WIDTH; d3dpp.BackBufferHeight = SCREEN_HEIGHT; d3dpp.hDeviceWindow = hwnd; //create Direct3D device d3d->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL, Hwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev); if (d3ddev == NULL) { MessageBox(hwnd, "Error creating Direct3D device", "Error", MB_OK); return 0; } //set random number seed srand(time(NULL)); //clear the backbuffer to black d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0); //create pointer to the back buffer d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer); //create surface result = d3ddev->CreateOffscreenPlainSurface( 100, //width of the surface 100, //height of the surface D3DFMT_X8R8G8B8, //surface format D3DPOOL_DEFAULT, //memory pool to use &surface, //pointer to the surface NULL); //reserved (always NULL) if (!result) return 1; //return okay return 1; }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

62

31

9/2/2012

The Create_Surface Example (3)


void Game_Run(HWND hwnd) { RECT rect; int r,g,b; //make sure the Direct3D device is valid if (d3ddev == NULL) return; //start rendering if (d3ddev->BeginScene()) { //fill the surface with random color r = rand() % 255; g = rand() % 255; b = rand() % 255; d3ddev->ColorFill(surface, NULL, D3DCOLOR_XRGB(r,g,b)); //copy the surface to the backbuffer rect.left = rand() % SCREEN_WIDTH/2; rect.right = rect.left + rand() % SCREEN_WIDTH/2; rect.top = rand() % SCREEN_HEIGHT; rect.bottom = rect.top + rand() % SCREEN_HEIGHT/2; d3ddev->StretchRect(surface, NULL, backbuffer, &rect, D3DTEXF_NONE); //stop rendering d3ddev->EndScene(); } //display the back buffer on the screen d3ddev->Present(NULL, NULL, NULL, NULL); //check for escape key (to exit program) if (KEY_DOWN(VK_ESCAPE)) PostMessage(hwnd, WM_DESTROY, 0, 0); }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

63

The Create_Surface Example (4)


void Game_End(HWND hwnd) { //free the surface surface->Release(); //release the Direct3D device if (d3ddev != NULL) d3ddev->Release(); //release the Direct3D object if (d3d != NULL) d3d->Release(); }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

64

32

9/2/2012

Loading Bitmaps from Disk


Must add
#include <d3dx.h> d3dx9.lib

to the project settings

HRESULT D3DXLoadSurfaceFromFile( LPDIRECT3DSURFACE9 pDestSurface, CONST PALETTEENTRY* pDestPalette, CONST RECT* pDestRect, LPCTSTR pSrcFile, CONST RECT* pSrcRect, DWORD Filter, D3DCOLOR ColorKey, D3DXIMAGE_INFO* pSrcInfo );

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

65

Graphics File Formats

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

66

33

9/2/2012

The Load_Bitmap Program (1)


Adding support for the D3DX library to the project

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

67

The Load_Bitmap Program (2)


int Game_Init(HWND hwnd) { //clear the backbuffer to black d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0); //create pointer to the back buffer d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer); //create surface result = d3ddev->CreateOffscreenPlainSurface( 640, //width of the surface 480, //height of the surface D3DFMT_X8R8G8B8, //surface format D3DPOOL_DEFAULT, //memory pool to use &surface, //pointer to the surface NULL); //reserved (always NULL) if (result != D3D_OK) return 1; //load surface from file result = D3DXLoadSurfaceFromFile( surface, //destination surface NULL, //destination palette NULL, //destination rectangle "legotron.bmp", //source filename NULL, //source rectangle D3DX_DEFAULT, //controls how image is filtered 0, //for transparency (0 for none) NULL); //source image info (usually NULL) //make sure file was loaded okay if (result != D3D_OK) return 1; //draw surface to the backbuffer d3ddev->StretchRect(surface, NULL, backbuffer, NULL, D3DTEXF_NONE); //return okay return 1; }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

68

34

9/2/2012

The Load_Bitmap Program (3)


void Game_Run(HWND hwnd) { //make sure the Direct3D device is valid if (d3ddev = = NULL) return; //start rendering if (d3ddev->BeginScene()) { //create pointer to the back buffer d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer); //draw surface to the backbuffer d3ddev->StretchRect(surface, NULL, backbuffer, NULL, D3DTEXF_NONE); //stop rendering d3ddev->EndScene(); } //display the back buffer on the screen d3ddev->Present(NULL, NULL, NULL, NULL); //check for escape key (to exit program) if (KEY_DOWN(VK_ESCAPE)) PostMessage(hwnd, WM_DESTROY, 0, 0); }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

69

Drawing Animated Sprites

The Anim_Sprite Project Concept Art Animated Sprites Explained

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

70

35

9/2/2012

The Anim_Sprite Project (1)


The new Anim_Sprite project.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

71

The Anim_Sprite Project (2)


The Project Properties dialog

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

72

36

9/2/2012

The Anim_Sprite Project (3)


Adding the Direct3D libraries to the project.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

73

The Anim_Sprite Project (4)


dxgraphics.h game.h winmain.cpp game.cpp

The Anim_Sprite program draws an animated cat on the screen.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

74

37

9/2/2012

The Anim_Sprite Project (5)


Adding a new header file to the project

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

75

The Anim_Sprite Project (6)

The Anim_Sprite project now includes dxgraphics.h.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

76

38

9/2/2012

The Anim_Sprite Project (7)

The completed Anim_Sprite project has five source code files.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

77

The Anim_Sprite Project (8)


load the sprite animation for (n=0; n<6; n++) { sprintf(s,"cat%d.bmp",n+1); kitty_image[n] = LoadSurface(s, D3DCOLOR_XRGB(255 ,0,255)); if (kitty_image[n] == NULL) return 0; }

The animated cat sprite has six frames.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

78

39

9/2/2012

The Anim_Sprite Project (9)


Add the following line up near the top of the game.cpp with the other variable declarations:
LPDIRECT3DSURFACE9 back;

Next, in Game_Init, add the line of code to load the background bitmap into this new surface:
back = LoadSurface("background.bmp", D3DCOLOR_XRGB(255,0,255));

Next, down in Game_Run, comment out the ColorFill line and replace it with a call to StretchRect, as shown here:
//d3ddev->ColorFill(backbuffer, NULL, D3DCOLOR_XRGB(0,0,0)); d3ddev->StretchRect(back, NULL, backbuffer, NULL, D3DTEXF_NONE);

Finally, add a line to Game_End to free the memory used by the background surface:
back->Release();

The cat is being animated over a colorful background. Note the lack of transparency.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

79

The Anim_Sprite Project (10)


result = D3DXLoadSurfaceFromFile( image, //destination surface NULL, //destination palette NULL, //destination rectangle filename, //source filename NULL, //source rectangle D3DX_DEFAULT, //controls how image is filtered transcolor, //for transparency (0 for none) NULL); //source image info (usually NULL)

The cat is being drawn without regard to the transparent color.


9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 80

40

9/2/2012

Others (1)
A bitmapped font used to print text on the screen in a game. A tank sprite with animated treads, courtesy of Ari Feldman

9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 81

Others (2)
A 32-frame rotation of the tank sprite (not animated), courtesy of Ari Feldman.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

82

41

9/2/2012

Others (3)
//sprite structure typedef struct { int x,y; int width,height; int movex,movey; int curframe,lastframe; int animdelay, animcount; } SPRITE;

An animated platform game character, courtesy of Ari Feldman

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

83

The kitty sprite


LPDIRECT3DSURFACE9 kitty_image[7]; SPRITE kitty; In the Game_Init function, initialize the sprites properties kitty.x = 100; kitty.y = 150; kitty.width = 96; kitty.height = 96; kitty.curframe = 0; kitty.lastframe = 5; kitty.animdelay = 2; kitty.animcount = 0; kitty.movex = 8; kitty.movey = 0; In Game_Run function, move the sprite kitty.x += kitty.movex; kitty.y += kitty.movey; //"warp" the sprite at screen edges if (kitty.x > SCREEN_WIDTH - kitty.width) kitty.x = 0; if (kitty.x < 0) kitty.x = SCREEN_WIDTH - kitty.width; //has animation delay reached threshold? if (+ +kitty.animcount > kitty.animdelay) { //reset counter kitty.animcount = 0; //animate the sprite if (+ +kitty.curframe > kitty.lastframe) kitty.curframe = 0; }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

84

42

9/2/2012

Drawing Transparent Sprites Creating a Sprite Handler Object Advanced Sprite Loading the Sprite Image Programming Drawing Transparent Sprites Drawing an Animated Sprite Working with Sprite Sheets The Tiled_Sprite Program Collision Detection Testing for Collisions The CollisionTest Program
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 85

Drawing Transparent Sprites

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

86

43

9/2/2012

Creating a Sprite Handler Object (1)


The D3DXSprite object is just a sprite handler that includes a function to draw sprites from a texture (with various transformations).
LPD3DXSPRITE sprite_handler; result = D3DXCreateSprite(d3ddev, &sprite_handler); HRESULT WINAPI D3DXCreateSprite(LPDIRECT3DDEVICE9 pDevice, LPD3DXSPRITE *ppSprite);

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

87

Creating a Sprite Handler Object (2)


Starting the Sprite Handler
sprite_handler>Begin(D3DXSPRITE_ALP HABLEND); D3DXSprite.Begin function HRESULT Begin(DWORD Flags);

Drawing a Sprite
HRESULT Draw(LPDIRECT3DTEXTU RE9 pTexture, CONST RECT *pSrcRect, CONST D3DXVECTOR3 *pCenter, CONST D3DXVECTOR3 *pPosition, D3DCOLOR Color); typedef struct D3DXVECTOR3 {FLOAT x; FLOAT y;FLOAT z;} D3DXVECTOR3;

Stopping the Sprite Handler


sprite_handler->End(); HRESULT End(VOID);

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

88

44

9/2/2012

Loading the Sprite Image


LPDIRECT3DTEXTURE9 texture = NULL; D3DXIMAGE_INFO info; result = D3DXGetImageInfoFromFile("image.bmp", &info);

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

89

Drawing Transparent Sprites (1)


Creating the Trans_Sprite Project
The Trans_Sprite program demonstrates how to draw transparent sprites with Direct3D

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

90

45

9/2/2012

Drawing Transparent Sprites (2)


Adding support for Direct3D to the project

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

91

Drawing Transparent Sprites (3)


dxgraphics.h game.h winmain.cpp dxgraphics.cpp
defined the new LoadTexture function

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

92

46

9/2/2012

Drawing an Animated Sprite

The caveman character has eight running frames and four jumping frames of animation.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

93

Working with Sprite Sheets


the pseudo-code:
left = (current frame % number of columns) * sprite width top = (current frame / number of columns) * sprite height

left = (curframe % columns) * width; top = (curframe / columns) * height; right = left + width; bottom = top + height;
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 94

47

9/2/2012

The Tiled_Sprite Program (1)


The Tiled_Sprite program demonstrates how to use a tiled bitmap image for sprite animation

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

95

The Tiled_Sprite Program (2)


#include "game.h" LPDIRECT3DTEXTURE9 caveman_image; SPRITE caveman; LPDIRECT3DSURFACE9 back; LPD3DXSPRITE sprite_handler; HRESULT result; //timing variable long start = GetTickCount(); //initializes the game int Game_Init(HWND hwnd) {} //the main game loop void Game_Run(HWND hwnd) {} } //frees memory and cleans up before the game ends void Game_End(HWND hwnd) {}

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

96

48

9/2/2012

Collision Detection (1)


The key to collision testing is to identify where two sprites are on the screen, and then compare their bounding boxes (or rectangles).
That is why this type of collision testing is called bounding box collision detection

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

97

Collision Detection (2)


int Collision(SPRITE sprite1, SPRITE sprite2) { RECT rect1; rect1.left = sprite1.x + 1; rect1.top = sprite1.y + 1; rect1.right = sprite1.x + sprite1.width-1; rect1.bottom = sprite1.y + sprite1.height-1; RECT rect2; rect2.left = sprite2.x + 1; rect2.top = sprite2.y + 1; rect2.right = sprite2.x + sprite2.width-1; rect2.bottom = sprite2.y + sprite2.height-1; RECT dest; return IntersectRect(&dest, &rect1, &rect2); }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

98

49

9/2/2012

The CollisionTest Program (1)


dxgraphics.h game.h winmain.cpp dxgraphics.cpp

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

99

The CollisionTest Program (2)


The CollisionTest program demonstrates collision detection

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

100

50

9/2/2012

Jamming with DirectX Audio

Using DirectSound Initializing DirectSound Creating a Sound Buffer Loading a Wave File Playing a Sound Testing DirectSound Creating the Project Creating the DirectX Audio Support Files Tweaking the Framework Code Adding the Game Files Running the Program
Khoa Khoa hc v K thut My tnh HBK Tp.HCM 101

9/2/2012

DSUtil
CSoundManager The primary DirectSound device. CSound Used to create DirectSound buffers. CWaveFile Helps load a wave file into a CSound buffer.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

102

51

9/2/2012

Initializing DirectSound
CSoundManager *dsound = new CSoundManager(); dsound->Initialize(window_handle, DSSCL_PRIORITY); DirectSound cooperative level
DSSCL_NORMAL: Shares sound device with other programs. DSSCL_PRIORITY: Gains higher priority over sound device (recommended for games). DSSCL_WRITEPRIMARY: Provides access to modify the primary sound buffer.
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 103

Creating a Sound Buffer


CSound *wave; The CSound object that you create is a wrapper for a secondary sound buffer called LPDIRECTSOUNDBUFFER8

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

104

52

9/2/2012

Loading a Wave File


result = dsound->Create(&wave, "snicker.wav"); HRESULT Create( CSound** ppSound, LPTSTR strWaveFileName, DWORD dwCreationFlags = 0, GUID guid3DAlgorithm = GUID_NULL, DWORD dwNumBuffers = 1 );

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

105

Playing & Stopping a Sound


Play
wave->Play(); wave->Play(0, DSBPLAY_LOOPING);

Stop
wave->Stop();

HRESULT Play( DWORD dwPriority = 0, DWORD dwFlags = 0, LONG lVolume = 0, LONG lFrequency = -1, LONG lPan = 0 ); HRESULT Stop();
Khoa Khoa hc v K thut My tnh HBK Tp.HCM 106

9/2/2012

53

9/2/2012

Testing DirectSound (1)


The Play_Sound program demonstrates how to use DirectSound.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

107

Testing DirectSound (2)


Copying the Reusable Copying the Source Files DirectSound Utility Files winmain.cpp
dxgraphics.h dxgraphics.cpp game.h game.cpp dxutil.h dsutil.h dsutil.cpp

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

108

54

9/2/2012

Testing DirectSound (3)

Adding an existing file to the project

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

109

Testing DirectSound (4)


Selecting the files to be inserted into the project: 1. winmain.cpp 2. dxgraphics.h 3. dxgraphics.cpp 4. game.h 5. game.cpp 6. dsutil.cpp 7. dxutil.h 8. dsutil.h

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

110

55

9/2/2012

Testing DirectSound (5)


Adding DirectX Library References
The framework files have been added to the project.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

111

Testing DirectSound (6)


Adding DirectX library references to the list of library modules in the Project Settings dialog: 1. d3d9.lib 2. d3dx9.lib 3. dsound.lib 4. dxguid.lib 5. dxerr9.lib 6. winmm.lib

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

112

56

9/2/2012

Creating the DirectX Audio Support Files (1)


Creating dxaudio.h
Adding the new dxaudio.h file to the project. #ifndef _DXAUDIO_H #define _DXAUDIO_H 1 #include "dsutil.h" //primary DirectSound object extern CSoundManager *dsound; //function prototypes int Init_DirectSound(HWND); CSound *LoadSound(char *); void PlaySound(CSound *); void LoopSound(CSound *); void StopSound(CSound *); #endif
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 113

Creating the DirectX Audio Support Files (2)


Creating dxaudio.cpp

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

114

57

9/2/2012

Creating the DirectX Audio Support Files (3)


code for the dxaudio.cpp file: #include "dxaudio.h" CSoundManager *dsound; int Init_DirectSound(HWND hwnd) { HRESULT result; //create DirectSound manager object dsound = new CSoundManager(); //initialize DirectSound result = dsound->Initialize(hwnd, DSSCL_PRIORITY); if (result != DS_OK) return 0; //set the primary buffer format result = dsound->SetPrimaryBufferFormat(2, 22050, 16); if (result != DS_OK) return 0; //return success return 1; } void PlaySound(CSound *sound) { sound->Play(); } CSound *LoadSound(char *filename) { HRESULT result; //create local reference to wave data CSound *wave; //attempt to load the wave file result = dsound->Create(&wave, filename); if (result != DS_OK) return NULL; //return the wave return wave; } void LoopSound(CSound *sound) { sound->Play(0, DSBPLAY_LOOPING); } void StopSound(CSound *sound) { sound->Stop(); }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

115

Adding the Game Files


game.h game.cpp

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

116

58

9/2/2012

Handling Input Devices

The Keyboard DirectInput Object and Device Initializing the Keyboard Reading Key Presses The Mouse Initializing the Mouse Reading the Mouse Paddle Game The New Framework Code for DirectInput The Paddle Game Source Code Paddle Game Explained
Khoa Khoa hc v K thut My tnh HBK Tp.HCM 117

9/2/2012

The Keyboard
The keyboard is the standard input device for all games The primary DirectInput object is called IDirectInput8;
can reference it directly or using the LPDIRECTINPUT8 pointer data type

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

118

59

9/2/2012

DirectInput Object and Device


Define the primary DirectInput object
LPDIRECTINPUT8 dinput; LPDIRECTINPUTDEVICE8 dinputdev; HRESULT result = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&dinput, NULL); result = dinput->CreateDevice(GUID_SysKeyboard, &dikeyboard, NULL); HRESULT WINAPI DirectInput8Create(HINSTANCE hinst, DWORD dwVersion, REFIID riidltf, LPVOID *ppvOut, LPUNKNOWN punkOuter); GUID_SysKeyboard, GUID_SysMouse HRESULT CreateDevice(REFGUID rguid,LPDIRECTINPUTDEVICE *lplpDirectInputDevice, LPUNKNOWN pUnkOuter);

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

119

Initializing the Keyboard


Setting the Data Format
HRESULT result = dikeyboard->SetDataFormat(&c_dfDIKeyboard); HRESULT SetDataFormat(LPCDIDATAFORMAT lpdf);

Setting the Cooperative Level


HRESULT result = dikeyboard>SetCooperativeLevel(hwnd,DISCL_NONEXCLUSIVE | DISCL_FOREGROUND); HRESULT SetCooperativeLevel(HWND hwnd,DWORD dwFlags);

Acquiring the Device


HRESULT Acquire(VOID); HRESULT Unacquire(VOID);

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

120

60

9/2/2012

Reading Key Presses


Reading keys
char keys[256]; dikeyboard->GetDeviceState(sizeof(keys), (LPVOID)&keys); if (keys[DIK_ESCAPE] & 0x80) { //ESCAPE key was pressed, so do something! } HRESULT GetDeviceState(DWORD cbData, LPVOID lpvData);
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 121

The Mouse (1)


Creating
LPDIRECTINPUTDEVICE8 dimouse; result = dinput->CreateDevice(GUID_SysMouse, &dimouse, NULL);

Initializing the Mouse


Setting the Data Format
HRESULT result = dimouse->SetDataFormat(&c_dfDIMouse); HRESULT SetDataFormat(LPCDIDATAFORMAT lpdf);

Setting the Cooperative Level


HRESULT result = dimouse->SetCooperativeLevel( hwnd,DISCL_EXCLUSIVE | DISCL_FOREGROUND); HRESULT SetCooperativeLevel(HWND hwnd,DWORD dwFlags);

Acquiring the Device


HRESULT Unacquire(VOID);
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 122

61

9/2/2012

The Mouse (2)


Reading the Mouse
DIMOUSESTATE mouse_state; dimouse->GetDeviceState(sizeof(mouse_state), (LPVOID)&mouse_state); HRESULT GetDeviceState(DWORD cbData, LPVOID lpvData); typedef struct DIMOUSESTATE {LONG lX; LONG lY; LONG lZ; BYTE rgbButtons[4]; } DIMOUSESTATE; typedef struct DIMOUSESTATE2 {LONG lX; LONG lY; LONG lZ; BYTE rgbButtons[8]; } DIMOUSESTATE2;
Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

123

The Mouse (3)


Reading special button
button_1 = obj.rgbButtons[0] & 0x80; #define BUTTON_DOWN(obj, button) (obj.rgbButtons[button] & 0x80) button_1 = BUTTON_DOWN(mouse_state, 0);

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

124

62

9/2/2012

Paddle Game
Paddle Game is a near-complete game that demonstrates how to use DirectInput to read the keyboard and mouse

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

125

Paddle Game Code

The project workspace for the Paddle Game project

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

126

63

9/2/2012

Tile-Based Scrolling Backgrounds

Introduction to Scrolling Introduction to Tile-Based Backgrounds Backgrounds and Scenery Creating Backgrounds from Tiles Tile-Based Scrolling Dynamically Rendered Tiles The Tile Map Creating a Tile Map Using Mappy The DynamicScroll Project
Khoa Khoa hc v K thut My tnh HBK Tp.HCM 127

9/2/2012

Introduction to Scrolling
The scroll window shows a small part of a larger game world

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

128

64

9/2/2012

Introduction to Tile-Based Backgrounds

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

129

Backgrounds and Scenery


A background is comprised of imagery or terrain in one form or another, upon which the sprites are drawn.
The background might be nothing more than a pretty picture behind the action in a game, or it might take an active part, as in a scroller. When you are talking about scrollers, they need not be relegated only to the high-speed arcade games. Role-playing games are usually scrollers too, as are most sports games
Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

130

65

9/2/2012

Creating Backgrounds from Tiles


The real power of a scrolling background comes from a technique called tiling.
Tiling is a process in which there really is no background, just an array of tiles that make up the background as it is displayed. In other words, it is a virtual background and it takes up very little memory compared to a full bitmapped background

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

131

Tile-Based Scrolling (1)


A bitmap image constructed of tiles

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

132

66

9/2/2012

Tile-Based Scrolling (2)


The ScrollTest program demonstrates how to perform tile-based background scrolling

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

133

Tile-Based Scrolling (3)


The source file containing the tiles used in the ScrollTest program A legend of the tiles and their reference numbers used to create a map in the DynamicScroll program

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

134

67

9/2/2012

Tile-Based Scrolling (4)


ScrollTest Program
library files again that must be added to the Additional Dependencies field under Project Properties, Linker, Input:
d3d9.lib d3dx9.lib dsound.lib dinput8.lib dxguid.lib dxerr9.lib winmm.lib
Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

135

Tile-Based Scrolling (5)

The map data in the ScrollTest program

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

136

68

9/2/2012

Dynamically Rendered Tiles

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

137

The Tile Map


This starfield image used by the DynamicScroll program was shot by the Hubble Space Telescope (courtesy of NASA).

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

138

69

9/2/2012

Creating a Tile Map Using Mappy (1)


Importing an Existing Bitmap File
Creating a new map using Mappy

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

139

Creating a Tile Map Using Mappy (2)

The new map that has been created by Mappy, awaiting your custom tiles

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

140

70

9/2/2012

Creating a Tile Map Using Mappy (3)


Preparing to import a large bitmap file as the source for our tiles

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

141

Creating a Tile Map Using Mappy (4)

The palette of tiles has been imported from the large space photograph

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

142

71

9/2/2012

Creating a Tile Map Using Mappy (5)

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

143

Creating a Tile Map Using Mappy (6)

The Export dialog box is used to export a tile map to a text file.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

144

72

9/2/2012

The DynamicScroll Project


The DynamicScroll program scrolls a map that was defined in the map array

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

145

ADVANCED TOPICS

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

146

73

9/2/2012

Building a 2D Game Engine

Compiler Support DirectX SDK Support Why Do We Need an Engine Creating the Engine Project Visual C++ Project Engine Source Code Compiling the Engine Project Testing the Engine The TestEngine Source Code Visual C++ Library Test Project.
Khoa Khoa hc v K thut My tnh HBK Tp.HCM 147

9/2/2012

Compiler Support
Dev-C++ 5.0 (MinGW / CygWin) Borland C++ 6.0 Visual C++ 7.1 (2003) Visual C++ 8.0 (2005) Visual C++ 8.0 (2005 SP1) Visual C++ 9.0 (2008)

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

148

74

9/2/2012

DirectX SDK Support


Direct3D 9 Direct3D 10 Microsofts DirectX SDK

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

149

Why Do We Need an Engine?


Teamwork is much easier when the rogrammers in a team use a game engine rather than writing their own core game code, because the engine code facilitates standardization across the project. Cross-compiler support is almost impossible without the use of a game engine. Logistics in a large game project can be a nightmare without some coordinated way to organize the entities, processes, and behaviors in your game.
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 150

75

9/2/2012

Creating the Engine Project (1)


Creating the New Engine Project

Creating a new Win32 project in Visual C++

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

151

Creating the Engine Project (2)


The Visual C engine project has files but needs source code 1. Advanced2D.h 2. Timer.h 3. winmain.h 4. Advanced2D.cpp 5. Timer.cpp 6. winmain.cpp

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

152

76

9/2/2012

Creating the Engine Project (3)

Setting the output file for the Visual C++ static library project.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

153

Compiling the Engine Project

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

154

77

9/2/2012

The TestEngine Source Code


Add a new source code file to the project called Main.cpp #include <iostream> #include "..\Engine\Advanced2D.h" bool game_preload() { //display engine version in a message box g_engine->message(g_engine->getVersionText(), "TEST ENGINE"); //return fail to terminate the engine return false; } bool game_init(HWND hwnd) { return 0;} void game_update() {} void game_end() {}

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

155

Visual C++ Library Test Project (1)

Configuring the Visual C++ projects linker dependencies: 1. ..\..\Engine\lib\Advanced2D.lib 2. d3d9.lib 3. d3dx9.lib 4. dxguid.lib 5. winmm.lib

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

156

78

9/2/2012

Visual C++ Library Test Project (2)

Adding the engines lib folder to the compilers library search path (optional).

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

157

Visual C++ Library Test Project (3)

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

158

79

9/2/2012

2D Rendering

Basic 2D Rendering Raising Happy Sprites Creating Vectors Testing Vector3 Creating a Reusable Sprite Class Rendering Sprites with Transparency Color Key Transparency Alpha Channel Transparency
Khoa Khoa hc v K thut My tnh HBK Tp.HCM 159

9/2/2012

Basic 2D Rendering (1)


Advanced2D.h file: public: Engine(); virtual ~Engine(); int Init(int width, int height, int colordepth, bool fullscreen); void Close(); void Update(); void message(std::string message, std::string title = "ADVANCED 2D"); void fatalerror(std::string message, std::string title = "FATAL ERROR"); void Shutdown(); void ClearScene(D3DCOLOR color); void SetDefaultMaterial(); void SetAmbient(D3DCOLOR colorvalue); int RenderStart(); int RenderStop(); int Render2D_Start(); int Render2D_Stop(); int Release(); Advanced2D.cpp file: int Engine::Render2D_Start() { if (p_sprite_handler>Begin(D3DXSPRITE_ALPHABLEND) != D3D_OK) return 0; else return 1; } int Engine::Render2D_Stop() { p_sprite_handler->End(); return 1; }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

160

80

9/2/2012

Basic 2D Rendering (2)


void Engine::Update() { static Timer timedUpdate; //calculate core framerate p_frameCount_core+ +; if (p_coreTimer.stopwatch(999)) { p_frameRate_core = p_frameCount_core; p_frameCount_core = 0; } //fast update with no timing game_update(); //update with 60fps timing if (!timedUpdate.stopwatch(14)) { if (!this->getMaximizeProcessor()) { Sleep(1); } }

else { //calculate real framerate p_frameCount_real++; if (p_realTimer.stopwatch(999)) { p_frameRate_real = p_frameCount_real; p_frameCount_real = 0; } //begin rendering this->RenderStart(); //let game do its own 3D game_render3d(); //2D rendering Render2D_Start(); game_render2d(); Render2D_Stop(); //done rendering this->RenderStop(); } }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

161

Creating Vectors
Vector3.h Vector3.cpp

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

162

81

9/2/2012

Creating a Reusable Sprite Class


Sprite.h Sprite.cpp

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

163

Rendering Sprites with Transparency

This sprite (being edited in GIMP) will be rendered with color-keyed transparency

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

164

82

9/2/2012

Color Key Transparency


#include "..\Engine\Advanced2D.h" using namespace Advanced2D; Sprite *sprite; bool game_preload() { Rendering Sprites with Transparency 93 Figure 3.4 This sprite (being edited in GIMP) will be rendered with colorkeyed transparency. g_engine->setAppTitle("SPRITE COLOR KEY DEMO"); g_engine->setFullscreen(false); g_engine->setScreenWidth(640); g_engine->setScreenHeight(480); g_engine->setColorDepth(32); return 1; } bool game_init(HWND) { //load sprite sprite = new Sprite(); sprite->loadImage("fatship_colorkeyed.bmp"); return true; } void game_update() { //exit when escape key is pressed if (KEY_DOWN(VK_ESCAPE)) g_engine->Close(); } void game_end() { delete sprite; Khoa Khoa hc v K thut} My tnh void game_render3d() 165 HBK Tp.HCM { g_engine->ClearScene(D3DCOLOR_XRGB(0,0,80));

The SpriteDemo program demonstrates sprite transparency

9/2/2012

Alpha Channel Transparency

This sprite will be rendered with alpha channel transparency


9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 166

83

9/2/2012

Animation

Animation Demo Sprite Rotation and Scaling Animation with Transforms Particles

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

167

Introduction (1)

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

168

84

9/2/2012

Introduction (2)
Using the Sprite class developed in the previous chapter, we could create a dragon sprite with code like this:
Sprite *dragon = new Sprite(); dragon->loadImage("dragon.tga"); dragon->setSize(96,96); dragon->setTotalFrames(64);

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

169

Introduction (3)
void Sprite::animate() { //update frame based on animdir if (frametimer > 0) { if (timeGetTime() > (DWORD)(framestart + frametimer)) { //reset animation timer framestart = timeGetTime(); curframe += animdir; //keep frame within bounds if (curframe < 0) curframe = totalframes-1; if (curframe > totalframes-1) curframe = 0; } } else { //no animation timer--update at cpu clock speed curframe += animdir; if (curframe < 0) curframe = totalframes-1; if (curframe > totalframes-1) curframe = 0; } }}

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

170

85

9/2/2012

Animation Demo
The sprite sheet for an animated explosion

The AnimationDemo program draws an animated explosion

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

171

Sprite Rotation and Scaling (1)


void Sprite::draw() { //calculate source frame location int fx = (this->curframe % this->animcolumns) * this->width; int fy = (this->curframe / this->animcolumns) * this->height; RECT srcRect = {fx,fy, fx+this->width, fy+this>height}; //draw the sprite frame this->transform(); g_engine->getSpriteHandler()->Draw( this>image->GetTexture(), &srcRect,NULL,NULL,color); } void Sprite::transform() { 3DXMATRIX mat; D3DXVECTOR2 scale((float)scaling,(float)scaling); D3DXVECTOR2 center((float)(width*scaling)/2, (float)(height*scaling)/2); D3DXVECTOR2 trans((float)getX(), (float)getY()); D3DXMatrixTransformation2D(&mat,NULL,0,&sc ale,&center,(float)rotation,&trans); g_engine->getSpriteHandler()>SetTransform(&mat); }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

172

86

9/2/2012

Sprite Rotation and Scaling (2)


The RotateScaleDemo program draws a sprite with rotation and scaling.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

173

Animation with Transforms

A 64-frame animated asteroid


9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

The RotateAnimDemo program draws an animated sprite with rotation and scaling.
174

87

9/2/2012

Particles (1)
Particles are tiny sprites that are rendered with about 50-percent alpha transparency so that they seem to glow. The key to creating a particle systemthat is, an emitter or other special effectis to start with a good source particle image.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

175

Particles (2)
Source particle image

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

176

88

9/2/2012

Particles (3)

Particle demonstration with a white background. Particle demonstration with a black background. Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

177

Physics

Collision Detection Automated Collision Detection Bounding Rectangle Collision Test Distance-Based Collision Test

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

178

89

9/2/2012

Collision Detection
The two types of collision testing we will utilize are
Bounding rectangle Distance

Bounding rectangle collision detection describes the use of a sprites boundary for collision testing.
these values may be represented as left, top, right, and bottom

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

179

Automated Collision Detection (1)


the engine to do is automatically perform collision detection, but then notify the game when a collision occurs In the Advanced2D.h file is a new external function definition:
extern void game_entityCollision( Advanced2D::Entity*,Advanced2D::Entity*);

four new support functions used internally by the engine to perform collision testing:

9/2/2012

bool collision(Sprite *sprite1, Sprite *sprite2); bool collisionBR(Sprite *sprite1, Sprite *sprite2); bool collisionD(Sprite *sprite1, Sprite *sprite2); void TestForCollisions();
Khoa Khoa hc v K thut My tnh HBK Tp.HCM 180

90

9/2/2012

Automated Collision Detection (2)


void Engine::Update() { //calculate core framerate p_frameCount_core+ +; if (p_coreTimer.stopwatch(999)) { p_frameRate_core = p_frameCount_core; p_frameCount_core = 0; } //fast update with no timing game_update(); //update entities if (!p_pauseMode) UpdateEntities(); //perform global collision testing if (!p_pauseMode && collisionTimer.stopwatch(50)) { TestForCollisions(); }
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 181

Automated Collision Detection (3)


void Engine::TestForCollisions() { std::list<Entity*>::iterator first; std::list<Entity*>::iterator second; Sprite *sprite1; Sprite *sprite2; first = p_entities.begin(); while (first != p_entities.end() ) { //we only care about sprite collisions if ( (*first)->getRenderType() = = RENDER2D ) { //point local sprite to sprite contained in the list sprite1 = (Sprite*) *first; //if this entity is alive and visible... if ( sprite1->getAlive() && sprite1->getVisible() && sprite1-> isCollidable() ) { //test all other entities for collision second = p_entities.begin(); while (second != p_entities.end() ) { //point local sprite to sprite contained in the list sprite2 = (Sprite*) *second; //if other entity is active and not same as first entity... if ( sprite2->getAlive() && sprite2->getVisible() && sprite2->isCollidable() && sprite1 != sprite2 ) { //test for collision if ( collision(sprite1, sprite2 ) ) { //notify game of collision game_entityCollision( sprite1, sprite2 ); } } //go to the next sprite in the list second+ +; } } //go to the next sprite in the list first+ +; }//render2d } //while }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

182

91

9/2/2012

Automated Collision Detection (4)


We need two methods for the two collision tests supported by the engine bounding rectangle and distance-based bool Engine::collision(Sprite *sprite1, Sprite *sprite2) { switch (sprite1->collisionMethod) { case COLLISION_RECT: return collisionBR(sprite1,sprite2); break; case COLLISION_DIST: return collisionD(sprite1,sprite2); break; case COLLISION_NONE: default: return false; } }
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 183

Automated Collision Detection (5)


bool Engine::collisionBR(Sprite *sprite1, Sprite *sprite2) { bool ret = false; Rect *ra = new Rect( sprite1->getX(), sprite1->getY(), sprite1->getX() + sprite1->getWidth()*sprite1>getScale(), sprite1->getY() + sprite1>getHeight()*sprite1->getScale()); Rect *rb = new Rect( sprite2->getX(), sprite2->getY(), sprite2->getX() + sprite2->getWidth()*sprite2>getScale(), sprite2->getY() + sprite2>getHeight()*sprite2->getScale()); //are any of sprite bs corners intersecting sprite a? if (ra->isInside( rb->getLeft(), rb->getTop() ) || ra->isInside( rb->getRight(), rb->getTop() ) || ra->isInside( rb->getLeft(), rb->getBottom() ) || ra->isInside( rb->getRight(), rb->getBottom() )) ret = true; delete ra; delete rb; return ret; }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

184

92

9/2/2012

Automated Collision Detection (6)


class Rect { public: double left,top,right,bottom; public: Rect(int left,int top,int right,int bottom); Rect(double left,double top,double right,double bottom); virtual ~Rect() { } double getLeft() { return left; } double getTop() { return top; } double getRight() { return right; } double getBottom() { return bottom; } bool isInside(Vector3 point); bool isInside(int x,int y); bool isInside(double x,double y); };

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

185

Automated Collision Detection (7)


Rect::Rect(int left,int top,int right,int bottom) { this->left = (double)left; this->top = (double)top; this->right = (double)right; this->bottom = (double)bottom; } Rect::Rect(double left,double top,double right,double bottom) { this->left = left; this->top = top; this->right = right; this->bottom = bottom; } bool Rect::isInside(Vector3 point) { return this->isInside(point.getX(), point.getY()); } bool Rect::isInside(int x,int y) { return this->isInside((double)x, (double)y); } bool Rect::isInside(double x,double y) { return (x > left && x < right && y > top && y < bottom); }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

186

93

9/2/2012

Automated Collision Detection (8)


bool Engine::collisionD(Sprite *sprite1, Sprite *sprite2) { double radius1, radius2; //calculate radius 1 if (sprite1->getWidth() > sprite1->getHeight()) Collision Detection 191 radius1 = (sprite1->getWidth()*sprite1>getScale())/2; else radius1 = (sprite1->getHeight()*sprite1>getScale())/2; //point = center of sprite 1 double x1 = sprite1->getX() + radius1; double y1 = sprite1->getY() + radius1; Vector3 vector1(x1, y1, 0.0); //calculate radius 2 if (sprite2->getWidth() > sprite2->getHeight()) radius2 = (sprite2->getWidth()*sprite2>getScale())/2; else radius2 = (sprite2->getHeight()*sprite2>getScale())/2; //point = center of sprite 2 double x2 = sprite2->getX() + radius2; double y2 = sprite2->getY() + radius2; Vector3 vector2(x2, y2, 0.0); //calculate distance double dist = vector1.Distance( vector2 ); //return distance comparison return (dist < radius1 + radius2); }

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

187

Bounding Rectangle Collision Test (1)


The CollisionDemo program demonstrates bounding rectangle collision detection using translucent collision boxes

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

188

94

9/2/2012

Bounding Rectangle Collision Test (2)


The stats of the CollisionDemo program show that the translucent boxes really hurt performance

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

189

Bounding Rectangle Collision Test (3)

This sprite collision demo is a performance punishment test

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

190

95

9/2/2012

Bounding Rectangle Collision Test (4)


The engine supports sprite rendering without collision detection.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

191

Bounding Rectangle Collision Test (5)

Changing from Debug to Release build nearly doubled performance

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

192

96

9/2/2012

Bounding Rectangle Collision Test (6)

With collisions turned back on, the framerate improved by the same amount (percentagewise).

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

193

Distance-Based Collision Test (1)

The distance-based collision demo with 50 sprites

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

194

97

9/2/2012

Distance-Based Collision Test (2)


The distancebased collision demo with 50 sprites.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

195

Math

Distance between two vectors Length of a vector Dot product Cross product Normalized vector

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

196

98

9/2/2012

Math Class
Distance Vector length Dot product Cross product Normalized vector Converting radians to degrees Converting degrees to radians X velocity of an angle Y velocity of an angle Angle to target vector

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

197

Math Class Header


#include "Advanced2D.h" #pragma once 214 Chapter 10 n Math namespace Advanced2D { const double PI = 3.1415926535; const double PI_over_180 = PI / 180.0f; const double PI_under_180 = 180.0f / PI; class Math { public: double toDegrees(double radian); double toRadians(double degree); double wrapAngleDegs(double degs); double wrapAngleRads(double rads); double LinearVelocityX(double angle); double LinearVelocityY(double angle); Vector3 LinearVelocity(double angle); double AngleToTarget(double x1,double y1,double x2,double y2); double AngleToTarget(Vector3& source,Vector3& target); double Distance( double x1,double y1,double x2,double y2 ); double Distance( Vector3& v, Vector3& vec2 ); double Length(Vector3& vec); double Length(double x,double y,double z); double DotProduct(double x1,double y1,double z1, double x2,double y2,double z2); double DotProduct(Vector3& vec1, Vector3& vec2); Vector3 CrossProduct(double x1,double y1,double z1, double x2,double y2,double z2); Vector3 CrossProduct(Vector3& vec1, Vector3& vec2); Vector3 Normal(double x,double y,double z); Vector3 Normal(Vector3& vec); }; };

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

198

99

9/2/2012

Math Test

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

199

Linear Velocity (1)


float Math::LinearVelocityX(float angle) { angle -= 90; if (angle < 0) angle = 360 + angle; return cos( angle * PI_over_180); } float Math::LinearVelocityY(float angle) { angle -= 90; if (angle < 0) angle = 360 + angle; return sin( angle * PI_over_180); }
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 200

100

9/2/2012

Linear Velocity (2)

The VelocityDemo program shows how to move an object in any direction

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

201

Angle to Target (1)


float Math::AngleToTarget(float x1,float y1,float x2,float y2) { float deltaX = (x2-x1); float deltaY = (y2-y1); return atan2(deltaY,deltaX); } float Math::AngleToTarget(Vector3& src,Vector3& tgt) { return AngleToTarget(src.getX(),src.getY(),tgt.getX(),tgt.getY()); }
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 202

101

9/2/2012

Angle to Target (2)

The TargetingDemo program demonstrates the utility of angle to target


Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

203

Drop-Down Console (1)


Console class
class Console { private: bool showing; Sprite *panel; Font *font; int currentLine; std::vector<std::string> textlines; std::vector<std::string>::iterator iter; public: Console(); virtual ~Console(); bool init(); void draw(); void clear(); void print(std::string text, int line = -1); bool isShowing() { return this->showing; } void show() { this->showing = true; } void hide() { this->showing = false; } void setShowing(bool value) { this->showing = value; } };

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

204

102

9/2/2012

Drop-Down Console (2)


Console Test
The game screen with the console drawn over the top with alpha blending and text output

The game screen that is normally seen


9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 205

APPENDIXES (VIETNAMESE)

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

206

103

9/2/2012

Gii thiu

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

207

Ti liu tham kho


Tng quan v video game v ngnh cng nghip video game Video game l g? Cc th loi game http://en.wikipedia.org/wiki/Video_game http://videogames.lovetoknow.com/wiki/Video_Game_G enres:_An_Overview http://www.rentersinsurance.org/video-game-genres/ http://en.wikipedia.org/wiki/Video_game_genres http://en.wikipedia.org/wiki/Video_game_industry http://www.gamespot.com/gamespot/features/video/hov/ index.html http://en.wikipedia.org/wiki/History_of_video_games http://www.giantbomb.com/platforms/

Ngnh cng nghip game Lch s pht trin

Cc nn tng chi game Xu hng hin nay Tng quan v pht trin game

Nhn s trong 1 d n game: http://grannycoder.blogspot.com/2009/07/understanding producer, designer, artist, programmer, -game-development.html tester S lc v quy trnh pht trin game Lm th no to ra mt game? http://grannycoder.blogspot.com/2009/07/what-arestages-in-game-development.html http://www.wieringsoftware.nl/coding/

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

208

104

9/2/2012

Game l g?
Game cng ch l mt ng dng, v n cng nh bao ng dng khc.
C th bt u vit game t hm main, hoc dng cc engine h tr.
Mt cch nhn khc, game l mt cun phim c tng tc. Nu nh mt b phim cn nhiu th nh kch bn tt, dn dng hay, hu k, kim duyt, qung b, ... th game cng vy. Game cng cn mt ni dung hay (kch bn), coding tt (dn dng, hu k), kim sot cht lng (kim duyt), qung b ... Nu mt phim thnh cng c nh gi qua doanh thu, th game cng vy. Tuy nhin, khi mi bt u, th doanh thu, li nhun, ... cn c gt ra khi t tng ca mnh, c tnh to tp trung vo chuyn mn.
209

ng v kha cnh lp trnh, game n gin l mt vng lp v tn, trong x l cc din bin ca game v s kin tng tc t ngi chi.
Tuy nhin, lm game cho mc ch thng mi, i hi bn nhiu hn th.
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM

Lp trnh game bng ngn ng no?


Nh mi ng dng khc, game c th c lp trnh bng mi ngn ng. Cc xu th hin nay:
Java:
dng vit game cho Mobile - cc dng phone h tr J2ME, hoc vit game cho Android. t khi dng vit game cho PC dng vit game cho windows mobiles hoc PC, vi XNA / Microsoft. dng cho mi trng web dng cho iOS nh my MAC, iPhone, iPad. C/C++ c xem l ngn ng c bn ca mi ngn ng lp trnh, v c l t nht mt ln trong i th mi programmer u tng ng n n.

C#:

Javascript: Objective C: C/C++:

C/C++ cng l mt ngn ng kh c a chung trong lp trnh game ngy nay, vi kh nng thc thi trn khc nhiu platform: Windows, Linux, MacOS, Android, iphone/iPad, Symbian, Brew, Meegoo ...

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

210

105

9/2/2012

Lp trnh game cn nhng kin thc g?


Cn phi bit lp trnh, t duy lp trnh. Khng nht thit bn phi xut sc; bit t, lm t, bit nhiu, lm nhiu. Mt cht kin thc k nng v game, bit chi game, v tng chi game. Bit mt ngn ng lp trnh no . Bit mt t kin thc v ton, vt l (Google, nu cn) Mt s kin thc v ha 2D, 3D
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 211

Video game l g?
Video game l cch gi cc loi my chi game chuyn dng nh Playstation, Xbox, GameCube Cc h my ny cn gi l h my console. Thng th video game thng c chi trn cc my chuyn dng k trn.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

212

106

9/2/2012

Cc th loi game (1)


Cc th loi video game (gi tt l cc th loi game) thng c dng phn loi video game da trn li chi tung tc ca chng hn l s khc bit gia phong cch ha hay cch tng thut ct truyn. Mt th loi video game c xc nh bng nhng thch thc li chi.
Chng c phn loi c lp vi th gii trong game hay cc thit lp trong th gii . khng ging nh cc tc phm gi tng khc nh phim hay sch truyn. V d, mt game hnh ng s vn l mt game hnh ng, bt k th gii trong game l mt th gii thn thoi hay ngoi khng gian.

Trong cc ngnh nghin cu game vn cha c s ng thun trong vic chp nhn mt nh ngha chnh thc cho cc th loi video game, mt s nh ngha c xem xt nhiu hn nhng ci khc.
Cng nh bt c s phn loi in hnh no khc, mt th loi video game nht nh cn c nhng c trng c th. Phn ln cc game u a ra cc kh khn cn phi vt qua, do vy cc th loi game c th nh ngha bng vic hon tt cc tr ngi thng qua cc cch c bn tng t.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

213

Cc th loi game (2)


Mt game hnh ng yu cu ngi chi s phn x nhanh chng, chnh xc v ng thi im vt qua cc tr ngi.
y c l l th loi c bn nht trong cc th loi game, v chc chn l th loi ln nht. Game hnh ng c li chi nhn mnh vo chin u. C kh nhiu th loi con ca game hnh ng, nh game i khng hay bn sng gc nhn ngi th nht.

Cc game th loi Beat 'em up (nh bi chng) v hack and slash (cht v chm) tp trung vo kiu chin u mt chi mt trm trong nhng vng khng gian nh, nh bi mt s lng ln qun ch do my tnh iu khin.
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 214

107

9/2/2012

Cc th loi game (3)


Game i khng tp trung vo trn chin 1-1 gia hai nhn vt, mt trong hai i th ny c th do my iu khin. Game m cung c khu vc tung tc hon ton l mt m cung, m ngi chi phi thm d. Game pinball (game bn bng) c thit k m phng hnh nh v cm gic ca mt bn chi pinball trong thc t o. Platform game (hay platformer) l th loi con ca game hnh ng.
Li chi ca cc game ny lin quan ch yu ti vic di chuyn gia cc "tng" (hay nn mt t) khc nhau bng cch nhy gia chng (i khi cc phng tin khc c dng h tr cho vic nhy nh nh u hoc dng bp bnh, nhng y u c coi l cc bin th ca mt c ch.
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 215

Ngnh cng nghip game


Lch s pht trin Cc nn tng chi game Xu hng hin nay

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

216

108

9/2/2012

Tng quan v video game v ngnh cng nghip video game


Ngnh cng nghip game Lch s pht trin Cc nn tng chi game Xu hng hin nay

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

217

Tng quan v video game v ngnh cng nghip video game


Ngnh cng nghip game Lch s pht trin Cc nn tng chi game Xu hng hin nay

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

218

109

9/2/2012

Tng quan v video game v ngnh cng nghip video game


Ngnh cng nghip game Lch s pht trin Cc nn tng chi game Xu hng hin nay

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

219

Tng quan v pht trin game


Nhn s trong 1 d n game:
producer, designer, artist, programmer, tester

S lc v quy trnh pht trin game Lm th no to ra mt game?

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

220

110

9/2/2012

Lp trnh game 2D

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

221

Ti liu tham kho


Cu trc Cc thnh phn c bn: Initialization, ca mt Enter Game Loop, Retrieve Player Input, game Perform AI and Game Logic, Render Next Frame, Synchronize Display, Loop, Shutdown, State Machine. FlowChart ca game. (V s minh ha v gii thch) Cc thnh phn / khi nim c bn Sprite http://en.wikipedia.org/wiki/Sprite_%28computer_graphics%29 http://www.flyingyogi.com/fun/spritelib.html http://www.videogamesprites.net/ http://www.freewebs.com/teh_pro/sprites.htm http://www.themechanicalmaniacs.com/guides/spriteguide.php http://www.spriters-resource.com/ http://en.wikipedia.org/wiki/Game_controller http://lazyfoo.net/SDL_tutorials/ (Lesson 4, 8, 9) http://en.wikipedia.org/wiki/Animation http://en.wikipedia.org/wiki/Frame_rate http://sacredsoftware.net/tutorials/Animation/TimeBasedAnimation.xht ml http://osdl.sourceforge.net/main/documentation/rendering/SDLaudio.html http://www.kekkai.org/roger/sdl/mixer/ 222 http://www.yaldex.com/gamesprogramming/0672323699_ch01lev1sec7.html http://www.ronkes.nl/blog/?2005-07-21-gameengine http://blog.monnet-usa.com/?cat=16

Input (keyboard, mouse, game controller,) Animation Frame rate

Cc khi nim c bn v m thanh s: frequency, sample, channels,

9/2/2012

Text: hin th text vi font True Type Khoa Khoa hc v K thuhttp://en.wikipedia.org/wiki/TrueType t My tnh http://www.libsdl.org/projects/SDL_ttf/ HBK Tp.HCM

111

9/2/2012

Cu trc ca mt game (1)


Thnh phn c bn:

9/2/2012

Initialization Enter Game Loop Retrieve Player Input Perform AI and Game Logic Render Next Frame Synchronize Display Loop Shutdown State Machine.
Khoa Khoa hc v K thut My tnh HBK Tp.HCM 223

Cu trc ca mt game (2)


Phn 1: Khi to
Trong phn ny, bn thc hin cc hot ng tiu chun bn s cho bt k chng trnh, chng hn nh cp pht b nh, mua li ti nguyn, d liu ti t a, v vv.

Phn 2: Nhp Vng Chi Game


Trong phn ny, thc hin ang i vo vng lp game chnh. y l ni m hnh ng bt u v tip tc cho n khi ngi dng thot khi vng lp chnh.

Phn 3: Ly u vo cu th
Trong phn ny, u vo ca ngi chi c x l v / hoc m cho sau ny s dng trong AI v phn lun l.

Phn 4: Thc hin cm gia cm v tr chi logic


Phn ny bao gm phn ln cc m s tr chi. Tr tu nhn to, h thng vt l v logic ca game ni chung c thc hin, v kt qu c s dng rt ra nhng khung hnh tip theo trn mn hnh
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 224

112

9/2/2012

Cu trc ca mt game (3)


Mc 5: Render
Tip theo KhungTrong phn ny, kt qu u vo ca my nghe nhc v thc hin ca tr chi AI v logic c s dng to ra cc khung hnh tip theo ca phim hot hnh cho cc tr chi. Hnh nh ny thng c v trn mt khu vc m offscreen, v vy bn khng th nhn thy n c thc hin. Sau , n c sao chp rt nhanh chng mn hnh hin th c th nhn thy.

Phn 6: ng b ha hin th
Nhiu my tnh s tng tc hoc lm chm do mc phc tp ca tr chi. V d, nu c 1.000 i tng ang chy trn mn hnh, CPU s c mt ti cao hn nu c ch c 10 i tng. T l khung hnh ca tr chi s thay i, l khng th chp nhn c. Do , bn phi ng b ha cc tr chi mt s t l khung hnh ti a v c gng gi n bng cch s dng v / hoc cc chc nng thi gian, ch i. Thng thng, tc 30fps c coi l ti u.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

225

Cu trc ca mt game (3)


Phn 7: Lp vng
Phn ny l kh n gin, ch cn i tr li u vng lp game v lm tt c mt ln na.

Phn 8: Shutdown
Giai on tt my cho bit kt thc ca tr chi, c ngha rng ngi dng thot vng lp c th hoc tr chi chnh v mun quay tr li h iu hnh. Tuy nhin, trc khi thot khi ngi s dng, bn phi pht hnh tt c cc ngun ti nguyn v lm sch h thng, cng ging nh bn cho bt k phn mm khc.
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 226

113

9/2/2012

Cu trc ca mt game (4)


// defines for game loop states #define GAME_INIT // the game is initializing #define GAME_MENU // the game is in the menu mode #define GAME_STARTING // the game is about to run #define GAME_RUN // the game is now running #define GAME_RESTART // the game is going to restart #define GAME_EXIT // the game is exiting // game globals int game_state = GAME_INIT; // start off in this state int error = 0; // used to send errors back to OS // main begins here void main() { // implementation of main game loop while (game_state!=GAME_EXIT) { // what state is game loop in switch(game_state) { case GAME_INIT: /* the game is initializing */ { // allocate all memory and resources Init(); // move to menu state game_state = GAME_MENU; } break; case GAME_MENU: /* the game is in the menu mode*/ { // call the main menu function and let it switch states game_state = Menu(); // note: we could force a RUN state here } break; case GAME_STARTING: /* the game is about to run */ { // this state is optional, but usually used to set things up right before the game is run you might do a little more housekeeping here Setup_For_Run(); // switch to run state game_state = GAME_RUN; } break; case GAME_RUN: /* the game is now running */ { // this section contains the entire game logic loop clear the display Clear(); // get the input Get_Input(); // perform logic and AI Do_Logic(); // display the next frame of animation Render_Frame(); // synchronize the display Wait(); // the only way that state can be changed is thru user interaction in the input section or by maybe losing the game. } break; case GAME_RESTART: /* the game is restarting */ { // this section is a cleanup state used to fix up any loose ends before running again Fixup(); // switch states back to the menu game_state = GAME_MENU; } break; case GAME_EXIT: /* the game is exiting */ { // if the game is in this state then it's time to bail, kill everything and cross your fingers Release_And_Cleanup(); // set the error word to whatever error = 0; // note: we don't have to switch states since we are already in this state on the next loop iteration the code will fall out of the main while and exit back to the OS } break; default: break; } // end switch } // end while // return error code to operating system return(error); } // end main

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

227

Cc thnh phn / khi nim c bn (1)


Sprite
L mt hnh nh hai chiu hoc hnh nh ng c tch hp vo mt khung cnh ln hn. Ban u c s dng m t i tng ha x l ring bit t bitmap b nh ca mt mn hnh hin th video, thut ng c p dng lng lo hn tham kho theo cch thc khc nhau ca lp ha. Ban u, sprites l mt phng php tch hp bitmap khng lin quan h xut hin l mt phn ca bitmap bnh thng trn mn hnh, chng hn nh to ra mt nhn vt hot hnh c th c di chuyn trn mn hnh m khng lm thay i cc d liu xc nh mn hnh tng th. Nh ha ba chiu tr nn ph bin hn, thut ng ny c s dng m t mt k thut m trong hnh nh phng c tch hp vo phc tp cnh ba chiu.

Input (keyboard, mouse )


Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

228

114

9/2/2012

Cc thnh phn / khi nim c bn (2)


Game controller
Mt b iu khin tr chi l mt thit b c s dng vi cc tr chi hoc cc h thng gii tr cung cp u vo cho mt tr chi video, thng kim sot mt i tng hoc nhn vt trong game. Mt b iu khin thng c kt ni vi mt giao din iu khin tr chi hoc my tnh bng cc phng tin ca mt dy hoc dy, mc d iu khin khng dy cng ph bin. Thit b u vo c phn loi nh l b iu khin tr chi bao gm bn phm, chut, ming tr chi, cn iu khin, thit b mc ch c bit, chng hn nh tay li cho li xe tr chi, sng nh sng cho tr chi bn sng, iu khin tr chi. Cc thit b nh chut v bn phm c th c m phng vi mt pad tr chi thng qua vic s dng cc chng trnh nh vy l JoyToKey.
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 229

Cc thnh phn / khi nim c bn (3)


Animation
Hot hnh l mn hnh hin th nhanh chng ca mt chui hnh nh to ra mt o nh ca phong tro. Cc phng php ph bin nht trnh by hnh nh ng nh mt hnh nh chuyn ng hay mt chng trnh video, mc d c nhng phng php khc. Kiu trnh chiu ny thng c thc hin vi mt my nh v mt my chiu hoc mn hnh xem my tnh c th nhanh chng chu k thng qua hnh nh trong mt chui. Hot hnh c th c thc hin vi mt trong hai bn tay tr li ngh thut, hnh nh, my tnh to ra, hoc cc i tng ba chiu, v d nh con ri hoc s liu t st, hoc s kt hp ca k thut. V tr ca tng i tng trong bt k hnh nh c th lin quan n v tr ca i tng trong nhng hnh nh trc v sau y cc i tng tng xut hin fluidly di chuyn c lp vi nhau. Cc thit b xem hin th nhng hnh nh ny trong k nhanh chng, thng l 24, 25 hoc 30 khung hnh mi giy.
Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

230

115

9/2/2012

Cc thnh phn / khi nim c bn (3)


Sample / mu
i vi mt ngun m thanh nht nh, tt c cc mu tn trng cc nh dng tng t, ging nh cc im nh ca mt b mt i vi cc nh dng im nh ca b mt. Kch thc ca mt mu ph thuc vo nh dng ca n, m chnh n ph thuc vo:
xc nh s lng mu c la chn, l chnh xc ca p lc m thanh o c, thng c m t vi 8 hoc 16 bit, tc l 256 hoc 65.536 gi tr khc nhau s lng cc knh (mono, stereo, 5.1, vv) SampleSize = (size of a quantification unit) * (number of channels) Do , mt mu ca mt ngun 8 bit m thanh stereo l: 1 [8 bit] * 2 knh] = 2 byte.

Frequency / tn s
L s lng mu chi mi giy, c th hin trong Hertz (Hz) hoc kg-Hertz (kHz, 1 kHz = 1000 Hz). Bn s thit lp ny n 44100 Hz (hoc 44,1 kHz) cho cht lng CD ", hoc khong 8 kHz cht lng in thoi.
Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

231

Cc thnh phn / khi nim c bn (4)


Channel / knh
Mt knh m thanh hoc theo di m thanh l mt knh thng tin lin lc trong mt thit b lu tr, c s dng trong cc hot ng nh multitrack ghi m v pht li. Trong pht thanh truyn hnh, mt knh l mt phm vi tn s (hoc tng ng, cc bc sng) c giao ca chnh ph cho hot ng ca mt i pht thanh i truyn hnh c bit, hoc knh truyn hnh. Trong s dng thng thng, thut ng ny cng c th c s dng tham kho iu hnh nh ga trn mt tn s c th. Trong vin thng v mng my tnh, mt knh truyn thng, hoc knh, hoc cp n mt phng tin truyn dn vt l nh mt dy, hoc mt kt ni hp l trong mt mi trng ghp nh mt knh pht thanh. Mt knh c s dng chuyn ti mt thng tin tn hiu, v d nh mt dng bit k thut s, t mt hoc mt s ngi gi (hoc in) mt hoc mt s nhn. Mt knh c mt nng lc nht nh cho truyn thng tin, thng c o bng bng thng ca n trong Hz hoc d liu tc bit mi giy Trong l thuyt thng tin, mt knh cp n mt m hnh knh l thuyt vi mt s c tnh li. Trong ny nhn tng qut hn, mt thit b lu tr cng l mt loi knh, c th c gi n (bng vn bn) v nhn (c).
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 232

116

9/2/2012

Cc thnh phn / khi nim c bn (5)


Frame rate / T l khung hnh
(cn c gi l tn s khung hnh) l tn s (t l) m ti mt thit b hnh nh hnh nh c o lin tip c gi l khung hnh. Thut ng ny c p dng tt nh nhau vi ha my tnh, my quay video, my nh phim, v cc h thng chp chuyn ng. T l khung hnh thng c th hin trong khung hnh mi giy (FPS) v cng c th hin trong cc mn hnh qut lin tc nh hertz (Hz).

Text hin th vi font True Type


TrueType l mt font phc tho tiu chun ban u c pht trin bi Apple Computer vo cui nhng nm 1980 nh l mt i th cnh tranh vi Adobe Type 1 phng ch c s dng trong PostScript. TrueType tr thnh nh dng ph bin nht cho cc phng ch trn c hai h iu hnh Mac v iu hnh h thng Microsoft Windows. Sc mnh chnh ca TrueType ban u m n cung cp cc nh pht trin phng ch mt mc cao kim sot trn chnh xc phng ch c hin th, cc im nh c th, vi kch thc phng ch khc nhau. Vi rng ri cng ngh to hnh khc nhau trong s dng ngy nay, kim sot mc im nh l khng cn nht nh trong mt phng ch TrueType.

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

233

Ci t v cu hnh cc cng c cn thit (1)


Visual C++ 2008 Express Edition
http://www.microsoft.com/visualstudio/enus/products/2008-editions/express

SDL, SDL_gfx, SDL_mixer


http://www.libsdl.org

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

234

117

9/2/2012

Ci t v cu hnh cc cng c cn thit (2)


SDL (http://www.libsdl.org)
n gin Directmedia lp th vin (SDL) l mt API chung cung cp truy cp mc thp m thanh, bn phm, chut, phm iu khin phn cng, 3D, thng qua OpenGL, v b m khung 2D trn nhiu nn tng. Phin bn hin ti h tr Windows XP, Windows Vista, Windows 7, Mac OS X, Linux, iOS v Android. M ny c h tr cho h iu hnh khc, nhng nhng ngi khng chnh thc h tr. SDL c vit trong C, nhng cc cng trnh C + + nguyn bn, v c cam kt rng buc ngn ng mt s khc, bao gm Ada, C #, Eiffel, Erlang, Euphoria, Guile, Haskell, Java, Lisp, Lua, ML, Objective C, Pascal, Perl, PHP, Pike, d sai bo, Python, Ruby v Smalltalk. SDL 2.0 zlib theo giy php, cho php s dng min ph cho cc mc ch thng mi v phi thng mi.
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 235

Ci t v cu hnh cc cng c cn thit (3)


SDL_mixer
L mt th vin trn m thanh c s dng vi cc th vin SDL, v gn nh cm tay. N cho php mt lp trnh s dng nhiu mu cng vi m nhc m khng cn phi vit m mt thut ton trn t. N cng n gin ha vic x l ti v chi mu v m nhc t tt c cc loi nh dng tp tin.

SDL_gfx
ha nguyn thy (dy chuyn, vng trn, hnh ch nht ...) vi h tr AA, rotozoomer v chc nng h tr bn v khc lin quan n gi ln trong mt da trn Cvo th vin truyn thng trc tip n gin (SDL) nn tng API lp.
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 236

118

9/2/2012

Bi tp 2: Vit game Tetris


Yu cu:
Vng v dnh cho game phi lp y ca s (tr vng system button). 1 H tr chc nng chi c bn (c tng tc phm), ch cn mt mu duy nht cho tt c cc block.(3). Th hin c hnh nh bn ngoi (2). H tr nhiu mu khc nhau: http://en.wikipedia.org/wiki/Tetris (2). H tr tnh im (1). C nhc nn (0.5) + m hiu ng (sfx) (0.5).

im cng:
C mn hnh hiu ng khi thng mn (0.5). Hi ngi chi c restart hay khng (menu la chn) lc thua mn chi. (0.5). Code vit d c, khng hard code (0.5).
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 237

Vt l trong game (1)


Cn bn v chuyn ng v va chm trong mt phng hai chiu: v tr (position), vn tc (velocity), gia tc (acceleration), pht hin va chm (collision detection) v phn ng (response ) (AABB, im nh hon ho (pixel perfect), ...)

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

238

119

9/2/2012

Vt l trong game (2)


V tr (position) & Vn tc (velocity)
M hnh ha chuyn ng ca cc i tng vi vn tc
Mt i tng s v tr no ti thi im t? Gi s khong cch n v l pixel

V tr ti thi im t cho mt i tng di chuyn vi vn tc v, t bt u t v tr x0:


x (t) = x0 + vx * t y (t) = y0 + vy * t

Gia tng tnh ton mi khung hnh, gi s bc thi gian lin tc-khng i v khng c kh nng tng tc:
vx v vy, cc hng s, trc khi tnh ton x += vx, y += vy
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 239

Vt l trong game (3)


Gia tc (acceleration)
Acceleration (a): thay i vn tc trn mt n v thi gian Gia tc khng i: vx += ax, vy += ay Gia tc bin ng
Tra cu bng da trn cc yu t nh: acceleration = acceleration_value(gear, speed, pedal_pressure) Mo: acceleration = acceleration_value(gear, speed) * pedal_pressure ax = cos(v) * gia tc ay = sin(v) * gia tc

Phn hoch tuyn tnh cho cc tnh nng lin tc


Khoa Khoa hc v K thut My tnh HBK Tp.HCM

9/2/2012

240

120

9/2/2012

Vt l trong game (4)


Trng lc (Gravity)
Trng lc l mt lc gia hai i tng:
Force F = G (m1 m2) / D2
G = 6,67 x 10^-11 Nm2kg-2 mi: khi lng ca hai i tng d = khong cch gia hai i tng

V vy, c hai i tng c cng mt lc lng p dng cho h


F = ma -> a = F / m

Trn tri t, gi s khi lng ca tri t l rt ln, n khng di chuyn, v D l khng i


gi nh tng tc thng nht Chc v ca i tng thuc ti thi im t:
x(t) = x0 y(t) = y0 +1 / 2 * 9.8m/s2 * t2 Tng bc, y + = trng lc (bnh thng ha vi t l khung hnh)
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 241

Vt l trong game (5)


Trng lc (Gravity)
i tng i din trung tm khi lng c th, khng chnh xc cho tt c cc i tng vt l Trung tm ca i chng (xc, yc) cho mt a gic vi nh n:
yc = ximi / mi, i = 0 .. n yc = yimi / mi, i = 0 .. n

i vi cc ha tit, t trung tm ca khi lng im nh dy c nht i vi cc tr chi arcade, m hnh lc hp dn trong khung hnh sprite
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 242

121

9/2/2012

Vt l trong game (6)


Trng lc (Gravity) - lc hp dn
nh hng c hai i tng
C th c hai i tng tc ng qu o ca nhau Ch c ngha cho cc i tng ln Xem xt vn N-i tng

iu g s xy ra sau khi bn p dng mt lc vo mt i tng? iu g s xy ra khi bn bn mt tn la t mt i tng di chuyn? Nhng loi iu khin bn mong i c trn mt con tu khng gian? iu g v mt tr chi bay?
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 243

Vt l trong game (7)


Ma st (Friction)
Chuyn i ng nng thnh nhit nng Thng l hai lc lng ma st
ma st tnh khi phn cn li (tc = 0). Khng c ng lc ma st ng khi di chuyn

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

244

122

9/2/2012

Vt l trong game (8)


Th loi game tc
Gia tc tuyn tnh Ma st ngh > ma st ln ma st ln <trt ma st Lc hng tm iu g iu khin bn mong i c cho mt game tc ?
i hi chuyn ng quay v pha trc! iu g v cc loi khc ca tr chi ua xe?
Boat? Hovercraft?
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 245

Vt l trong game (9)


Chuyn ng n o
vix = vi cos() viy = vi sin()

t nh t = vi sin()/g Vi sc gi
x += vix + W y += viy

Vi sc gi khng v trng lc
vix += Wrx viy += Wry + g, g chun
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 246

123

9/2/2012

Vt l trong game (10)


particle system explosions
Bt u vi rt nhiu i tng im (1-4 im nh) Khi to vi vn tc ngu nhin da trn vn tc ca i tng n p dng lc hp dn Chuyn i cng mu sc nh l mt hm ca thi gian Ph hy cc i tng khi c va chm hoc sau mt thi gian c nh C th thm ng mn hi mu sc khc nhau, sut cuc i, gi
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 247

Vt l trong game (11)


Collision detection & response (AABB, pixel perfect,...)
Cc bc phn tch i vi cc loi khc nhau va chm Vng trn / phm vi thay cho mt i tng c nh / phng Hai vng trn / phm vi Rigid c quan bin dng M hnh xy dng n gin, ng to mt ng c tng qut
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 248

124

9/2/2012

Vt l trong game (12)


Cc bc phn tch va chm
Pht hin mt v va chm xy ra Xc nh thi gian ca v va chm V vy, c th sao lu im ca v va chm Xc nh cc i tng c ti thi im va chm Xc nh cc gc va chm ngoi khi bnh thng va chm Xc nh cc vect vn tc sau khi va chm Xc nh nhng thay i trong vng quay
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 249

Vt l trong game (13)


Va chm vng trn v ng
trng hp n gin
Bc cho cc tr chi ca bn pinball Gi s vng trn nh mt ro cn bt ng

Pht hin mt v va chm xy ra


Nu khong cch t cicle dng <vng trn bn knh Xy dng li nh l mt im nh mt bc tng ln hn Nu bc tng dc v ngang, n gin th nghim ca x, y

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

250

125

9/2/2012

Vt l trong game (14)


Va chm
iu g s xy ra nu nn phc tp hn: pinball? i vi cc b mt phc tp, trc khi tnh ton v in vo mt mng vi cc im va chm (v b mt bnh thng)

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

251

Vt l trong game (15)


Va chm Phn hi va chm gia vng trn v tng
Xc nh cc vect vn tc sau khi va chm gc ca gc = reflectant ti, phn nh i tng mt gc bng nhau v i din ra khi b mt bnh thng Nu b mt l ng tuyn tnh vi x-y-trc
Dc - du hiu thay i theo vn tc x Ngang - du hiu thay i ca vn tc y Gc - thay i du hiu ca c hai

S dng t-tc tnh ton v tr mi t im va chm Xc nh nhng thay i trong vng quay Khng! y c phi l gi tr n? Ph thuc vo tc ca m phng, ...
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 252

126

9/2/2012

Vt l trong game (16)


Va chm Phn hi va chm gia vng trn v tng
Xc nh thi gian ca v va chm
tc = ti + (xh x1) / (x2 x1) * delta(t) T1 = thi im u Delta(t) = mc tng

Xc nh cc i tng khi chng chm vo yc y1 (y1-y2)*(tc-t1) / delta(t) Xc nh cc gc va chm so vi bnh thng va chm
va chm bnh thng l b mt bnh thng ca bc tng trong trng hp ny tnh ton gc ca ng s dng (x1-xh) v (y1-yc)
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 253

Vt l trong game (17)


Va chm Phn hi va chm gia vng trn v vng trn
Mt trng hp c bit quan trng Tt bc cho cc tr chi ca bn Nhiu k thut pht trin y c th c s dng cho cc loi i tng khc Gi va chm n hi:
Chuyn ha ng lng Bo tn ng lng

Khng va chm n hi chuyn i ng Nng lng thnh nhit v / hoc bin dng c kh
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 254

127

9/2/2012

Thit k mn chi (1)


Cc k thut xy dng mn chi cho game: tool (level editor), raw file, Cch hin thc

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

255

Thit k mn chi (2)


level editor
Mt mc , bn , khu vc, sn khu, hoc th gii trong mt tr chi video l tng s khng gian c sn cho cc cu th trong qu trnh hon thnh mt mc tiu ring bit. Thut ng "" cng c th tham kho mc kh khn, nh trong mt mc kh khns

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

256

128

9/2/2012

C ch save game (1)


Ti sao cn save game?
Mt tr chi lu (cng i khi c gi l mt tr chi tit kim, savegame, hoc savefile) l mt phn ca thng tin k thut s c lu tr v nhng tin b ca mt cu th trong mt tr chi in t (ging nh mt tr chi video). Tr chi ny lu c th c np li sau ny, do , ngi chi c th tip tc ni ng dng li. Ngi chi thng lu tr chi ngn chn s mt mt ca s tin b trong tr chi (nh c th xy ra sau khi mt tr chi trn, tr khi tr chi tnh nng permadeath, trong lu cc tp tin b xa vnh vin), c bit l khi b gin on hoc kt thc mt phin tr chi. Vic s dng cc tr chi lu l rt ph bin trong cc tr chi video hin i, c bit trong tr chi nhp vai, thng l qu di kt thc trong mt phin duy nht.
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 257

C ch save game (2)


Cc kiu lu
Lu im Lu v tr Lu t ng Lu trng thi Lu nhanh Lu ty

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

258

129

9/2/2012

Tr tu nhn to trong game


Cc gii thut AI thng dng:
Random/Ngu nhin: s dng chc nng ngu nhin xc nh nhng ng thi tip theo v nhng g my tnh s lm g tip theo vi c hi. Distance /T xa: y l hnh ng ca s dng forumals khong cch xc nh nhng g mt k th hoc i tng cn lm. Logical / Lun l: Checkers, Chess, v Tic-Tac-Toe ch l mt s trong nhng tr chi s dng ton hc hp l ... N bc ln khong 20 bc xem nhng g s xy ra trong tng lai xc nh nhng g n s lm g tip theo. Pathfinding / Tm ng: iu ny nn l mt ch ring ca n .. l mt phin bn nh nh th no bn c th lm cho mt nhn vt ngh rng khi lm pathfinding. Math / Ton hc: Lm th no s dng ton hc li th ca bn khi thc hin tr tu nhn to .. Dy mt s cc chc nng ton hc c bn s gip AI kch bn trng cao cp hn nhng nhanh hn.
9/2/2012 Khoa Khoa hc v K thut My tnh HBK Tp.HCM 259

~~~~ HT ~~~~

9/2/2012

Khoa Khoa hc v K thut My tnh HBK Tp.HCM

260

130

You might also like