游戲重力

有些游戲中存在將游戲組件拉向一個方向的力,例如重力將物體拉向地面。


重力

如需將此特性添加到我們的組件構造函數中,請首先添加一個 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>

親自試一試

一個游戲

根據我們迄今為止所學到的知識制作一個游戲:

實例

親自試一試

請單擊加速按鈕開始游戲。

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