1 回答

TA貢獻1828條經(jīng)驗 獲得超3個贊
您可以定義將創(chuàng)建磚對象的對象構(gòu)造函數(shù)。然后,您可以從此對象讀取磚塊的屬性以進行渲染。
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;
}
當我們要創(chuàng)建一個brick對象時,我們調(diào)用函數(shù)如下:
var brick = new Brick(x,y,width,height); //whatever values you want it to have
解決方案的第二部分是將所有磚對象存儲在一個數(shù)組中:
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
}
}
我們現(xiàn)在在適當?shù)奈恢糜幸粋€充滿磚塊的數(shù)組,但是我們需要在屏幕上渲染它們。讓我們定義一個 renderBricks 函數(shù),這樣我們就不必在每個動畫幀都渲染它們,只有當我們需要更新它們時:
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 函數(shù)中,以便在每次球的位置更改時檢查它。
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
}
}
這是解決您的問題的一種可能方法。希望能幫助到你!
添加回答
舉報