ゲーム重力

一部のゲームでは、ゲームコンポーネントを特定の方向に引き寄せる力が存在します。例えば、重力は物体を地面に引き寄せます。


重力

この特性を私たちのコンポーネントの構築関数に追加するには、まず以下を追加してください 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>

実際に試してみてください

ゲーム

今まで学んだことを基にゲームを作成してください:

実際に試してみてください

ゲームを開始するには、加速ボタンをクリックしてください。

どれくらい生きられるか?加速ボタンを使用して空中に保持してください。