Game Development Reference
In-Depth Information
function butterflyGone(){
stage.removeChild(this);
}
Here your butterfly fades out, and when complete, calls a function named butterflyGone , which then removes it
from the stage. You can already see how this will be important to your game development. This function might also be
used to remove a reference from an object pool, add points to a scoreboard, and/or determine if the user has caught
enough to advance to the next level.
Callbacks are common in JavaScript programming. What differentiate them from regular functions is that the
time in which they are called is completely independent from other surrounding code that is being executed. In other
words it's out of order, or asynchronous .
An example would be when using AJAX to fetch data from a server. You need a function to process that data and
execute other commands when the service is complete. With your butterfly animation, you need to know when that
animation is complete so you can handle it while still carrying on with your game logic.
Notice that by default the callback function is scoped to the Tween 's target, butterfly . This may not always be
the behavior you want. In the examples so far, you are working directly in the global scope of window , so it's easy for
you to continue referencing any other global variable or function in your application. But as your games progress
you won't be working in this global manner, but instead inside other objects and instances. You'll often times need
to access to an object's properties and functions within your callbacks, and in many situations you'll lose sight of
them completely.
There a few other helpful arguments you can pass into call to help you manage with scope in asynchronous
situations. Take a look at the example shown in Listing 1-3.
Listing 1-3. Setting Callback Scope in Tweeners call Method
var Game = {
score:0,
init:function () {
this.drawButterfly();
},
drawButterfly:function () {
var imgPath = 'images/butterfly.png';
var butterfly = new createjs.Bitmap(imgPath);
stage.addChild(butterfly);
createjs.Tween.get(butterfly).to({y:100}, 1000).call(this.butterflyGone,
[butterfly],this);
},
butterflyGone:function (butterfly) {
stage.removeChild(butterfly);
this.score += 10;
this.gameOver();
},
gameOver:function () {
alert('score: ' + this.score);
}
}
This example's code is all encapsulated into an object named Game . When you get to the callback function,
you need to maintain a reference to the object it's contained in so you can set its score property and reach its other
methods. You managed to do this by first passing a reference to your butterfly instance to the callback through the
second argument in call . You do this instead of keeping it the default scope that calls the callback function. This
argument takes an array where you can pass as many values as you want to the callback.
Search WWH ::




Custom Search