欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Phaserjs3 对象池随机产生炸弹并销毁

程序员文章站 2022-05-18 22:53:40
使用对象池 Object Pool产生炸弹,首先创建一个对象组 this.exploadGroup = this.add.group(); 然后用对象组的.get重复应用对象池而不是用.create,this.exploadGroup.get(x,y,'explode'); 最后销毁的时候不是用.d... ......


Phaserjs3 对象池随机产生炸弹并销毁
效果图
Phaserjs3 对象池随机产生炸弹并销毁
对象池 object pool

scene.js

/// <reference path="../../libs/phaser/phaser.min.js"/>
 
'use strict';
var bootscene = new phaser.class({
    extends: phaser.scene,

    initialize: function bootscene() {

        phaser.scene.call(this, {
            key: 'boot',
            active: true // listening resize event;
        });
   
    },
    init: function () {
        console.log('init bootscene');
        this.particles = {};
    },

    preload: function () {
        this.load.image('sky', 'assets/space.jpg');
        this.load.spritesheet('explode','assets/explode.png',{framewidth:128,frameheight:128})
  },

    create: function () {
        // this.sound.play('hitbomb');
        this.background = this.add.sprite(0, 0, 'sky').setorigin(0, 0);
        this.createexplode();
 
    },
    update:function(){
        // console.log('bootscene update');
    },
    
    createexplode:function(){
        //* single image;
        // this.add.sprite(200,200,'explode',10);
        this.anims.create({
            key: 'explodeanimation',
            frames: this.anims.generateframenumbers('explode', { start: 0, end: 16, first: 0 }),
            framerate: 25,
            repeat: 0
        });
        //* pool group
        this.exploadgroup = this.add.group();
        
        this.time.addevent({
            delay: 2500, //  
            repeat: -1,
            callbackscope: this,
            callback: this.spawnrandomexplode
        });
    },
    spawnrandomexplode:function(){
        let x = phaser.math.between(10, this.sys.game.config.width);
        let y = phaser.math.between(10,this.sys.game.config.height);
       // this.add.sprite(x,y,'explode').setscale(0.7).play('explodeanimation');
        let singleexplode = this.exploadgroup.get(x,y,'explode'); //* get to pool instead of create
        singleexplode.setscale(0.7).play('explodeanimation'); //* play animation;
        singleexplode.setactive(true);
        singleexplode.setvisible(true);

        // explosion lifespan
        this.explosiontimeevent = this.time.addevent({
            delay: 600, // delay 5s 删除 this.bomb;
            repeat: 0,
            callbackscope: this,
            callback:function(){
                this.exploadgroup.killandhide(singleexplode);
              //*  this.explosiontimeevent.remove(false);
            }
        });
            
        
    }, 

});

效果预览地址:http://www.ifiero.com/uploads/phaserjs3/randombombeffect

更多游戏教学:http://www.ifiero.com -- 为游戏开发深感自豪