Skip to content

How to detect overlap in Phaser.js?

I am new to Phaserjs, and I am trying to make a shooting game. I want the damage function to fire when a bullet touches plane2, that is the green plane. Can somone please tell me what am I doing wrong here? Here is my code:

 var config = {
        type: Phaser.AUTO,
        width: 800,
        height: 800,
        parent:"game",
        physics: {
            default: 'arcade',
            arcade: {
            debugging:true,
            gravity: {y: 0}   
            }
        },
        scene: {
            preload: preload,
            create: create,
            update: update
        }
    };
    var plane1
    var plane2
    var hp;
    var botHp;
    function preload (){
        this.load.setBaseURL('https://shoot.abaanshanid.repl.co/assets');
        this.load.image("bg", "bg.jpg");
        this.load.image("plane1", "plane1.png");
        this.load.image("plane2", "plane2.png");
        this.load.image("bullet", "bullet.png");
    }
    function create (){
       this.background = this.add.image(400, 400, "bg");
       plane1 =  this.physics.add.sprite(400,700,"plane1");
       plane2 =  this.physics.add.sprite(400,100,"plane2");
       plane1.enableBody = true;
    }
    function update(){ 
      keys = this.input.keyboard.createCursorKeys();
      if (keys.left.isDown) {
      plane1.x = plane1.x - 7.5;
      }else if(keys.right.isDown){
      plane1.x = plane1.x + 7.5;
      }else if(keys.space.isDown){
      var bullet = this.physics.add.sprite(plane1.x,600,"bullet");
      bullet.enableBody = true;
      setInterval(function(){
        bullet.y =  bullet.y - 25;
      },50);
      this.physics.overlap(bullet,plane2,this.damage);
      } 
    }
    function damage(){
        console.log("less HP")
    }
    var game = new Phaser.Game(config);
    
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.54.0/phaser.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.54.0/phaser-arcade-physics.min.js"></script>
  </head>
  <body>
    <div id="game"></div>
    <script defer src="script.js"></script>
  </body>
</html>

Here is the link to the game if needed https://shoot.abaanshanid.repl.co/

Answer

This works:

this.physics.add.overlap(bullet,plane2,damage);

but its kinda laggy. Id try to destroy bullet on impact and i also found:

this.physics.add.collider(bullet,plane2,damage);