2013-08-26 100 views
0

我正在開發的遊戲正在進步,越來越多的元素被添加,但我當然面臨着新的問題,其中之一就是性能。2D遊戲,性能改進?

目前,我有3個線程,其中兩個執行計算,另一個更新畫布。這三個線程與CyclicBarrier同步,以便在開始繪製畫布時完成所有計算。

我使用了幾個不同大小的位圖。在繪圖方法中,位圖正在旋轉(通過使用drawBitmap-matrix組合將縮放/平移/旋轉添加到矩陣中以「原生」(我猜)管理它),當然還有繪製。我面臨的問題是,只要屏幕上有太多「移動和旋轉」元素,就會變得不連貫。

Matrix matrix = new Matrix(); 
matrix.setTranslate(view.getX(), view.getY()); 
matrix.preScale((1.0f * view.getWidth()/view.getCurrentBitmap().getWidth()), (1.0f * view.getHeight()/view.getCurrentBitmap().getHeight())); 
matrix.postRotate(view.getRotation(), view.getX() + view.getWidth()/2f, view.getY() + view.getHeight()/2f); 
mCanvas.drawBitmap(view.getCurrentBitmap(), matrix, mBasicPaint); 

例如,這是根據旋轉和位置的玩家對象是如何被繪製:

private void drawPlayer(final Canvas mCanvas) { 
    final Bitmap playerBitmap = mPlayer.getCurrentBitmap(); 
    mPlayer.nextFrame(); 
    if(playerBitmap != null) { 
     if(mPlayer.getRotation() != 0) { 
      Matrix matrix = new Matrix(); 
      matrix.setTranslate(-mPlayer.getCurrentBitmap().getWidth()/2f, -mPlayer.getCurrentBitmap().getHeight()/2f); 
      matrix.postRotate(mPlayer.getRotation()); 
      matrix.postTranslate(mPlayer.getX() + + mPlayer.getCurrentBitmap().getWidth()/2f, mPlayer.getY() + mPlayer.getCurrentBitmap().getHeight()/2f); 
      matrix.postScale((1.0f * mPlayer.getWidth()/mPlayer.getCurrentBitmap().getWidth()), (1.0f * mPlayer.getHeight()/mPlayer.getCurrentBitmap().getHeight()), mPlayer.getX(), mPlayer.getY()); 
      mCanvas.drawBitmap(mPlayer.getCurrentBitmap(), matrix, mBasicPaint); 
     } else { 
      Matrix matrix = new Matrix(); 
      matrix.setScale((1.0f * mPlayer.getWidth()/mPlayer.getCurrentBitmap().getWidth()), (1.0f * mPlayer.getHeight()/mPlayer.getCurrentBitmap().getHeight())); 
      matrix.postTranslate(mPlayer.getX(), mPlayer.getY()); 
      mCanvas.drawBitmap(mPlayer.getCurrentBitmap(), matrix, mBasicPaint); 
     } 
    } else log("bitmap = null!"); 
} 

(這是一種不建議使用的版本中,.getCurrentBitmap()調用是在當前版本中減少到一個。)

我該如何提高性能?我應該創建某種「加載...」屏幕,其中我預加載了每個位圖(最大尺寸)和每個位圖的預旋轉版本? (這會導致,如果我以2-4度的步進走,每個位圖的90-180版本,這似乎很多..)或者,這與旋轉的位圖存儲以及太多記憶?我不知道任何關於OpenGL等,這就是爲什麼我使用SurfaceView,沒有其他遊戲引擎,我相信它也必須像這樣工作 - 不知何故。

+0

如果您繪製到屏幕外畫布,然後只需翻轉它們以呈現它,那麼該怎麼辦。將有兩個畫布(帆布?)需要太多內存爲您的應用程序? –

+0

但是這不會使情況變得更糟嗎?繪圖完成得很好,只是有很多旋轉,它正在放慢速度。將它繪製到另一個畫布上,然後複製畫布只需要更多的CPU時間,不是嗎? – damian

回答

0

您每次調用drawPlayer方法時都會創建一個Matrix(矩陣)和Bitmap(playerBitmap)對象。據我所知,你會每幀調用這個方法。因此,每個框架,您創建2個大對象,當您退出該方法時需要收集垃圾,這會減慢幀速率。您只能創建兩個對象matrixplayerBitmap作爲類級變量,並在每次調用drawPlayer時刷新它們,從而減少GC調用的次數。

+0

getCurrentBitmap執行以下操作:public Bitmap gettCurrentBitmap(){ return mResourceBitmaps [mFrame]; },在mResourceBitmaps(針對每個ViewObject實例)中,每個幀的位圖都在初次初始化對象時加載,所以這不應該創建位圖,而更可能返回引用?或者「最終的位圖位圖」總是創建一個全新的位圖,即使它只是參考? – damian

+0

從drawPlayer()的範圍中,每次調用它時,都會創建一個新的位圖對象(在此範圍內),並且當此對象超出範圍(drawPlayer()退出)時,此對象不再被引用,並且是垃圾收集(與Matrix對象相同) –