2016-11-30 48 views
0

我已經在libGdx中做了一個簡單的自定義actor。LibGdx渲染多個自定義演員的性能

public class HealthBar extends Actor { 
private Texture background; 
private Texture bar; 
private float max; 
private float current; 

public HealthBar(Color bgColor, Color barColor) { 
    Pixmap bgPixmap = new Pixmap(1, 1, Pixmap.Format.RGB565); 
    bgPixmap.setColor(bgColor); 
    bgPixmap.drawPixel(0, 0); 
    background = new Texture(bgPixmap); 
    bgPixmap.dispose(); 
    Pixmap barPixmap = new Pixmap(1, 1, Pixmap.Format.RGB565); 
    barPixmap.setColor(barColor); 
    barPixmap.drawPixel(0, 0); 
    bar = new Texture(barPixmap); 
    barPixmap.dispose(); 
} 

@Override 
public void draw(Batch batch, float parentAlpha) { 
    batch.draw(background, getX(), getY(), getWidth(), getHeight()); 
    batch.draw(bar, getX(), getY(), getBarEnd(), getHeight()); 
} 

private float getBarEnd() { 
    return current/max * getWidth(); 
} 

public void setHealth(float current, float max) { 
    this.current = current; 
    this.max = max; 
} 

public void dispose(){ 
    background.dispose(); 
    bar.dispose(); 
} 

}

我'在組渲染此大約30上階段2d上。

問題是渲染會導致我花費20幀/秒左右。呈現相同數量的簡單標籤沒有明顯的性能影響。我在這段代碼中缺少一些東西?這些Actor被添加到使用Stage呈現的組中。

performance when drawing

performance with draw() content commented

回答

2

通過爲您的背景分開紋理對象,你是導致SpriteBatch有沖洗兩次提請您HealthBars的每一個。每當SpriteBatch接收到一個命令以繪製與繪製的最後一個紋理不匹配的紋理時,SpriteBatch都必須進行刷新。

(無關,也實在是很浪費的要創建相同的紋理這麼多的副本 - 它會更有意義創建一個單一的白色圖像,並擁有所有的健康酒吧使用它)

的正確的方法是將純白色圖像放入TextureAtlas中,其餘圖像用於UI中並在演員中使用。在繪製背景之前,您可以在該批次上調用setColor,然後使用白色紋理區域,使其看起來像您想要的任何顏色。這大大減少或消除了批量沖洗(當Stage完成繪圖時,除了最後一個)。

但是,除非您正在非常低端的手機或Android模擬器上進行測試,否則額外的60批次刷新通常不足以導致如此大的幀速下降。 Android模擬器無法獲得設備實際性能的印象。

+0

謝謝你的好評!我認爲只有當我調用flush()方法時纔會刷新批處理。它在低端Android設備上進行了測試。在Nvidia Shield平板電腦遊戲中,該手機擁有20-30fps的穩定60fps。 –