Jump to content

How to move and check collision in a group of objects, instead of whole group?


CarlosBR
 Share

Recommended Posts

I could make the group move and collide with the map, but the the code only works for all of them at once.  When one of the group hits the map, all group starts moving the opposite direction they were going, instead of only the object who hit the map. I'm using createFromObjects to create the Group.

I created a flag to check if they're going right or left. I suppose this flag should be unique to all of them instead one for all group, but I'm learning Phaser3 and trying to make things work one step at time. Here's the code (only the part that matters):
 

create() {
        
        this.right = true;        
        this.enemies = this.physics.add.group();
        this.enemies = map.createFromObjects('enemies_objects', 'enemy1', { key: 'enemies' });   
        this.physics.add.collider(this.layer, this.enemies, this.bounce, null, this);    
        
}

update() {      
        this.moveEnemies();       
}

moveEnemies() {
        this.enemies.forEach((enemy) => {
            if(enemy instanceof Phaser.GameObjects.Sprite) {
                if(this.right === true) {
                    enemy.body.setVelocityX(-20);
                }
                else {
                    enemy.body.setVelocityX(20);
                }
            }
        });
}

bounce() {
        if(this.right === true) {
            this.right = false;            
        }
        else {
            this.right = true;            
        }
 }

Thanks in advance for any help.

 

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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