حركة اللعبة
مع الطريقة الجديدة لرسم المكونات ، الموضحة في فصل Game Rotation ، أصبحت الحركات أكثر مرونة.
كيفية نقل الكائنات؟
أضف speed
خاصية إلى component
المُنشئ ، والتي تمثل السرعة الحالية للمكون.
قم أيضًا بإجراء بعض التغييرات في 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()
الطريقة احسب
angle
بناءً على moveAngle
الخاصية:
مثال
اضبط الخاصية 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);
}
}
استخدم لوحة المفاتيح
كيف يتحرك المربع الأحمر عند استخدام لوحة المفاتيح؟ بدلاً من التحرك لأعلى ولأسفل ، ومن جانب إلى آخر ، يتحرك المربع الأحمر للأمام عندما تستخدم السهم "لأعلى" ، ويتحول لليسار ولليمين عند الضغط على السهمين الأيمن والأيسر.