لعبة الجاذبية


تمتلك بعض الألعاب قوى تسحب عنصر اللعبة في اتجاه واحد ، مثل الجاذبية التي تسحب الأشياء إلى الأرض.




الجاذبية

لإضافة هذه الوظيفة إلى مُنشئ المكونات لدينا ، أضف أولاً gravityخاصية تحدد الجاذبية الحالية. ثم أضف gravitySpeedخاصية ، والتي تزيد في كل مرة نقوم فيها بتحديث الإطار:

مثال

function component(width, height, color, x, y, type) {
  this.type = type;
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;
  this.speedX = 0;
  this.speedY = 0;
  this.gravity = 0.05;
  this.gravitySpeed = 0;
 
this.update = function() {
    ctx = myGameArea.context;
    ctx.fillStyle = color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
  this.newPos = function() {
    this.gravitySpeed += this.gravity;
    this.x += this.speedX;
    this.y += this.speedY + this.gravitySpeed;
  }
}


أصابة العمق

لمنع المربع الأحمر من السقوط إلى الأبد ، أوقف السقوط عندما يصل إلى أسفل منطقة اللعبة:

مثال

  this.newPos = function() {
    this.gravitySpeed += this.gravity;
    this.x += this.speedX;
    this.y += this.speedY + this.gravitySpeed;
    this.hitBottom();
  }
  this.hitBottom = function() {
    var rockbottom = myGameArea.canvas.height - this.height;
    if (this.y > rockbottom) {
      this.y = rockbottom;
    }
  }


تسريع

في اللعبة ، عندما يكون لديك قوة تسحبك للأسفل ، يجب أن يكون لديك طريقة لإجبار المكون على التسريع.

قم بتشغيل وظيفة عندما ينقر شخص ما على زر ، واجعل المربع الأحمر يطير في الهواء:

مثال

<script>
function accelerate(n) {
  myGamePiece.gravity = n;
}
</script>

<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">ACCELERATE</button>

لعبة

اصنع لعبة بناءً على ما تعلمناه حتى الآن:

مثال