Search code examples
javascriptcollisionphaser-frameworkoverlap

How can I destroy overlap between 2 objects Phaser 3


I am working on a game, where I add overlap between 2 objects, but after a certain action between them I want to destroy the overlap. I can't figured it out. Any help is appreciated.

Update function

 function checkOverlap(postava, rozcestnik) {
            var boundsA = postava.getBounds();
            var boundsB = rozcestnik.getBounds();
            return Phaser.Geom.Intersects.RectangleToRectangle(boundsA, boundsB);
        }


        if(this.keys.E.isDown && checkOverlap(this.postava, this.rozcestnik) == true)
        {

         this.colliderRozcestnik = this.physics.add.overlap(this.postava, this.rozcestnik, diaOknoRozcestnik.bind(this), null, this)

         this.physics.world.removeCollider(this.colliderRozcestnik);
         
        }


        function diaOknoRozcestnik(postava, rozcestnik)
        {
        postava.anims.play("left");
        this.gzDialog.visible;
        this.gzDialog.setText("I need to find some car mechanic to repair the engine.");
        }

Solution

  • Well you would just need to call the removeCollider in the function diaOknoRozcestnik.

    function diaOknoRozcestnik(){
        this.physics.world.removeCollider(this.colliderRozcestnik);
        //...
    }
    

    Or you could write a small wrapper like this:

    ...
    if(this.keys.E.isDown && checkOverlap(this.postava, this.rozcestnik) == true){
      this.colliderRozcestnik = this.physics.add.overlap( this.postava, this.rozcestnik,
        (...args) => {
          this.physics.world.removeCollider(this.colliderRozcestnik);
          diaOknoRozcestnik.call(this, ...args);
        });
    }
    ...
    

    Btw.: if you are using bind or call with this as the first parameter, you don't need to pass the this reference to the overlap function, and so you could also omit the null, shortening the whole call, as seen in the example above.

    Like this:

    this.colliderRozcestnik = this.physics.add.overlap(this.postava, this.rozcestnik, diaOknoRozcestnik.bind(this));