HTML and CSS Reference
In-Depth Information
this.y = this.centerY - Q.height / 2 / this.scale;
},
predraw: function() {
Q.ctx.save();
Q.ctx.translate(Q.width/2,Q.height/2);
Q.ctx.scale(this.scale,this.scale);
Q.ctx.translate(-this.centerX, -this.centerY);
},
postdraw: function() {
Q.ctx.restore();
}
});
The initial added method doesn't do much except set up the viewport parameters as necessary. This sets up
the initial centerX and centerY positions; a scale mulitiplier to control how large the game should rescale
the sprites and events; and the x and y to determine the position of the top left of the window.
Next, the stage is extended with three methods: follow , unfollow , and centerOn . These enable the
developer to tell the view to follow the position of a specific sprite, unfollow that sprite, and manually center
the viewport on a specific pixel location. follow and unfollow simply bind and unbind an event handler
that calls the component's centerOn each step. The entity's centerOn method also is just a proxy for the
component's method.
Next, the component's centerOn method sets the centerX and centerY and then calculates the x and
y locations from the center, width of the Canvas, and the scale.
The predraw method does all the work to set up the viewport transform. It saves the current transform,
centers the context in the window, does any necessary rescaling, and then moves the top left of the window by
the wanted center values.
The postdraw method undoes all the transforms by simply calling restore on the context.
To test this method, modify the Q.scene code in animation.js as highlighted in the following code:
Q.scene('level',new Q.Scene(function(stage) {
var player = stage.insert(new Q.Player({ x:100, y:50, z:2 }));
stage.insert(new Q.Block({ x:800, y:160, z:1 }));
stage.insert(new Q.Block({ x:550, y:160, z:1 }));
stage.add('viewport');
stage.follow(player);
Q.input.bind('action',stage,function() {
stage.viewport.scale = stage.viewport.scale == 1 ? 0.5 : 1;
});
}, { sort: true }));
This adds a viewport onto the stage, sets it to follow the player, and then adds a handler to allow the user to
play with the scale amount by pressing the action key (the b button on mobile devices).
Search WWH ::




Custom Search