opengl中的颜色在黑色和红色之间振荡

Color oscillates between black and red in open gl

我用 lwjgl 3 和 opengl 写了一些 java classes,它们创建了一个 window 红色,但颜色实际上可能在红色和背面之间的每一帧之间振荡这是window class

的代码

此 window class 用作主要 class 中的对象,其中有一个游戏循环

package engine.io.output;

import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT;

import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.*;

import engine.io.input.*;

public class Window {
public int width , height;
public String title;
long time;
int frames = 0;
private long window;
public KeyInput keyInputCallBack = new KeyInput();
MouseButtonInput mouseButtonInput = new MouseButtonInput();
MousePositionInput mPositionInput = new MousePositionInput();
public Window(int width , int height , String title) {
    this.width = width;
    this.height = height;
    this.title = title;
}
public void create() {
    time = System.currentTimeMillis();
    if (!glfwInit()) {
        System.err.println("Couldnt init");
        System.exit(-1);
    }
    window = glfwCreateWindow(width, height, title,0, 0);
    
    if (window == 0) {
        System.err.println("cannot create window");
        System.exit(-1);
    }
    GLFWVidMode vm = glfwGetVideoMode(glfwGetPrimaryMonitor());
    
    int windowXPos = vm.width()/2 - width/2;
    int windowYPos = vm.height()/2 - height/2;
    
    glfwSetWindowPos(window, windowXPos,windowYPos);
    
    addCallback(window);
    glfwMakeContextCurrent(window);
    
    GL.createCapabilities();
    GL11.glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
    GL11.glClear(GL11.GL_COLOR_BUFFER_BIT |GL_DEPTH_BUFFER_BIT);
    glfwShowWindow(window);
    glfwSwapInterval(1);
    
}
private void addCallback(long window2) {
    glfwSetKeyCallback(window,keyInputCallBack.getKeyCallback());
    glfwSetMouseButtonCallback(window2, mouseButtonInput.getbuttonCallback());
    glfwSetCursorPosCallback(window2, mPositionInput.getMousePositionCallback());
}
public void update() {
    frames++;
    if (System.currentTimeMillis() >= time + 1000) {
        glfwSetWindowTitle(window,"fps is " + frames);
        frames = 0;
        time = System.currentTimeMillis();
    }
    glfwPollEvents();
}
public void render() {
    glfwSwapBuffers(window);
}
public boolean shouldClose() {
    return glfwWindowShouldClose(window);
    
}}

如何停止振荡

根据上面的评论,在您的原始代码中,您似乎只在创建 window 时清除一次,而通常您会在每帧清除一次。 (我猜你看到的闪烁是由于多个帧缓冲区中只有一个被清除为红色,但这只是一个猜测。)

请注意,尽管 update() 中的清除(如您上面提到的)可能有效,但取决于环境的设置方式,render() 函数可能更适合执行此操作。调用 update() 时上下文很可能是当前的,因此您可以在那里进行渲染,但至少在概念上,最好将更新逻辑和渲染保留在各自的专用函数中。