[英]Make background blink with lwjgl
我已經從lwjgl.org網頁( http://www.lwjgl.org/guide )編譯了“入門”示例,現在我想不斷地更改為背景色。 所以,我想要一個閃爍效果。 但是在程序運行時,我沒有背景使用glClearColor
永久地切換其顏色。 我嘗試使用glClearColor
在while循環的loop()函數中執行此glClearColor
。 但這似乎是錯誤的,因為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,而不是lwjgl2。而且似乎不再有Display Class。 GLFW似乎可以代替它。
在下面的while循環中,認為每個迭代代表1幀。 在您的場景中,只有在每次迭代后調用glfwPollEvents()
之后,您才會看到更改。 這就是為什么一次迭代更改兩次顏色不會產生任何影響的原因。
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.