LIBGDX版NEHE OPENGL- 3. Adding Color
opengl在给图形加颜色时,需要为每一点指定比如:
glColor3f(1.0f,0.0f,0.0f);
// Set The Color To Red
glVertex3f( 0.0f, 1.0f, 0.0f);
// Move Up One Unit From Center (Top Point)
glColor3f(0.0f,1.0f,0.0f);
// Set
The Color To Green
glVertex3f(-1.0f,-1.0f, 0.0f);
//
Left And Down One Unit (Bottom Left)
glColor3f(0.0f,0.0f,1.0f);
// Set The Color To Blue
glVertex3f( 1.0f,-1.0f, 0.0f);
// Right And Down One Unit (Bottom Right)
在libgdx中,我们相应的给mesh添加上颜色的属性,全部代码如下:
package com.kyugao.screen; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; public class AddingColor implements Screen { private Mesh triangleMesh, squareMesh; private PerspectiveCamera camera; @Override public void render(float delta) { camera.update(); camera.apply(Gdx.graphics.getGL10()); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); drawGLScene(); } private boolean drawGLScene() { triangleMesh.render(GL10.GL_TRIANGLES, 0, 3); squareMesh.render(GL10.GL_TRIANGLE_STRIP, 0, 4); return true; } @Override public void show() { triangleMesh = new Mesh(true, 3, 3, new VertexAttribute(Usage.Position, 3, "a_position"), new VertexAttribute(Usage.ColorPacked, 4, "a_color")); squareMesh = new Mesh(true, 4, 4, new VertexAttribute(Usage.Position, 3, "b_position"), new VertexAttribute(Usage.ColorPacked, 4, "b_color")); triangleMesh.setVertices(new float[] { // -1.5f, 1.0f, -6.0f, // point 1 Color.toFloatBits(1f, 0f, 0f, 1f), // color 1 -2.5f, -1.0f, -6.0f, // point 2 Color.toFloatBits(0f, 1f, 0f, 1f), // color 2 -0.5f, -1.0f, -6.0f,// point 3 Color.toFloatBits(0f, 0f, 1f, 1f) // color 3 }); triangleMesh.setIndices(new short[] { 0, 1, 2 }); squareMesh.setVertices(new float[] { 0.5f, -1.0f, -6.0f,// point BL Color.toFloatBits(0.5f, 0.5f, 1f, 1f), // color 1 2.5f, -1.0f, -6.0f,// point BR Color.toFloatBits(0.5f, 0.5f, 1f, 1f), // color 1 0.5f, 1.0f, -6.0f, // point TL Color.toFloatBits(0.5f, 0.5f, 1f, 1f), // color 1 2.5f, 1.0f, -6.0f, // point TR Color.toFloatBits(0.5f, 0.5f, 1f, 1f) // color 1 }); squareMesh.setIndices(new short[] { 0, 1, 2, 3 }); } @Override public void hide() { } @Override public void pause() { } @Override public void resume() { } @Override public void dispose() { } @Override public void resize(int width, int height) { float aspectRatio = (float) width / (float) height; camera = new PerspectiveCamera(45, 2f * aspectRatio, 2f); } }显示效果如下:
![](http://img-my.csdn.net/uploads/201304/19/1366375716_5260.png)