Jump to content

Toggle overlap / collision detection once per update?


piotr
 Share

Recommended Posts

Hi all, this seems easy but all the examples I found destroy or remove overlap permanently. 

I need the sword to check overlap with enemies every time the space bar is pressed. That means enable overlap for 1 frame and then disable it the next frame.

I'm using animations on the sword to trigger the body but what I get at most is that the collisions happens 4 times per update

Is there a way to check overlap / collision only once per update?

export default class Play extends Phaser.Scene {

create() {
    //Player
    this.player = new Player(this, 0, 0);
	this.container = this.add.container(100, 100);
  	this.container.setSize(16, 16);
  	this.physics.world.enable(this.container);
  	this.container.add(this.player);

  	//Weapon
	this.meleeWeapon = new MeleeWeapon(this, 0, 0);
	this.physics.world.enable(this.meleeWeapon);
	this.container.add(this.meleeWeapon);
    
    //Enemy
	this.enemy = new Enemy(this, 600, 600);
	this.enemies = this.add.group();
	this.enemies.add(this.enemy)

	//Collisions
  	this.physics.add.overlap(this.meleeWeapon, this.enemies, this.onMeetEnemy, false, this);
	}

onMeetEnemy(weapon, enemy) {
   enemy.takeDamage(weapon.damage);
}

update() {
    if(this.spaceBar.isDown) {
	  this.meleeWeapon.attack();
	}
}

MeleeWeapon.js

export default class MeleeWeapon extends Phaser.Physics.Arcade.Sprite
{
    constructor (scene, x, y)
    {
      this.body.enable = false;
    }

attack ()
    {
        
        if(!this.isAttacking)
        {
            this.isAttacking = true;

            this.attackAnimation = this.anims.play('attack', false);

            this.attackAnimation.on('animationupdate', () => {
                
                if(this.attackAnimation.anims.currentFrame.index == 2)
                {
                    this.body.enable = true;
                } 
                else
                {
                    this.body.enable = false;
                };
            }); 

            this.attackAnimation.on('animationcomplete', () => {
                this.isAttacking = false;
            });          
        }

    }

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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