Search code examples
javascriptgame-developmentphaser-frameworkphaserjs

Find Which Object is in Collision In Phaser


I have multiple objects in my static group and need to know which one I am colliding with when my player hits one of the objects. My code looks like this:

//Create Function
  signs = this.physics.add.staticGroup()

  sign1 = signs.create(0, -100, "sign1")
  sign1.name = "sign1";
  sign1Info = this.add.image(0, -100, "sign1").setScale(4);
  sign1Info.visible = false;

  sign2 = signs.create(100, -100, "sign2")
  sign2.name = "sign2";
  sign2Info = this.add.image(100, -100, "sign2").setScale(4);
  sign2Info.visible = false;

  this.physics.add.collider(player, signs){
    signName = sign.name; //The info I need to get out
  });

I tried this:

this.physics.add.collider(player, signs, function (sign){
    signName = sign.name;
 });

but when I printed the sign.name to the console it was an 'empty string'

How can I find the specific object the player is colliding with?


Solution

  • The documentation is not very specific about the topic. It just states that

    An optional callback function that is called if the objects collide

    Reading the sourcecode here, it looks like both collided objects are passed as arguments, being the first object, in your case, the player. Thats probably the reason that you're getting an empty string, because your player does not have a name.

    According to your code, the name would be available in the second parameter of the callback function, like the following:

    // note the added parameter to the function declaration
    this.physics.add.collider(player, signs, function (player, sign){
        signName = sign.name;
        // console.log(sign.name) should show the name of the sign as expected
    });
    

    I cannot replicate your scenario since I dont have the full code to try it out, but it should work. If you still dont get the name, do a console.log(sign). It should reference the object you expect, but maybe the property name is not directly on the object but on one subpropery. Let me know