Jump to content

Problems with states and functions game.time.events.add


Recommended Posts

I'm working with different states. Where I have all code of gameplay called "ingame" 
Ok, I'll use it when calling the game.time.events.add function receives the following parameters: 
game.time.events.add (1000, this.myFunction, this, arguments);
Use this follow: 
add(delay, callback, callbackContext, arguments)
So far so good. The problem comes when wanting to use this function from an extended sprite update (created by me). When I call the function from there "this" refers to the sprite, so you can not put "this" in the third parameter of the function. 

The context when I use this is SpriteExtended.prototype.update = function() { ... } , so, the "callbackContext" parameter which is now?
What should I put? 
Thank you !!
Link to comment
Share on other sites

  • 2 months later...
  • 4 months later...

Similar problem here, also totally noob, my code (From an excellent tutorial):

launchGreenEnemy () {    let MIN_ENEMY_SPACING = 300;    let MAX_ENEMY_SPACING = 3000;    let ENEMY_SPEED = 300;    let enemy = greenEnemies.getFirstExists(false);    if (enemy) {        enemy.reset(this.game.rnd.integerInRange(0, this.game.width), -20);        enemy.body.velocity.x = this.game.rnd.integerInRange(-300, 300);        enemy.body.velocity.y = ENEMY_SPEED;        enemy.body.drag.x = 100;    }    //  Send another enemy soon    this.game.time.events.add(this.game.rnd.integerInRange(MIN_ENEMY_SPACING, MAX_ENEMY_SPACING), this.launchGreenEnemy);  }

the part that sends another enemy fails, like loosing context, throwing:


Uncaught TypeError: Cannot read property 'game' of undefined


On the first line after the IF (enemy.reset(this.game.rnd.integerInRange(0, this.game.width), -20);).


 Any help would be appreciated.


Link to comment
Share on other sites

  • 3 months later...

I know it's old but for future reference, the launchGreenEnemy problem is probably a JavaScript scoping issue -- that is, the "this" object refers to something other than the global "this" object. Usually this sort of error happens when you call a function from inside a callback or something similar. The (hack) fix is:


var that = this;


    enemy.reset(that.game.rnd.integerInRange(0, that.game.width), -20); <-"that" refers to the container variable which points to the global "this"


Link to comment
Share on other sites


  • Recently Browsing   0 members

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