Now I want to have my camera to be able to "walk" on the terrain. The getY() function gets the x and z coordinates of the camera, and I understand that with those I have to find the closest vertices of the terrain to decide which triangle the camera is over. The thing is i'm unsure of how to actually do that, I have looked for a lot of examples on google but haven't been able to find any concrete answers for it. Currently my code looks like this:
HM_SIZE_X and HM_SIZE_Y are both 6
float Terrain::getY(int x, int z)
{
//return
}
void Terrain::createTerrain()
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Setup heightmap
glGenVertexArrays(1, &uiVAOHeightmap); // Create one VAO
glGenBuffers(1, &uiVBOHeightmapData); // One VBO for data
glGenBuffers(1, &uiVBOIndices); // And finally one VBO for indices
glBindVertexArray(uiVAOHeightmap);
glBindBuffer(GL_ARRAY_BUFFER, uiVBOHeightmapData);
float fHeights[HM_SIZE_X*HM_SIZE_Y] =
{
10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f,
5.0f, 5.0f,5.0f, 10.0f, 10.0f, 10.0f,
5.0f, 5.0f, 5.0f, 10.0f, 10.0f, 10.0f,
5.0f, 5.0f, 10.0f, 10.0f, 10.0f, 10.0f,
10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f,
10.0f, 5.0f, 5.0f, 5.0f, 5.0f, 10.0f,
};
float fSizeX = 100.0f, fSizeZ = 100.0f;
for (int i = 0; i<HM_SIZE_X*HM_SIZE_Y;i++)
{
for (int j = 0; j < HM_SIZE_X*HM_SIZE_Y; j++)
{
float column = float(i%HM_SIZE_X), row = float(i / HM_SIZE_X);
vHeightmapData = glm::vec3(
-fSizeX / 2 + fSizeX*column / float(HM_SIZE_X - 1), // X Coordinate
fHeights, // Y Coordinate (it's height)
-fSizeZ / 2 + fSizeZ*row / float(HM_SIZE_Y - 1) // Z Coordinate
);
}
}
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*HM_SIZE_X*HM_SIZE_Y, vHeightmapData, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glGenBuffers(1, &uiVBOIndices);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, uiVBOIndices);
int iIndices[] =
{
0, 6, 1, 7, 2, 8, 3, 9, 4, 10, 5, 11, 36,
6, 12, 7, 13, 8, 14, 9, 15, 10, 16, 11, 17, 36,
12, 18, 13, 19, 14, 20, 15, 21, 16, 22, 17, 23, 36,
18, 24, 19, 25, 20, 26, 21, 27, 22, 28, 23, 29, 36,
24, 30, 25, 31, 26, 32, 27, 33, 28, 34, 29, 35
};
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(iIndices), iIndices, GL_STATIC_DRAW);
glEnable(GL_PRIMITIVE_RESTART);
glPrimitiveRestartIndex(HM_SIZE_X*HM_SIZE_Y);
}