[英]Issues with making an OpenGL plane out of triangles
我正在嘗試使用OpenGL制作飛機,在某種程度上代碼可以工作,但是在某些索引上卻得到了奇怪的結果。 我將盡力解釋我的代碼,這是我的代碼和我在網上找到的混合物。
主要的:
所有設置都在主設備中進行,因此該功能將知道所需的所有值
float zoom = 6.0f;
float vertical = 1.2f;
float horizontal = 1.2f;
const int planeWidth = 4; //columns
const int planeHeight = 2; //rows
const int totalVertices = (planeWidth + 1) * (planeHeight + 1);
//GLfloat* vertices = new GLfloat[totalVertices];
GLfloat vertices[totalVertices] = { 0.0 };
const int indPerRow = planeWidth * 2 + 2;
const int indDegenReq = (planeHeight - 1) * 2;
const int totalIndices = indPerRow * planeWidth + indDegenReq;
//GLuint* indices = new GLuint[totalIndices];
GLuint indices[totalIndices] = { 0 };
GLfloat texCoords[totalVertices] = { 0 };
makePlane(planeWidth, planeHeight, vertices, indices, texCoords);
功能:
第一個for循環創建頂點,第二個執行索引
void makePlane(int width, int height, GLfloat *vertices, GLuint *indices)
{
width++; //columns
height++; //rows
int size = sizeof(GLfloat);
for (int y = 0; y < height; y++)
{
int base = y * width;
for (int x = 0; x < width; x++)
{
int index = (base + x) * 2;
vertices[index] = (float)x;
vertices[index +1] = (float)y;
}
}
int i = 0;
height--;
for (int y = 0; y < height; y++)
{
int base = y * width;
for (int x = 0; x < width; x++)
{
indices[i++] = base + x;
indices[i++] = base + width + x;
}
if (y < height - 1)
{
indices[i++] = ((y + 1) * width + (width - 1));
indices[i++] = ((y + 1) * width);
}
}
}
結果:
4 x 2
索引0、5、1、6、2、7、3、8、4、9、9、5、5、10、6、11、7、12、8、9、14、0、0、0 ,0,0,0,...} unsigned int [42]
它會正確執行22個值,然后其余均為零。
知道為什么嗎?
我認為您的循環需要看起來像這樣(請注意,未經測試的:)。 基本上將其視為遍歷四邊形並輸出三角形對的索引。
for (int y = 0; y < height; y++)
{
unsigned int base = y * width;
unsigned int top = base + width;
for (int x = 0; x < (width-1); x++)
{
indices[i++] = base + x;
indices[i++] = top + x;
indices[i++] = top + x + 1;
indices[i++] = top + x + 1;
indices[i++] = base + x + 1;
indices[i++] = base + x;
}
}
我意識到頂點是從下到上創建的,索引被命令從上到下創建三角形。 因此,我將頂點創建更改為循環。
int index = 0;
for (int y = height; y >= 0; y--)
{
for (int x = 0; x <= width; x++)
{
vertices[index] = ((float)x/4)-0.5;
vertices[index +1] = ((float)y/4)-0.5;
vertices[index + 2] = 0.0f;
index += 3;
}
}
它從左上角到右下角創建頂點。 索引的循環保持不變:
int i = 0;
++width;
GLuint indices2[170] = { 0 };
for (int y = 0; y < height; y++)
{
int base = y * width;
for (int x = 0; x < width; x++)
{
indices[i++] = base + x;
indices[i++] = base + width + x;
}
if (y < height - 1)
{
indices[i++] = ((y + 1) * width + (width - 1));
indices[i++] = ((y + 1) * width);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.