如何在使用Cordova的相位游戏中避免高内存使用

How to avoid high memory usage in Phaser game using Cordova?

本文关键字:高内存 内存 Cordova 游戏      更新时间:2023-09-26

我开发了一个Cordova Phaser游戏。它可以在Android和iOS设备上运行。

游戏有7个关卡,每个关卡都有一些精灵(背景,玩家)和群组(子弹,敌人)。

preload函数中,我已经加载了所有图像和atlasJSONHash

function preload(){
    game.load.atlasJSONHash('anim', 'anim.png', 'anim.json');
    //and so on
}
function create(){
     var star = game.add.sprite(160, 32, 'level1bg');
     star.x = 0;
     star.y = 0;
     star.height = game.height;
     star.width = game.width;
     bullets = game.add.group();
     bullets.enableBody = true;
     bullets.physicsBodyType = Phaser.Physics.ARCADE;
     bullets.createMultiple(30, 'bullet');
     bullets.setAll('anchor.x', 0.5);
     bullets.setAll('anchor.y', 1);
     bullets.setAll('outOfBoundsKill', true);
     bullets.setAll('checkWorldBounds', true);
     //and so on
}
function startlevel(level)
{
     var star = game.add.sprite(160, 32, 'level1bg');
     star.x = 0;
     star.y = 0;
     star.height = game.height;
     star.width = game.width;
     bullets = game.add.group();
     bullets.enableBody = true;
     bullets.physicsBodyType = Phaser.Physics.ARCADE;
     bullets.createMultiple(30, 'bullet');
     bullets.setAll('anchor.x', 0.5);
     bullets.setAll('anchor.y', 1);
     bullets.setAll('outOfBoundsKill', true);
     bullets.setAll('checkWorldBounds', true);
     //and so on
}

当关卡结束时,我调用startlevel(2),以此类推。

在浏览器中它运行得很好,但是在移动内存中每关都会加倍,最终导致应用崩溃。如何避免这个内存问题?

我希望这对你有帮助。在分配新组之前,为了确保旧组被销毁,我总是在它上调用destroy,然后重新分配一个新组。移开,我想你会想创建一个新的函数init你的子弹组,并重复使用它。

function createBulletGroup(){
    if(bullets!=null)
    { 
         bullets.destroy(true);
         bullets = null; 
    }
    //.. The rest of add group
}

更多,因为你使用

var star = game.add.sprite(160, 32, 'level1bg');

每次你开始关卡,一个新的星星将被放置在旧的星星上,因为它们的位置是相同的。当star被创建时,它将被分配给world。并且多次重新创建星型,造成肉眼看不到的内存泄漏。

你可以尝试在开始新关卡时随机放置星星,看看它是否与其他星星重叠,或者将alpha设置为0.5;