如何在游戏中添加多个块

use*_*496 0 javascript html5 canvas html5-canvas

我试图做一个简单的突围赛象这样.我正在使用HTML5 Canvas + JavaScript.

我的问题是我不知道如何添加多个块(有效).

我可以加一个; 但是我不能在不改变这个的情况下添加另一个:

var block = {
    width: 75,
    height: 20,
    x: 212,
    y: 0
};

ctx.fillRect(block.x, block.y, block.width, block.height);
Run Code Online (Sandbox Code Playgroud)

对此:

var block2 = {
    width: 75,
    height: 20,
    x: 300,
    y: 0
};
ctx.fillRect(block2.x, block2.y, block2.width, block2.height);
Run Code Online (Sandbox Code Playgroud)

必须有一种比手动创建新变量和使用ctx.fillRect游戏中每个块更好的方法.如果有人能告诉我如何,我将非常感谢,谢谢!

请查看此JSFiddle以供参考:http://jsfiddle.net/3hEJJ/1/

小智 7

您可以创建一个包含自我更新方法的可实例化对象,而不是使用对象文字:

function Block(x, y, w, h) {
   this.x = x;
   this.y = y;
   this.width = w;
   this.height = h;
}

Block.prototype.update = function(ctx) {
   ctx.fillRect(this.x, this.y, this.width, this.height); 
};
Run Code Online (Sandbox Code Playgroud)

现在您可以创建一堆对象:

var blocks = [];

for(var i = 0; i < 100; i++) {
    // get the x,y ... from somewhere, f.ex. another array
    blocks.push(new Block(x, y, w, h));
}
Run Code Online (Sandbox Code Playgroud)

要更新然后只需调用:

for(var i = 0; i < blocks.length; i++) {
    blocks[i].update(ctx);
}
Run Code Online (Sandbox Code Playgroud)