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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

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