1
我正在嘗試學習如何編寫一些代碼來繪製立方體並旋轉它。我決定用三角形繪製它們,在繪製立方體的三面之後,我很快意識到存在一個問題,即立方體的白色面會與紅色和藍色面重疊,藍色會與紅色面重疊。無法在LWJGL中繪製立方體
我也注意到: - 白臉繪製最後 - 藍臉的白臉 之前繪製 - 紅色的臉藍臉
我懷疑這可能是導致前繪製因爲白色是在紅色頂部的藍色和藍色上繪製的問題。
我在正確的軌道上嗎?任何人都可以幫我找到解決這個問題的辦法嗎?
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
public class RubiksCube {
int angle = 0;
public void start() {
final int width = 800;
final int height = 600;
try {
Display.setDisplayMode(new DisplayMode(width, height));
Display.create();
} catch (LWJGLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}
// init OpenGL here
while (!Display.isCloseRequested()) {
render();
angle = (angle+1)%360;
Display.update();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Display.destroy();
}
public void render(){
float edgeLength= 20.0f;
edgeLength /= 2.0f;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, Display.getDisplayMode().getWidth(), Display.getDisplayMode().getHeight(), 0.0f, -50.0f, 50.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear screen
glPushMatrix();
glTranslatef((Display.getWidth()/2), (Display.getHeight()/2), 0.0f);
glRotatef(angle, 1.0f, 1.0f, 1.0f);
glBegin(GL_TRIANGLES);
//Back
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(-edgeLength, edgeLength, edgeLength);
glVertex3f(-edgeLength, -edgeLength, edgeLength);
glVertex3f(edgeLength, -edgeLength, edgeLength);
glVertex3f(-edgeLength, edgeLength, edgeLength);
glVertex3f(edgeLength, edgeLength, edgeLength);
glVertex3f(edgeLength, -edgeLength, edgeLength);
//Front
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(-edgeLength, edgeLength, -edgeLength);
glVertex3f(-edgeLength, -edgeLength, -edgeLength);
glVertex3f(edgeLength, -edgeLength, -edgeLength);
glVertex3f(-edgeLength, edgeLength, -edgeLength);
glVertex3f(edgeLength, edgeLength, -edgeLength);
glVertex3f(edgeLength, -edgeLength, -edgeLength);
// Right
glColor3f(1.0f, 1.0f, 1.0f);
glVertex3f(edgeLength, edgeLength, -edgeLength);
glVertex3f(edgeLength, -edgeLength, -edgeLength);
glVertex3f(edgeLength, -edgeLength, edgeLength);
glVertex3f(edgeLength, edgeLength, -edgeLength);
glVertex3f(edgeLength, edgeLength, edgeLength);
glVertex3f(edgeLength, -edgeLength, edgeLength);
glEnd();
glPopMatrix();
}
}