1 回答
TA贡献1828条经验 获得超3个赞
您可以定义将创建砖对象的对象构造函数。然后,您可以从此对象读取砖块的属性以进行渲染。
function Brick(x,y,width,height){ // as inputs you take the position and size
this.x = x; // adding attributes to the object based on the values that were entered
this.y = y;
this.width = width;
this.height = height;
}
当我们要创建一个brick对象时,我们调用函数如下:
var brick = new Brick(x,y,width,height); //whatever values you want it to have
解决方案的第二部分是将所有砖对象存储在一个数组中:
var bricks = [];//initialise the array
var brickWidth = 30;//the default dimensions of the bricks. Change these to be whatever you want
var brickHeight = 10;
var xBrickPadding = 5;//the default spacing between bricks
var yBrickPadding = 5;
var minX = 0; // the dimensions of the area in which you want your bricks to be
var maxX = 100;
var minY = 0;
var maxY = 50;
//when you want to add your bricks to the array, probably at the start of the game or whenever you refresh, use a loop like this:
for(let x = minX; x<maxX; x+= brickWidth+xBrickPadding){ //loop over the x coordinates
for(let y = minY; y<maxY; y+= brickHeight+yBrickPadding){//loop over the y coordinate
bricks.push(new Brick(x,y,brickWidth,brickHeight)); //add our new brick to the array at each x and y position
}
}
我们现在在适当的位置有一个充满砖块的数组,但是我们需要在屏幕上渲染它们。让我们定义一个 renderBricks 函数,这样我们就不必在每个动画帧都渲染它们,只有当我们需要更新它们时:
renderBricks = function(){
for(brick of bricks){//loop over every brick stored in the array
c.beginPath();
c.rect(brick.x,brick.y,brick.width,brick.height);//read the relevant properties from the brick object in order to render it
c.fill();
c.closePath();
}
}
代码的最后一部分是在砖块被击中时移除砖块的逻辑。将此代码添加到您的 createBall 函数中,以便在每次球的位置更改时检查它。
for(brick of bricks){//loop over every brick
if(){//insert your condition here to check if the ball has collided or not. You can use the properties brick.x, brick.y, brick.width and brick.height
bricks.splice(bricks.indexOf(brick),1); //if so, remove the brick from the array
renderBricks(); // then, render the bricks again so the brick no longer appears on the screen
}
}
这是解决您的问题的一种可能方法。希望能帮助到你!
添加回答
举报