遊戲旋轉
紅色方塊可以旋轉
旋轉元件
在本教程的早期,紅色方塊可以在遊戲區域內移動,但無法轉動或旋轉。
要旋轉元件,我們必須改變繪製元件的方式。
canvas 元素唯一可用的旋轉方法將旋轉整個 canvas。

您在 canvas 上繪製的所有內容也將被旋轉,而不僅僅是特定元件。
因此,我們需要在 update()
方法中進行一些更改。
首先,我們儲存當前的 canvas 上下文物件。
ctx.save();
然後,我們使用 translate 方法將整個 canvas 移動到特定元件的中心。
ctx.translate(x, y);

然後,我們使用 rotate() 方法執行所需的旋轉。
ctx.rotate(angle);

現在,我們可以在 canvas 上繪製元件了,但現在我們將以其中心位置在轉換後的(和旋轉後的) canvas 的 0,0 位置繪製它。
ctx.fillRect(width / -2, height / -2, width, height);

完成後,我們必須使用 restore 方法將上下文物件恢復到其儲存的位置。
ctx.restore();
元件是唯一旋轉的部分。

元件建構函式
名為 component
的建構函式有一個名為 angle
的新屬性,它是一個弧度數,表示元件的角度。
名為 component
的建構函式的 update
方法是繪製元件的地方,您可以在此處看到允許元件旋轉的更改。
示例
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.angle = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.angle += 1 * Math.PI / 180;
myGamePiece.update();
}
自己動手試一試 »