Jump to content

How to call a class member function from a button within the class


mattbrand
 Share

Recommended Posts

I don't know how to call a class member function from a button declared within the same class. Here is my code:

class Player {
	constructor() {
		this.sprite = game.add.sprite(0, 0, "player");
		this.sprite.scale.setTo(scale.x, scale.y);
		this.sprite.x = gameWidth / 2;
		this.sprite.y = game.world.height - (this.sprite.height / 2);
		game.physics.p2.enable(this.sprite, false);
		this.sprite.body.setCircle(45 * scale.x);
		this.sprite.body.setCollisionGroup(playerCollisionGroup);
		this.sprite.body.collides(bubbleCollisionGroup, playerHitBubble, this);
		this.sprite.body.static = true;
		this.button = game.add.button(0, 0, "player", onClick);
		this.button.scale.setTo(scale.x, scale.y);
		this.button.anchor.setTo(0.5, 0.5);
		this.button.x = this.sprite.x;
		this.button.y = this.sprite.y;
		this.shootingMode = ShootingMode.SPLIT;
	}

	onClick() {
		console.log(this);
		if (this.shootingMode == ShootingMode.SPLIT) {
			this.shootingMode = ShootingMode.BOUNCE;
			this.sprite.tint = 0x000000;
		}
		else {
			this.shootingMode = ShootingMode.SPLIT;
			this.sprite.tint = 0xffffff;
		}
	}
}

As it is, I get the error message that onClick is not defined. But if i call it as "this.onClick", then "this" in the onClick function is the button, not the class instance.

Any ideas?

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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