I want to pass a variable to the overlap function

There are functions that are the basis of each player.

function Player(_posX, _posY) {

	this.posX = _posX,
	this.posY = _posY,
	
	this.hp = 100,
	this.stamina = 500,
	this.damage = 10,
	
	this.attack = function(otherPlayer) {
		otherPlayer.hp -= this.damage;
	},
		
	this.beAttack = function() {
		this.hp -= 10;
	}
	
	this.defense = function(otherPlayer) {
		otherPlayer.hp -= this.damage / 10;
	}
}

If the two players overlap, I want to pass player2 through the third argument.

this.physics.add.overlap(player1, player2, player1.attack, isAttack, this);

I am using attack in the function below, but I feel like the code is wasting. I want to use as clean a code as possible.

this.physics.add.overlap(player1, player2, attack, isAttack, this);

the attack function

function attack() {
    player1.attack(player2);
}

Is there a simple way to pass player 2’s information in the overlap function?

Overlap handlers always receive the two bodies that overlapped as arguments. In this case, the variable you’re looking for is one of the two bodies, so you should be able to use the arguments that Phaser passes to your function.

If you want to avoid the attack function, which only serves calls player1.attack, you can use bind to force the context: this.physics.add.overlap(player1, player2, player1.attack.bind(player1), isAttack, this); If you do it this way, you can also pass arbitrary values into bind that will be given to the function as its first arguments.

Thank you for answer.
I haven’t read the link in detail yet, but I tried applying it first

Resolved code:
this.physics.add.overlap(player2, player1, player1.attack.bind(player1), isAttack, this);

…overlap(player1, player2… -> …overlap(player2, player1…

1 Like