在动态生成的按钮上添加多个动作

时间:2018-11-08 18:37:19

标签: javascript phaser-framework

我已经动态生成了按钮。我想向此按钮添加click和onInputOver操作,但是只有click(chooseHero)按钮有效:

编辑FULL_CODE

var heroesState = {
  create: function() {
    //game.add.image(0, 0, 'board');
    backBtn = game.add.button(5, 5, 'back_btn', this.GoBack);
    choiceText = game.add.bitmapText(150, 50, 'desyrel', 'Welcome warrior, Choose your Hero', 35);

    //var heroCardStyle = { fill: "#00ff00" };

    var initWidth = 60;
    var initHeight = 150;

    var heroesFiles = ["obatala.jpg", "obba.jpg", "olokun.jpg", "orunmila.jpg", "oshun.jpg",
      "oxosi.jpg", "oya.jpg", "ozain.jpg", "shango.jpg", "yemoja.jpg"
    ];
    var heroesLength = heroesFiles.length;
    var heroCard = [];
    //4 buttons generated dynamically with a loop
    for (var i = 0; i < heroesLength / 2; i++) {
      //longueur de chaque élément dans heroes
      var ln = heroesFiles[i].length;
      heroCard = game.add.button(initWidth, initHeight, heroesFiles[i].substring(0, ln - 4), this.ChooseHero, this.over);
      heroCard.scale.setTo(0.5, 0.5);
      heroCard.alpha = 0.4;
      initWidth = initWidth + 150;
    };

    var initWidth = 60;
    var initHeight = 350;
    //4 buttons generated dynamically with a loop
    for (var i = heroesLength / 2; i < heroesLength; i++) {
      //longueur de chaque élément dans heroes
      var ln = heroesFiles[i].length;
      heroCard = game.add.button(initWidth, initHeight, heroesFiles[i].substring(0, ln - 4), this.ChooseHero, this.over);
      heroCard.scale.setTo(0.5, 0.5);
      heroCard.alpha = 0.4;
      initWidth = initWidth + 150;

    };
    //heroCard.onInputOver.add(over, this); 

  },
  //functions associated to button events(chooseChero works fine but over doesn't work)
  GoBack: function() {
    game.state.start("menu");
  },

  over: function() {
    heroCard.tint = 0xffffff;
  },

  ChooseHero: function() {
    //game.state.start("menu");
    chosenHero = this.key;
    alert(this.key);
    game.state.start("play", true, false, chosenHero);
  }
};

我收到此错误:无法读取未定义的属性'onInputOver'

1 个答案:

答案 0 :(得分:1)

从其他代码中,我可以看到以下问题:

  1. game.add.button()具有不同的签名。在the official docs中,我们可以看到它是:
  

新按钮(游戏[,x] [,y] [,键] [,回调] [,callbackContext] [,overFrame] [,outFrame] [,downFrame] [,upFrame])

overFrameoutFramedownFrameupFrame都在寻找要在要使用的图形上使用的框架,而不是要调用的函数。

  1. var heroCard = [];用于初始化变量,但随后将其设置为实际按钮。我可能建议将其更改为heroCards,然后在heroCard循环中创建一个新的for,在将其添加到heroCards数组之前在其中定义其属性。

  2. heroCard.onInputOver.add(over, this);应该在您的for循环内。如果您console.log(arguments);看到返回两个参数,则可以使用第一个参数来修改它们悬停的按钮:

    over: function(heroCard) {
        heroCard.tint = 0xffffff;
        // This is a quick and dirty way to see what arguments are being passed
        // to a function in JavaScript.
        // console.log(arguments);
    }