Gerakan Permainan
Dengan cara baru menggambar komponen, dijelaskan di bab Rotasi Game, gerakannya lebih fleksibel.
Bagaimana Memindahkan Objek?
Tambahkan speed
properti ke component
konstruktor, yang mewakili kecepatan komponen saat ini.
Juga membuat beberapa perubahan dalam newPos()
metode, untuk menghitung posisi komponen, berdasarkan speed
dan angle
.
Secara default, komponen menghadap ke atas, dan dengan menyetel properti kecepatan ke 1, komponen akan mulai bergerak maju.
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);
}
}
Berbelok
Kami juga ingin bisa berbelok ke kiri dan ke kanan. Buat properti baru yang disebut moveAngle
, yang menunjukkan nilai bergerak saat ini, atau sudut rotasi. Dalam newPos()
metode menghitung
angle
berdasarkan moveAngle
properti:
Contoh
Setel properti moveangle ke 1, dan lihat apa yang terjadi:
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);
}
}
Gunakan Keyboard
Bagaimana kotak merah bergerak saat menggunakan keyboard? Alih-alih bergerak ke atas dan ke bawah, dan dari sisi ke sisi, kotak merah bergerak maju saat Anda menggunakan panah "atas", dan berbelok ke kiri dan kanan saat menekan panah kiri dan kanan.