游戏重力

有些游戏中存在将游戏组件拉向一个方向的力,例如重力将物体拉向地面。


gravity

ຖ້າຕ້ອງການສະເໜີຄວາມມູນຄ່ານີ້ເຂົ້າໃນພວກປະກອບວຽກສ້າງພັນທະບັດສະຖານະທີ່ຕ້ອງການ, ກໍ່ຕ້ອງການເພີ່ມພວກມັນຫນັງກ່ອນ. 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)">ກະຕຸ້ນ</button>

亲自试一试

一个游戏

根据我们迄今为止所学到的知识制作一个游戏:

实例

亲自试一试

请单击加速按钮开始游戏。

能活多久?请使用加速按钮保持在空中。