1

我从游戏开发开始,为了掌握事情的窍门,我认为使用 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 的一个非常基本的方面,但是我怎样才能加载这些图像而不会使它们变形呢?


编辑: 这是精灵的渲染函数(使用由返回的bufferID loadAndBufferImage()

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();
4

0 回答 0