【问题标题】:How to avoid high memory usage in Phaser game using Cordova?如何在使用 Cordova 的 Phaser 游戏中避免高内存使用?
【发布时间】:2016-10-22 12:39:07
【问题描述】:

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

游戏有七个关卡,每个关卡都有多个精灵(背景、玩家)和组(子弹、敌人)。

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)等等。

在浏览器中它运行良好,但在移动内存中每个级别都会翻倍,应用程序最终会崩溃。如何避免这个内存问题?

【问题讨论】:

    标签: javascript cordova phaser-framework


    【解决方案1】:

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

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

    更多,因为你使用

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

    每次你开始升级时,都会在旧星上放置一个新星,因为它们的位置是相同的。当star被创建时,它将被分配到世界。并且多次重新创建star会导致肉眼看不到的内存泄漏。

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

    【讨论】:

    • 我是否理解正确,我们应该在销毁后始终设置 NULL ref?似乎 Phaser 只是清理精灵中的道具而不是删除对象
    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2023-03-26
    • 2010-10-19
    • 1970-01-01
    • 2014-05-21
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多