Jump to content

Recommended Posts

I want to create a dynamic interfaces for items in an inventory.

 

I need the items to be button to view that item. And want that button to calla  function with the item id as an argument.

 

inventory[index].button = game.add.button(inventory[index].x - (1030/2), inventory[index].y, 'equipmentButton', this.EquipItem, this);

 

...

 

EquipItem: function(index) {

 

};

Link to comment
Share on other sites

Hi, and welcome to Phaser wold :)

 

To make it more clear:

  • I will assume that you create your buttons in loop, "for" loop - for example..
  • your problem is how to provide "index" value in function event callback "EquipItem"
  • inventory array/object with "index" as a key is already an existing object
  • "EquipItem" is function part of "this" object and buttons are created in function also part of "this" object

 

Here you are, a three possible solutions:

 

1. Using Phaser "onInputDown" Signal event https://github.com/photonstorm/phaser/blob/v2.4.4/src/gameobjects/Button.js#L158

inventory[index].button = game.add.button(inventory[index].x - (1030/2), inventory[index].y, 'equipmentButton');inventory[index].button.onInputDown.add(this.EquipItem, this, 0 /* priority */, index);// But you will need to adjust your function like thisEquipItem: function (btnObj /* reference to button */, ev /* event object */, index /* your index provided value */) {    console.log("index: ", index);},

2. Using "bind" https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

inventory[index].button = game.add.button(inventory[index].x - (1030/2), inventory[index].y, 'equipmentButton', this.EquipItem.bind(this, index), this);

3. You can use closure

inventory[index].button = game.add.button(inventory[index].x - (1030/2), inventory[index].y, 'equipmentButton', (function (_this, index) {    return function () {        _this.EquipItem.call(_this, index);    }})(this, k));

Hope this will help you!

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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