我开始进行游戏开发,为了解决问题,我认为使用GLFW将是一个很好的开始。我遵循了一个基本的教程,并且有一个基本功能的简单游戏。
我的问题是在教程中,当设置OpenGL窗口时,它使用glBufferData
的固定顶点:
typedef struct {
GLfloat positionCoordinates[3];
GLfloat textureCoordiantes[2];
} VertexData;
VertexData vertices[] = {
{{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f}},
{{50.0f, 0.0f, 0.0f}, {1.0f, 0.0f}},
{{50.0f, 50.0f, 0.0f}, {1.0f, 1.0f}},
{{0.0f, 50.0f, 0.0f}, {0.0f, 1.0f}}
};
void GameWindow::setupGL() {
glClearColor(0.05f, 0.05f, 0.05f, 1.0f);
glViewport(0, 0, _width, _height);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0, _width, 0, _height);
glMatrixMode(GL_MODELVIEW);
glGenBuffers(1, &_vertexBufferID);
glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferID);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(VertexData), (GLvoid *) offsetof(VertexData, positionCoordinates));
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, sizeof(VertexData), (GLvoid *) offsetof(VertexData, textureCoordiantes));
}
据我所知,这是正确的练习,这是有道理的,但所有加载的纹理都符合这个大小。因此,即使图像具有不同的分辨率,它们仍然会延伸到该垂直的规格。
GLuint GameWindow::loadAndBufferImage(const char *filename) {
GLFWimage imageData;
glfwReadImage(filename, &imageData, NULL);
GLuint textureBufferID;
glGenTextures(1, &textureBufferID);
glBindTexture(GL_TEXTURE_2D, textureBufferID);
std::cout << "Width:" << imageData.Width << " Height:" << imageData.Height << std::endl;
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageData.Width, imageData.Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData.Data);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glfwFreeImage(&imageData);
return textureBufferID;
}
我知道这必须是OpenGL的一个非常基本的方面,但是如何在不使它们变形的情况下加载这些图像呢?
<小时/> 修改 这是sprite的render函数(使用loadAndBufferImage()
返回的bufferID)
void Sprite::render() {
glBindTexture(GL_TEXTURE_2D, _textureBufferID);
glLoadIdentity();
glTranslatef(_position.x, _position.y, 0);
glRotatef(_rotation, 0, 0, 1.0f);
glDrawArrays(GL_QUADS, 0, 4);
}
编辑2:
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(0,0,0);
glTexCoord2f(1.0f, 0.0f); glVertex3f(width,0,0);
glTexCoord2f(1.0f, 1.0f); glVertex3f(width,height,0);
glTexCoord2f(0.0f, 1.0f); glVertex3f(0,height,0);
glEnd();