第九章 Libgdx内存管理
Android游戲開發群:290051794
Libgdx游戲開發框架交流群:261954621
?
游戲是使用資源較多的應用。圖像和音效會占用大量的內存。此外,這些資源大部分不是通過java的垃圾回收器管理,而是由本地驅動管理。使用垃圾回收器對紋理等進行回收不是一個明智的做法。
我們需要合理的控制資源的生命周期。在Libgdx中有多個類實現這個功能。它們都實現Disposable接口指明在生命周期結束后要銷毀的類的實例。錯誤的釋放資源會導致內存泄露。
下面的類需要手工處理:
AssetManager
Bitmap
BitmapFont
BitmapFontCache
CameraGroupStrategy
DecalBatch
ETC1Data
FrameBuffer
Mesh
ParticleEffect
Pixmap
PixmapPacker
ShaderProgram
Shape
Skin
SpriteBatch
SpriteCache
Stage
Texture
TextureAtlas
TileAtlas
TileMapRenderer
com.badlogic.gdx.physics.box2d.World
當資源不再使用應盡快的進行釋放,釋放與它們有關的內存。訪問一個已經釋放的資源會導致未定義錯誤,所以要處理所有資源的引用。
當你想知道一個類是不是需要釋放,檢查它是否有dispose()方法。如果有,那么你正在使用本地資源。
對象池
對象池是重新使用閑置的或“死掉”的對象,而不是每次都創建新的對象。這通過一個對象池實現,當你需要一個對象時,從對象池中獲得。如果對象池有可用的對象,則返回。如果對象池是空的,或者沒有閑置的對象,會創建一個對象的一個新的實例并返回。當你不再需要一個對象,并釋放它。就意味著它返回到對象池。通過這種方式,對象分配的內存重新被使用。
對于需要生成大量對象,比如子彈,障礙,怪物等等,的游戲來說,這對內存管理是重要的。
Libgdx對簡單池提供了一些工具:
Poolable interface
Pool
Pools
實現Poolable接口意味著你需要在對象中實現reset()方法,它會自動的釋放你的對象。
下面是一個簡單的例子:
public class Bullet implements Poolable {public Vector2 position;public boolean alive;/*** Bullet 構造函數,初始化變量。.*/public Bullet() {this.position = new Vector2();this.alive = false;}/*** 初始化Bullet當從對象池中獲取Bullet是調用。*/public void init(float posX, float posY) {position.set(posX, posY);alive = true;}/***對象空閑的回調方法,自動被 Pool.free()調用。*/public void reset() {position.set(0,0);alive = false;}/*** 更新*/public void update (float delta) {// update bullet positionposition.add(1*delta*60, 1*delta*60);// if bullet is out of screen, set it to deadif (isOutOfScreen()) alive = false;}} 在游戲中:public class World() {// array containing the active bullets.private final Array<Bullet> activeBullets = new Array<Bullet>();// bullet pool.private final Pool<Bullet> bulletPool = new Pool<Bullet>() {@Overrideprotected Bullet newObject() {return new Bullet();}};public void update(float delta) {// if you want to spawn a new bullet:Bullet item = bulletPool.obtain();item.init(2, 2);activeBullets.add(item);// if you want to free dead bullets, returning them to the pool:Bullet item;int len = activeBullets.size;for (int i = len; --i >= 0;) {item = activeBullets.get(i);if (item.alive == false) {activeBullets.removeIndex(i);bulletPool.free(item);}}}}
Pools類提供了動態創建任何對象池的靜態方法。在上面的示例中,可以這樣使用:
作者:宋志輝?
出處:http://blog.csdn.net/song19891121
本文版權歸作者所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。?
支持:?新浪微博?騰訊微博
?
轉載于:https://www.cnblogs.com/hainange/archive/2013/05/27/6153548.html
總結
以上是生活随笔為你收集整理的第九章 Libgdx内存管理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 又要说离开了!
- 下一篇: 全球首发5.5G 高通骁龙X75基带不再