mattbrand

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

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?

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

  • Recently Browsing   0 members

    No registered users viewing this page.