游戲運動
通過利用游戲旋轉章節中講解的繪制組件的新方式,動作現在更加靈活了。
如何移動物體?
在 component
構造函數中添加一個 speed
屬性,該屬性代表組件當前的速度。
還要對 newPos()
方法進行一些更改,以根據 speed
和 angle
計算組件的位置。
默認情況下,組件面朝上,通過將 speed
屬性設置為 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); } }
使用鍵盤
使用鍵盤時紅色方塊如何移動?當您使用“向上”箭頭時,紅色方塊不會向上和向下,而是會從一側移動到另一側向前移動,并且會在按向左和向右箭頭時左右旋轉。
實例
確保游戲區域獲得焦點,然后使用箭頭鍵移動紅色方塊。