我正在用OpenGL + C ++编写游戏。
生成动画的唯一方法是在glutDisplayFunc
内定义一个无限循环。而我做到了。但是想象一下我有不同的gameObject,每个对象都有其draw()
函数。
但是我想要一个函数来添加另一个对象。当我将它们保存在指针数组中时,此函数如下所示:
void display() {
while (running) {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer
if(objects_count != 0)
for(unsigned int i = 0; i< objects_count - 1; i++) {
(objects + i)->drawAsPoint();
}
glFlush();
usleep(f60FPS);// Render now
}
}
bool addRenderableObjectSync(GameEntity *object) {
running = false;
if(objects_count + 1>= objects_capacity) {
//reallocating memory
objects_capacity = round(objects_capacity * 1.5f);
GameEntity * _new_objects = new GameEntity[objects_capacity];
for(unsigned int i = 0; i < objects_count; i++) {
_new_objects[i] = objects[i];
}
//now objects are safe to delete free
delete[] objects;
//now we move new array to objects and free the temporary one
objects = _new_objects;
delete[] _new_objects;
}
objects[objects_count] = *object;
objects_count++;
//delete *object as it no longer needed;
delete object;
return true; }
running
是一个布尔值,它对显示函数内部的循环做出响应。
但是,绘制循环是无限的,我认为我需要一些可以破解running
状态的异步函数,例如:
void Renderer::addRenderableObject(GameEntity *object) {
//the reason we do it cause a game is in infinite loop which never ends
//so we stop the game, add an object, and after fn finish we let it run again
std::future<bool> fut = std:: async(addRenderableObjectSync, object);
running = fut.get();
}
这是正确的解决方案吗?还是有更好的方法?