如何在Phaser中重新创建炸弹对象?点击按钮恢复已销毁炸弹
解决Phaser中炸弹销毁后重新生成的问题
问题根源
- 全局变量管理不当,场景内访问实例易出现作用域冲突
- 重新创建炸弹时未正确绑定物理碰撞规则
update方法未判断炸弹实例是否存在,销毁后执行操作会引发报错- 使用
new bomb是错误用法——bomb是Phaser生成的Sprite实例,而非可实例化的构造函数
修复后的完整代码
class Scene1 extends Phaser.Scene { constructor() { super("bootGame"); // 声明场景实例属性 this.player; this.bomb; this.platform; this.keyboard; this.addbombBtn; } preload() { this.load.image("background", "./assets/ice.png"); this.load.image("platform", "./assets/platform.png"); this.load.image("snowman", "./assets/snowman.png"); this.load.image("bomb", "./assets/war-bomb.png"); } create() { this.add.image(0, 0, "background").setOrigin(0, 0); this.player = this.physics.add.sprite(100, 100, "snowman"); // 调用封装的炸弹创建函数 this.createBomb(); // 创建添加炸弹按钮 this.addbombBtn = this.add.image(600, 100, "bomb").setInteractive(); this.addbombBtn.on("pointerdown", () => { // 仅当炸弹已销毁时重新创建 if (!this.bomb || !this.bomb.active) { this.createBomb(); console.log("bomb_added"); } }); this.platform = this.physics.add.staticGroup(); this.platform.create(400, 500, "platform").setScale(2).refreshBody(); this.physics.add.collider(this.player, this.platform); this.physics.add.collider(this.player, this.bomb, this.handleBombCollision, null, this); this.player.setCollideWorldBounds(true); this.keyboard = this.input.keyboard.createCursorKeys(); } // 封装炸弹创建逻辑,实现代码复用 createBomb() { this.bomb = this.physics.add.sprite(500, 200, "bomb"); this.bomb.setCollideWorldBounds(true); this.bomb.setBounce(1); // 绑定炸弹与平台的碰撞 this.physics.add.collider(this.bomb, this.platform); } // 炸弹碰撞处理函数 handleBombCollision() { this.bomb.disableBody(true, true); console.log("collide:true"); } update() { // 先判断炸弹是否存在且活跃,再执行操作 if (this.bomb && this.bomb.active) { this.bomb.setRotation(this.bomb.rotation + 0.15); this.bomb.body.setGravity(0, 200); } if (this.keyboard.left.isDown) { this.player.setVelocityX(-150); } else if (this.keyboard.right.isDown) { this.player.setVelocityX(150); } else { this.player.setVelocityX(0); } if (this.keyboard.up.isDown && this.player.body.touching.down) { this.player.setVelocityY(-150); } } } var config = { type: Phaser.AUTO, width: 768, height: 512, backgroundColor: 0x22566, scale: { autoCenter: Phaser.Scale.CENTER, }, scene: [Scene1], physics: { default: "arcade", arcade: { gravity: { y: 100, }, }, }, }; var game = new Phaser.Game(config);
关键修改说明
- 将全局变量改为场景
this属性,避免作用域冲突 - 新增
createBomb函数封装炸弹创建、属性配置、碰撞绑定逻辑,初始化和重新创建均可复用 - 按钮点击事件中增加炸弹状态判断,防止重复创建
update方法中先校验炸弹实例状态,避免销毁后执行操作引发错误- 碰撞处理函数改为场景方法,确保正确访问
this.bomb实例
内容的提问来源于stack exchange,提问作者baseus827
相关产品推荐
相关产品推荐

