ccgbagnet

Proper Sprite Button Events management

Recommended Posts

I've just started learning pixi.js 2 days ago and I'm stuck with this.

I'm trying to register mouse button events on 3 different buttons which I generate this way.

function initializeButtons(bg: PIXI.Graphics) {
	let xPos = (canvasWidthHeight/2) - 130;
	for(let i = 0; i < 3; i++) {
		let temp = PIXI.Sprite.fromImage(BOX_SPRITES[0]);
		temp.scale.set(0.5);
		temp.anchor.set(0.5, 0.5);

		temp.position.x = xPos;
		temp.position.y = canvasWidthHeight / 2;

		temp.interactive = true;
		temp.buttonMode = true;

		temp.on('pointerdown', function() {onClick(i);} );


		rewardBoxes.push(temp);
		bg.addChild(temp);

		xPos += 120;
	}
}

However, everytime I try to click on any button, it's always the last button that gets clicked. What is the proper way to achieve this? Thank you!

Share this post


Link to post
Share on other sites

Try to use something like this ..

 

function createClickListener(temp, i) {
      temp.pointerdown = function() {
        onClick(i);
      };
  }

 

Call this function in the body of your loop

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.