Game Gravity

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


重力

如需将此特性添加到我们的组件构造函数中,请首先添加一个 gravity 属性,该属性设置当前的重力。然后添加一个 gravitySpeed 属性,每当我们更新帧时它都会增加:

Examples

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;
  }
}

Try it yourself

触底

为了防止红色方块永远下落,我们需要在它到达游戏区域底部时停止下落:

Examples

  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;
    }
  }

Try it yourself

加速

在游戏中,当有一个力把方块拉下来时,您应该设计一个方法来迫使组件加速。

当有人点击按钮时触发一个函数,让红色方块飞到空中:

Examples

<script>
function accelerate(n) {
  myGamePiece.gravity = n;
}
</script>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">加速</button>

Try it yourself

A game

Make a game based on what we have learned so far:

Examples

Try it yourself

Please click the boost button to start the game.

How long can you live? Use the boost button to stay in the air.