Gerakan Permainan
- Hal Sebelumnya Putar Permainan
- Hal Berikutnya Grafik HTML
通過利用遊戲旋轉章節中講解的繪製组件的新方式,動作現在更加靈活了。
如何移动物体?
在 component
構造函數中添加一個 speed
屬性,該屬性代表组件當前的速度。
還要對 newPos()
方法進行一些更改,以根據 speed
和 angle
計算组件的位置。
默認情況下,组件面朝上,通過將 speed
屬性設置為 1,组件将开始向前移动。
Contoh
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
:
Contoh
請將 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); } }
使用键盘
如何使用键盘移动红色方块?當您使用“向上”箭頭時,红色方块不會向上和向下,而是會從一側移動到另一側向前移動,並且會在按向左和向右箭頭時左右旋轉。
Contoh
Pastikan kawasan permainan mendapat fokus, lalu gunakan tombol panah untuk gerakkan kubu merah.
- Hal Sebelumnya Putar Permainan
- Hal Berikutnya Grafik HTML