遊戲移動
透過遊戲旋轉章節中解釋的新元件繪製方式,移動更加靈活。
如何移動物件?
在 component
建構函式中新增一個 speed
屬性,它表示元件的當前速度。
同時在 newPos()
方法中進行一些更改,以根據 speed
和 angle
計算元件的位置。
預設情況下,元件朝向上方,並將速度屬性設定為 1,元件將開始向前移動。
示例
function component(width, height, color, x, y) {
this.gamearea = gamearea;
this.width = width;
this.height = height;
this.angle = 0;
this.speed = 1;
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();
}
this.newPos = function() {
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
自己動手試一試 »
轉向
我們還希望能夠進行左轉和右轉。建立一個名為 moveAngle
的新屬性,它表示當前的移動值或旋轉角度。在 newPos()
方法中,根據 moveAngle
屬性計算 angle
。
示例
將 moveangle 屬性設定為 1,看看會發生什麼。
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.angle = 0;
this.moveAngle = 1;
this.speed = 1;
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();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
自己動手試一試 »
使用鍵盤
紅色方塊是如何在使用鍵盤時移動的?紅色方塊不再上下左右移動,而是當你按下“向上”箭頭時向前移動,按下左右箭頭時向左或向右轉動。