我已经从lwjgl.org网页(http://www.lwjgl.org/guide)编译了Get Started示例,现在我想继续更改为背景颜色。所以,我想要一些像闪烁效果的东西。但是,当程序运行时,我无法使用glClearColor
永久地切换其颜色。
我试图在glClearColor
的while循环中的loop()函数中执行此操作。但这似乎是错误的,因为glClearColor
方法只在while循环之外调用。例如,在下面的代码中,背景颜色采用最后使用glClearColor
调用的颜色。
...
private void loop() {
// This line is critical for LWJGL's interoperation with GLFW's
// OpenGL context, or any context that is managed externally.
// LWJGL detects the context that is current in the current thread,
// creates the ContextCapabilities instance and makes the OpenGL
// bindings available for use.
GLContext.createFromCurrent();
// Set the clear color
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
// Run the rendering loop until the user has attempted to close
// the window or has pressed the ESCAPE key.
while ( glfwWindowShouldClose(window) == GL_FALSE ) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer
/* Switch permanently between red and green background color
- doesn't work, no blinking, just green background color */
glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
glClearColor(0.0f, 1.0f, 0.0f, 0.0f);
glfwSwapBuffers(window); // swap the color buffers
// Poll for window events. The key callback above will only be
// invoked during this call.
glfwPollEvents();
}
}
...
我对lwjgl很新,因此我认为我犯了一些基本的错误,背景颜色不应该像我那样改变。有没有办法处理lwjgl中的背景来实现这个目标?
我应该提到我正在使用lwjgl 3,而不是lwjgl 2.而且似乎没有显示类了。 GLFW似乎是它的替代品。
答案 0 :(得分:1)
在下面的while循环中,假设每次迭代代表你的1帧。在场景中,只有在每次迭代后glfwPollEvents()
调用后才会看到更改。这就是为什么在一次迭代中改变颜色2次不会影响任何事情。
while ( glfwWindowShouldClose(window) == GL_FALSE ) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer
/* Switch permanently between red and green background color
- doesn't work, no blinking, just green background color */
glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
glClearColor(0.0f, 1.0f, 0.0f, 0.0f);
glfwSwapBuffers(window); // swap the color buffers
// Poll for window events. The key callback above will only be
// invoked during this call.
glfwPollEvents();
}
在下面,我为您的问题编写了一个简单的解决方案。如果你改变每一帧的颜色你都看不到变化,因为它会非常快,所以我做了一个小技巧,每30帧改变你的颜色。您可以使用时间相关的颜色变化而不是帧数来编写替代方案。
正确版本:
boolean redOrGreen = true; // true = Green false = Red
int counter = 0;
int COLORCHANGEAT = 30;
while ( glfwWindowShouldClose(window) == GL_FALSE ) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer
counter++;
if(counter == COLORCHANGEAT) {
redOrGreen = !redOrGreen;
counter = counter % COLORCHANGEAT;
}
if(redOrGreen == true)
glClearColor(1.0f, 1.0f, 0.0f, 0.0f);
else
glClearColor(0.0f, 1.0f, 0.0f, 0.0f);
glfwSwapBuffers(window); // swap the color buffers
// Poll for window events. The key callback above will only be
// invoked during this call.
glfwPollEvents();
}