Andy Pike - DirectX 8 Programming Tutorial

Здесь есть возможность читать онлайн «Andy Pike - DirectX 8 Programming Tutorial» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

DirectX 8 Programming Tutorial: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «DirectX 8 Programming Tutorial»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

DirectX 8 Programming Tutorial — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «DirectX 8 Programming Tutorial», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

} else if(KEYDOWN(KeyboardState, DIK_LEFT)) {

m_rRotate += 0.5f;

}

//Set an upper and lower limit for the rotation factor

if (m_rRotate < –20.0f) {

m_rRotate = –20.0f;

} else if(m_rRotate > 20.0f) {

m_rRotate = 20.0f;

}

//Scale Earth

if (KEYDOWN(KeyboardState, DIK_UP)) {

m_rScale += 0.5f;

} else if (KEYDOWN(KeyboardState, DIK_DOWN)) {

m_rScale –= 0.5f;

}

//Set an upper and lower limit for the scale factor

if (m_rScale < 1.0f) {

m_rScale = 1.0f;

} else if(m_rScale > 20.0f) {

m_rScale = 20.0f;

}

}

This function is pretty straightforward. At the start we call GetDeviceState which gets the current state of the keyboard device. The function call fills a char array with the key states of the keyboard. You can see from the function above, that once the array has been populated with key states, we can then use a simple macro called KEYDOWN to ascertain if a given key is in the down position. The KEYDOWN macro is shown below. So, based on certain key states, we manipulate some member variables that control scale and rotation.

#define KEYDOWN(name, key) (name[key] & 0x80)

Getting mouse data

As with the keyboard, we have a new function called ProcessMouse which is called from our Render function. This means that ProcessMouse will also be called once per frame. The code for ProcessMouse is shown below.

void CGame::ProcessMouse() {

DIMOUSESTATE MouseState;

if (FAILED(m_pMouse->GetDeviceState(sizeof(MouseState),(LPVOID)&MouseState))) {

return;

}

//Is the left mouse button down?

if (MOUSEBUTTONDOWN(MouseState.rgbButtons[MOUSEBUTTON_LEFT])) {

m_nMouseLeft = 1;

} else {

m_nMouseLeft = 0;

}

//Is the right mouse button down?

if (MOUSEBUTTONDOWN(MouseState.rgbButtons[MOUSEBUTTON_RIGHT])) {

m_nMouseRight = 1;

} else {

m_nMouseRight = 0;

}

m_nMouseX += MouseState.lX;

m_nMouseY += MouseState.lY;

}

So, to get access to the mouse data we make a call to GetDeviceState which fills a DIMOUSESTATE structure with data from the mouse. The DIMOUSESTATE structure has four members:

· lX: Distance the mouse has moved along the x-axis since the last call to GetDeviceState.

· lY: Distance the mouse has moved along the y-axis since the last call to GetDeviceState.

· lZ: Distance mouse wheel has moved since the last call to GetDeviceState.

· rgbButtons: Array of mouse button states.

lX, lY and lZ return the distance moved in device units (NOT pixels) since the last call to GetDeviceState. If you want to get the current screen position in pixels, you can use the Win32 GetCursorPos function. We use the macro MOUSEBUTTONDOWN to determine if a given mouse button is down or not. This macro is shown below along with some constants used for referring to mouse buttons.

#define MOUSEBUTTONDOWN(key) (key & 0x80)

#define MOUSEBUTTON_LEFT 0

#define MOUSEBUTTON_RIGHT 1

#define MOUSEBUTTON_MIDDLE 2

Using the data

In our Render3D function, we use the data that we have retrieved from the keyboard and mouse to alter the scene. The Render3D function is shown below:

void CGame::Render3D() {

//Render our 3D objects

D3DXMATRIX matEarth, matScale, matRotate, matEarthRoll, matEarthMove;

float rMouseSpeed = 20.0f;

//If left mouse button is down, stop the earth from rotating

if (m_nMouseLeft == 1) {

m_rRotate = 0.0f;

}

//If right mouse button is down, start the earth rotating at default speed

if (m_nMouseRight == 1) {

m_rRotate = 2.0f;

}

m_rAngle += m_rRotate;

//Create the transformation matrices

D3DXMatrixRotationY(&matRotate, D3DXToRadian(m_rAngle));

D3DXMatrixScaling(&matScale, m_rScale, m_rScale, m_rScale);

D3DXMatrixRotationYawPitchRoll(&matEarthRoll, 0.0f, 0.0f, D3DXToRadian(23.44f));

D3DXMatrixTranslation(&matEarthMove, (m_nMouseX / rMouseSpeed), –(m_nMouseY / rMouseSpeed), 0.0f);

D3DXMatrixMultiply(&matEarth, &matScale, &matRotate);

D3DXMatrixMultiply(&matEarth, &matEarth, &matEarthRoll);

D3DXMatrixMultiply(&matEarth, &matEarth, &matEarthMove);

//Render our objects

m_pD3DDevice->SetTransform(D3DTS_WORLD, &matEarth);

m_dwTotalPolygons += m_pSphere->Render();

}

Cleaning up

Here is a simple function that will unacquire the mouse and keyboard and clean up the Direct Input related pointers. This is called from the destructor of our CGame class as part of the games clean up process.

void CGame::CleanUpDirectInput() {

if (m_pKeyboard) {

m_pKeyboard->Unacquire();

}

if (m_pMouse) {

m_pMouse->Unacquire();

}

SafeRelease(m_pMouse);

SafeRelease(m_pKeyboard);

SafeRelease(m_pDirectInput);

}

So now we have an Earth that you can control.

Summary

In this tutorial we've seen how to use the mouse and keyboard via DirectInput. We've used the data from these input devices to control elements in our scene. The next thing to do is add some sound and music to our application, we'll do this in the next tutorial.

DirectX Tutorial 13: Sounds and Music

Introduction

In this tutorial we will learn how to play music and sounds with DirectX. We will use DirectX Audio to play wav and midi files, we will also use DirectShow to play mp3 files. In this tutorial we will have a simple application that plays a background track (in mp3 format) and we will allow the user to use the mouse to play some sound effects (in wav format) whenever they click on a coloured number. You can download the full source code by clicking the "Download Source" link above.

DirectX Audio and DirectShow

So far in our tutorials we have used Direct3D and DirectInput for graphics and user input. Now I'm going to introduce you to two more components of DirectX: DirectX Audio and DirectShow. We use DirectX Audio to play wav and midi audio files. We use DirectShow to play streaming media such as full motion video (avi) and high quality audio (mp3) files. In this tutorial we will only be looking at how to play mp3's with DirectShow.

Wav, Midi and Mp3 – When should I use what?

So when should I use which type of file format? Well, that is largely a matter of personal preference. Before I tell you my preference, here is some information about each format.

Wav files

Wav files are pure, uncompressed digital audio. It is an actual, digital recording similar to that stored on a CD. Uncompressed digital audio is the only true "CD quality" audio. But wav files can be massive. Even a short track can take up 20 or 30 megabytes of space, often much more.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «DirectX 8 Programming Tutorial»

Представляем Вашему вниманию похожие книги на «DirectX 8 Programming Tutorial» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «DirectX 8 Programming Tutorial»

Обсуждение, отзывы о книге «DirectX 8 Programming Tutorial» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x