HTML and CSS Reference
In-Depth Information
curY = p.y - viewY;
startX = curX;
while(curY < Q.height / scale) {
curX = startX;
while(curX < Q.width / scale) {
if(sheet) {
sheet.draw(ctx,curX + viewX, curY + viewY,p.frame);
} else {
ctx.drawImage(asset,curX + viewX, curY + viewY);
curX += p.repeatW;
if(!p.repeatX) { break; }
curY += p.repeatH;
if(!p.repeatY) { break; }
The init method, per usual, just sets up some initial defaults. It also defaults to the repeat width and height
to match the size of the image or asset so that tiles repeat perfectly by default.
The draw method is more complex; it needs to calculate the offset of each repeated tile. The preceding code
takes the easy way out. Instead of calculating the exact partial image to draw each of the corners, the class over-
draws tiles as necessary. Optimized code that handles the edge cases of rendering partial tiles at the edges and
corners is left as an exercise for you.
Some complication is added because the background might repeat only in the vertical or the horizontal dir-
ection. If the element isn't set to repeat in a direction, instead of calculating an offset using the modulus, the
position of the tile is set to the x or y position of the sprite minus the view.
On the other hand, if a tile repeats in a direction, first, the offset is calculated by using the sprite's position,
and the view's position is multiplied by the scrolling speed.
Finally, the drawing loop goes over each direction and starts from before the left side of the Canvas until
after the right side of the Canvas and from before the top side of the Canvas until after the bottom of the Canvas.
If the repeater is turned off in either direction, the loop just breaks out after the first cycle.
To try out the repeater, add a couple of scrolling backgrounds to the level:
Q.scene('level',new Q.Scene(function(stage) {
stage.insert(new Q.Repeater({ asset: 'background-wall.png',
speedX: 0.50, repeatY: false, y:-225
stage.insert(new Q.Repeater({ asset: 'background-floor.png',
speedX: 1.0, repeatY: false,
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 }));
Search WWH ::

Custom Search