Jump to content

How should I check if an element from group A overlaps element from group B?


totallybueno
 Share

Recommended Posts

Hi there,

I have two groups, each one with 50 item placed randomly in the stage. I need to check if any of the items of group1 overlaps with any of the items of group2 (and then, destroy it) but I´m doing something wrong as all the elements of group 2 are being destroyed, it´s like is checking object1 with the whole group2... how can I check items by item? I have this code (not working properly)

function checkOverlaps(group1, group2){
    group1.forEachAlive(function(obj1){
        group2.forEachAlive(function(obj2){
            var boundsA = obj1.getBounds();
            var boundsB = obj2.getBounds();
            if(Phaser.Rectangle.intersects(boundsA, boundsB)){
                obj2.destroy();
            }
        }, this)
    }, this)
},

 

Link to comment
Share on other sites

overlap group vs. group is best.

If you prefer Phaser.Rectangle.intersects:

// If and only if both objects have anchor (0, 0), you can use
group1.forEachAlive(function (obj1) {
  group2.forEachAlive(function (obj2) {
    if (Phaser.Rectangle.intersects(obj1, obj2)) {
      obj2.destroy();
    }
  });
});

// Otherwise:
group1.forEachAlive(function (obj1) {
  var rect1 = new Phaser.Rectangle(obj1.left, obj1.top, obj1.width, obj1.height);
  group2.forEachAlive(function (obj2) {
    var rect2 = new Phaser.Rectangle(obj2.left, obj2.top, obj2.width, obj2.height);
    if (Phaser.Rectangle.intersects(rect1, rect2)) {
      obj2.destroy();
    }
  });
});

 

Link to comment
Share on other sites

On 10/8/2017 at 7:03 PM, Sturb said:

If you're using Arcade physics you could use:


update() {
    game.physics.arcade.overlap(groupA, groupB, onOverlap);
}

onOverlap(thing1, thing2) {
    // Do things!
}

https://phaser.io/docs/2.6.2/Phaser.Physics.Arcade.html#overlap
 

 

Is there a way to determine the actual objects overlapping instead of the group? I mean, in the callback function, I´d like to know which two items are overlapping to destroy one of them as if I thing1.destroy() I destroy de whole group, or do I need to loop inside the callback to check the items overlapping?

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...