Jump to content

Callback function cannot access game object


frokenstein
 Share

Recommended Posts

It seems my kill sprite callback function has no access to any scope. I am trying to update a var and I cannot do it from within the callback this.killAsteroid().

 

I start with this:

asteroid.events.onOutOfBounds.add(this.killAsteroid, asteroid);

My kill function is like so:

killAsteroid: function(asteroid) {// Kill asteroid that is out of bounds or has collided with somethingasteroid.kill();console.log("asteroid killed");this.asteroidCount--;console.log("Asteroid count after kill: " + this.asteroidCount);}

I can kill the asteroid, apparently. But this.asteroidCount is NaN or undefined. I can access this variable from every other function in the app except here, and I presume it's because of scoping of this callback. How can I update this.asteroidCount from within this function? Even if I use this.game.asteroidCount or Starpatrol.Game.asteroidCount it also returns NaN.

Link to comment
Share on other sites

var that = this;asteroid.events.onOutOfBounds.add(function(asteroid){// Kill asteroid that is out of bounds or has collided with somethingasteroid.kill();console.log("asteroid killed");that.asteroidCount--;console.log("Asteroid count after kill: " + that.asteroidCount);}, asteroid);
var that = this;asteroid.events.onOutOfBounds.add(function(asteroid){that.killAsteroid(asteroid, that);}, asteroid);

Two different ways to do this for you.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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