如何在碰撞动态移相器js中删除物质js对象

How to delete matter js object on collision dynamically phaser js

我正在制作一款平台游戏,其中有玩家和一些道具。为了检查碰撞,我使用了 matterjs collisionactive 函数:

this.matter.world.on("collisionactive", (e, o1, o2) => {
    
});

在函数内部,我需要从游戏中移除 powerup。所以我尝试了 o1.destroy ,其中 o1 是通电。这没有用,也没有 return 错误。我也试过this.matter.world.remove(o1);。这也不起作用。为什么我无法移除对象?任何帮助是极大的赞赏。谢谢!

有一些问题,如果你从他们的世界中删除对象。 best/cleanest的解决方法是使用GameObject.

destroy()方法

我会使用事件 collisionstart,检查 player 是否与 powerup 交互,然后销毁 gameObject。这也将清除物理对象。

这里有一个例子,基于上一个答案

let playertouchingground = true
const config = {
  type: Phaser.AUTO,
  width: 400,
  height: 180,
  physics: {
    default: "matter",
    matter: {
      debug: true
    }
  },
  scene: {
    create,
    update
  },
};

var game = new Phaser.Game(config);

function create() {
  ground = this.matter.add.sprite(0, 180, 'platform').setStatic(true).setScale(100, 1).setOrigin(0)
  ground.body.label = 'platform'
  ground.setCollisionCategory(1)

  player = this.matter.add.sprite(125, 140, 'player')
  player.body.label = 'player'
  player.setCollisionGroup(2)
  player.setFixedRotation()
  
  powerup = this.matter.add.sprite(140, 10, 'powerup').setBody('circle')
  powerup.body.label = 'powerup'
    powerup.setCollisionGroup(2)
  
    this.matter.world.on("collisionstart", (e, o1, o2) => {
      
      if([o1.label, o2.label].indexOf('powerup') != -1 &&
      [o1.label, o2.label].indexOf('player') != -1){
        o2.gameObject.destroy();
       }
  });

  this.matter.world.on("collisionend", (e, o1, o2) => {
      playertouchingground = true;
    }
  )
  
  this.cursors = this.input.keyboard.createCursorKeys();
}

function update() {
  if (this.cursors.left.isDown ) {
    player.setVelocityX(-3)
  } else if (this.cursors.right.isDown ) {
    player.setVelocityX(3)
  } else {
    player.setVelocityX(0);
  }

  if (this.cursors.up.isDown && playertouchingground ) {
    player.setVelocityY(-8)
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.23.0/phaser.min.js" ></script>

btw.: this.matter.world.remove(o1) should work, but doesn't hide/remove the image, as mentioned in this post. The solution is shown in the code above, since it works.