javascriptcollision-detectionphaser-framework

How to handle collision-end in arcade physics


I need to show some icon, when player overlap with game object and hide it when collision with the object ended

i tried this :

create() {
    this.physics.add.overlap(player,obj,()=>{
        this.objCollide = true;
    });
}

update() {
    if(this.objCollide){
        this.icon.setAlpha(1);
    }else{
        this.icon.setAlpha(0);
    }
}

It works, but when player collide with the object, icon starts flicker, because update function sets alpha 0, but then, after millisecond sets alpha 1. I don't like that flicker effect. So how can i do something like that : this.physics.add.overlapEnd(player,obj, func) ?


Solution

  • An easy solution would be to just to use the this.physics.overlap function in the update function, and setting there the Alpha.

    Watchout: this.physics.overlap not this.physics.add.overlap, the first does once a check, the later, adds a eventlistener for overlaps.

    Small Demo:

    document.body.style = 'margin:0;';
    
    var config = {
        type: Phaser.AUTO,
        width: 536,
        height: 183,
        physics: {
            default: 'arcade',
            arcade: {            
                gravity:{ y: 100 },
            }
        },
        scene: {
            create,
            update
        },
    }; 
    
    function update(){
    
        if(this.physics.overlap(this.box1, this.box2)) {
            this.box2.setAlpha(.5)
        } else {
            this.box2.setAlpha(1)
        }
    }
    
    function create () {
        this.add.text(10,10, 'Overlap')
            .setScale(1.5)
            .setOrigin(0)
            .setStyle({fontStyle: 'bold', fontFamily: 'Arial'});
    
        let graphics  = this.make.graphics();
        graphics.fillStyle(0xffffff);
        graphics.fillRect(0, 0, 10, 10);
        graphics.generateTexture('img', 10, 10);
        
        this.box1 = this.physics.add.image(50, 10, 'img').setDepth(100);
        this.box2 = this.add.rectangle(0, 100, 550, 50, 0xff0000)
          .setOrigin(0);
        
        this.physics.add.existing(this.box2, true);
    }
    
    new Phaser.Game(config);
    <script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>