Gravité du jeu


Certains jeux ont des forces qui tirent le composant du jeu dans une direction, comme la gravité tire les objets vers le sol.




La gravité

Pour ajouter cette fonctionnalité à notre constructeur de composants, ajoutez d'abord une gravitypropriété, qui définit la gravité actuelle. Ajoutez ensuite une gravitySpeedpropriété, qui augmente à chaque fois que nous mettons à jour le cadre :

Exemple

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


Toucher le fond

Pour éviter que le carré rouge ne tombe à jamais, arrêtez la chute lorsqu'il touche le bas de la zone de jeu :

Exemple

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


Accélérer

Dans un jeu, lorsque vous avez une force qui vous tire vers le bas, vous devriez avoir une méthode pour forcer le composant à accélérer.

Déclenchez une fonction lorsque quelqu'un clique sur un bouton et faites voler le carré rouge dans les airs :

Exemple

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

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

Un jeu

Créez un jeu basé sur ce que nous avons appris jusqu'à présent :

Exemple