游戲旋轉

紅色方塊能旋轉:


旋轉部件

在本教程前面的部分,紅色方塊能夠在游戲區域上移動,但無法轉動或旋轉。

要旋轉組件,我們必須改變繪制組件的方式。

canvas 元素唯一可用的旋轉方法將旋轉整個畫布:

您在畫布上繪制的其他所有內容也將被旋轉,而不僅僅是特定組件。

這就是為什么我們必須在 update() 方法中做一些更改:

首先,我們保存當前的畫布上下文對象:

ctx.save();

然后我們使用 translate 方法將整個畫布移動到特定組件的中心:

ctx.translate(x, y);

然后我們使用 rotate() 方法執行想要的旋轉:

ctx.rotate(angle);

現在我們準備將組件繪制到畫布上,但現在我們將在被平移(和旋轉)的畫布上將其中心位置繪制在位置 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();
}

親自試一試