حرکت بازی
- صفحه قبلی چرخش بازی
- صفحه بعدی تصاویر HTML
پیشنهاد دوره:
بازی دوباره
چگونه میتوانیم یک شیء را حرکت دهیم؟ در
component سرعت
در کنار این، یک
تنظیم شود که این ویژگی، که مقدار سرعت فعلی component را نشان میدهد. newPos()
و سرعت
روشها تغییراتی ایجاد میکنیم، تا بر اساس angle
و
به طور پیشفرض، سطح component به سمت بالا است و برای محاسبه موقعیت component از سرعت
تنظیم شود که 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); {} {}
استفاده از صفحه کلید
چگونه میتوانم با استفاده از صفحه کلید مربع قرمز را حرکت دهم؟ وقتی که از کلید
مثال
مطمئن شوید که منطقه بازی تمرکز دارد، سپس از کلیدهای شتاب به حرکت دادن مکعب قرمز بپردازید.
- صفحه قبلی چرخش بازی
- صفحه بعدی تصاویر HTML