Game Development Reference
In-Depth Information
function tick(e) {
if(!e.paused){
updateCircle();
renderCircle();
stage.update();
}
This simple game loop example will gradually move the circle across the screen horizontally. The
update
and
render
methods get called on each
game tick
, followed by the
update
call on stage to finalize the actual rendering of
your graphics.
■
Because of the dynamic nature of Javascript, you can easily “dynamically inject” properties and methods into
any object. in the previous example,
nextX
is a custom property injected into your circle shape. this approach will be
used many times in this topic as a way to quickly extend display objects by giving them extra, useful values.
Note
You might be wondering why you didn't simply change the x position in your
update
method. The reason you
want to keep these calls separated is because you rarely change the sprite's next position without first evaluating
its current locations and/or the game's current situation. You handle all of your physics logic within these
update
methods, separated from the function that ultimately
moves
them. In an even more complex game loop, you might
call on several
other
update
methods from here as well, where sprites or containers might handle calculations within
themselves.
Listing 2-5 shows an example of this process in action. Albeit a simple demonstration, it should give you an idea
on how the update/render cycle is executed within a game loop.
Listing 2-5.
Bouncing a Ball Against the Walls Using a Simple Update/Render Cycle
var stage = new createjs.Stage(document.getElementById('canvas'));
var direction = 1;
var speed = 10;
var circle = new createjs.Shape();
circle.graphics.beginStroke('#000');
circle.graphics.beginFill('#FFF000');
circle.graphics.drawCircle(0, 0, 50);
circle.radius = 50;
circle.x = 100;
circle.y = 300;
stage.addChild(circle);
createjs.Ticker.addEventListener("tick", tick);
createjs.Ticker.setFPS(60);
function updateCircle() {
var nextX = circle.x + (speed * direction);
if (nextX > stage.canvas.width - circle.radius) {
nextX = stage.canvas.width - circle.radius;
direction *= -1;
}
else if (nextX < circle.radius) {