Cube历程添加三角形的方法:
首先要确立你需要与Cube共用多少个顶点,以下教程为共用两个顶点,只添加一个顶点。
步骤如下:
打开Cube.cpp文件,找到第23、24行代码,如下:
const int Width = 640; //绘制窗口的宽度
const int Height = 480; //绘制窗口的高度
把起参数修改大一点以方便查看效果,如
const int Width = 800;
const int Height = 600;
找到第54行 Device->CreateVertexBuffer 代码,如下
Device->CreateVertexBuffer(
8 * sizeof(Vertex), //设置 8个Vertex长度
D3DUSAGE_WRITEONLY,
Vertex::FVF,
D3DPOOL_MANAGED,
&VB,
0);
把其中
8 * sizeof(Vertex),
中的数字“8”改为“9” (该数字代表一共使用多少个顶点缓存)
修改后效果如下:
Device->CreateVertexBuffer(
9 * sizeof(Vertex),
D3DUSAGE_WRITEONLY,
Vertex::FVF,
D3DPOOL_MANAGED,
&VB,
0);
找到第62行 Device->CreateIndexBuffer代码,如下:
Device->CreateIndexBuffer(
36 * sizeof(WORD), //设置36个WORD长度
D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16,
D3DPOOL_MANAGED,
&IB,
0);
把其中
36 * sizeof(WORD),
中的数字“36”改为“39”(该数字代表一共使用多少个索引缓存,一个三角形使用3个索引,所以为39)
修改后效果如下:
Device->CreateIndexBuffer(
39 * sizeof(WORD),
D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16,
D3DPOOL_MANAGED,
&IB,
0);
找到第86行代码,如下:
vertices[7] = Vertex( 1.0f, -1.0f, 1.0f);
在其下面添加一行代码:
vertices[8] = Vertex( 2.0f, -2.0f, -1.0f);
修改后,效果为:
vertices[7] = Vertex( 1.0f, -1.0f, 1.0f);
vertices[8] = Vertex( 2.0f, -2.0f, -1.0f);
找到第118行代码,如下:
indices[33] = 4; indices[34] = 3; indices[35] = 7;
在其下面添加一行代码:
//right trigon
indices[42] = 8; indices[43] = 7; indices[44] = 6;
修改后,效果为:
indices[33] = 4; indices[34] = 3; indices[35] = 7;
//right trigon
indices[42] = 8; indices[43] = 7; indices[44] = 6;
疑问理解:
1.Cube定义了一个Vertex类vertices来存放顶点缓存。(使用方法较像数组)
vertices[0] = Vertex(-1.0f, -1.0f, -1.0f); //本句代表vertices[0]的坐标是(-1.0,-1.0,-1.0)
2.Cube定义了一个WORD类indices来存放索引缓存。(使用方法较像数组)
indices[0] = 0; indices[1] = 1; indices[2] = 2; //其中 indices[0] = 0 中的 = 0 为对应顶点的“数组”下标。
Device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8, 0, 12);
修改为
Device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 9, 0, 13);
(注释:其中9代表有9个顶点缓存,13代表13个三角形面)
完成后编译执行,得到一个立方体带一个三角形的图。
如何解决由于背部消隐,从而在旋转到背后时,没有显示三角形的问题?
找到第158行代码,如下:
Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME); //填充模式
在其下面添加一行代码:
Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
修改后,效果如下:
Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
最后终于把作业完成!