2011-10-21 32 views
0

我正在創建一個Android 2D空間射擊遊戲作爲學習OpenGL的方式,並希望在遊戲中擁有繁星背景。我的想法是用白色斑點爲背景斑點背景,但點不顯示。首先是渲染代碼:在背景中的點不顯示

public void onSurfaceCreated(GL10 gl, EGLConfig config) { 

} 

public void onSurfaceChanged(GL10 gl, int w, int h) { 
    gl.glViewport(0, 0, w, h); 
    width = w; 
    height = h; 
    gl.glMatrixMode(GL10.GL_PROJECTION); 
} 

public void onDrawFrame(GL10 gl) { 
    // black background 
    gl.glClearColor(0f, 0f, 0f, 1.0f); 
    // clear the color buffer to show the ClearColor we called above... 
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT); 
    gl.glLoadIdentity(); 

    stars.draw(gl); 
} 

那麼明星們的繪畫:

private final FloatBuffer vertexBuffer; 
private int count; 

public Stars() { 
    Random r = new Random(); 
    count = (int) ((r.nextFloat() * 200.0f) + 200.0f); 
    count *= 3; 

    ByteBuffer buffer = ByteBuffer.allocateDirect(count * Float.SIZE); 
    buffer.order(ByteOrder.nativeOrder()); 

    // allocate _count number of floats 
    vertexBuffer = buffer.asFloatBuffer(); 

    float rVtx = (r.nextFloat() * 2.0f) - 1.0f; 
    for (int i = 0; i < count; i += 3) { 
     vertexBuffer.put(rVtx); 
     rVtx = (r.nextFloat() * 2.0f) - 1.0f; 

     vertexBuffer.put(rVtx); 
     rVtx = (r.nextFloat() * 2.0f) - 1.0f; 

     vertexBuffer.put(0.0f); 
    } 
} 

public void draw(GL10 gl) { 
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); 
    gl.glPointSize(3); 
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer); 

    gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); 
    gl.glDrawArrays(GL10.GL_POINTS, 0, count/3); 

    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); 
} 

似乎是什麼錯誤?

問候

回答

0

您需要設置onSurfaceChanged默認的投影矩陣。是這樣的:

gl.glMatrixMode(GL10.GL_PROJECTION);     
gl.glLoadIdentity();   
gl.glOrthof(-1, 1, -1, 1, -1, 1); 

gl.glMatrixMode(GL10.GL_MODELVIEW);     
gl.glLoadIdentity(); 

,並在星()結束時,把這個作爲最後一行:

vertexBuffer.position(0); 
+0

添加這給了我的屏幕,以便取得了一些成功,但不是中間的一個點隨機的星夜。此外,該點的顏色是黑色而不是白色...... – eldacar

+0

然後'gl.glOrtho(-1,1,-1,-1,-1,1);',你的星星在-1和1之間 –

+0

仍然只有一個點... – eldacar