在OpenGl中创建Model类

时间:2016-03-28 05:33:04

标签: c++ opengl

大家好我想在opengl中创建一个模型类,并在游戏中创建一个模型类的实例。我能够只渲染一个对象而第二个对象不渲染。

当所有这些都在同一个班级时,我遇到了同样的问题。我为bot创建了一个单独的VBO和VAO,并解决了问题。

现在我正在尝试创建一个类,现在我面临同样的问题。因为它是一个类,不是单独的VAO和VBO创建??

我的模型类和游戏类如下。

#include "FlatModel.h"

#include "Camera.h"

GLfloat vertices[] = {

//position              
-0.5f, -0.5f, 0.0f,   
-0.5f, 0.5f, 0.0f,   
0.5f, 0.5f, 0.0f,     
0.5f, -0.5f, 0.0f    
};

GLuint indices[] = {
// front
0, 1, 2,
0, 2, 3
};


 FlatModel::FlatModel(Camera* _camera, glm::vec3 color) {

camera = _camera;
objectColor = color;

ShaderLoader *shaderLoader = 0;
program = shaderLoader->CreateProgram("shaders/FlatModel.vs","shaders/FlatModel.fs");

glEnable(GL_DEPTH_TEST);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

glGenBuffers(1, &vbo);
glGenBuffers(1, &ebo);

glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices),  indices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}

FlatModel::~FlatModel() {
}

void FlatModel::update(GLfloat time) {

GLint currentTimeLocation = glGetUniformLocation(program, "currentTime");
glUniform1f(currentTimeLocation, time);

GLint objectColorLoc = glGetUniformLocation(program, "objectColor");
glUniform3f(objectColorLoc, objectColor.x, objectColor.y, objectColor.z);

glm::mat4 mvp = camera->getprojectionMatrix() * camera->getViewMatrix() * model;
GLint mvpLoc = glGetUniformLocation(program, "mvp");
glUniformMatrix4fv(mvpLoc, 1, GL_FALSE, glm::value_ptr(mvp));
}


 void FlatModel::render() {

glUseProgram(this->program);
glBindVertexArray(vao);

glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);

}

这是游戏类

#include "Game.h"

void Game::GameInit(){

camera = new Camera(45.0f, WIDTH, HEIGHT, 0.1f, 100.0f);
camera->setCameraSpeed(0.05f);

ground = new FlatModel(camera, glm::vec3(1.0f, 1.0f, 0.5f));
ground->setScale(glm::vec3(3.0f, 0.5f, 1.0f));
ground->setPosition(glm::vec3(0.0f, -0.5f, 0.0f));

box = new FlatModel(camera, glm::vec3(1.0f, 0.0f, 0.0f));
box->setScale(glm::vec3(1.0f, 0.5f, 1.0f));
box->setPosition(glm::vec3(0.0f, 0.5f, 0.0f));
}

void Game::GameUpdate(){

camera->update();

GLfloat currentTime = glutGet(GLUT_ELAPSED_TIME);
currentTime = currentTime / 1000;

ground->update(currentTime);
box->update(currentTime);
}

void Game::GameDraw(){

glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

ground->render();
box->render();

}

这是输出。只有框显示,地面不显示。

enter image description here

1 个答案:

答案 0 :(得分:1)

你必须将制服传递给着色器,而不是在更新中的Draw调用中。因为您在Draw中激活了着色器。

检查此示例 http://in2gpu.com/2015/06/04/drawing-a-cube/