Gravedad de juego

En algunos juegos, existe una fuerza que arrastra los componentes del juego en una dirección, por ejemplo, la gravedad arrastra los objetos hacia el suelo.


gravedad

Si deseas agregar esta característica a la función constructora de nuestro componente, primero agrega una gravedad Atributo, que establece la gravedad actual. Luego, agrega una gravedadVelocidad Atributos, que aumentan cada vez que actualizamos el cuadro del frame:

Ejemplo

function componente(ancho, alto, color, x, y, tipo) {
  this.tipo = type;
  this.ancho = width;
  this.alto = height;
  this.x = x;
  this.y = y;
  this.velocidadX = 0;
  this.velocidadY = 0;
  this.gravedad = 0.05;
  this.gravedadVelocidad = 0;
  this.actualizar = function() {
    ctx = myGameArea.context;
    ctx.fillStyle = color;
    ctx.fillRect(this.x, this.y, this.ancho, this.alto);
  }
  this.nuevaPosicion = function() {
    this.gravedadVelocidad += this.gravedad;
    this.x += this.velocidadX;
    this.y += this.velocidadY + this.gravedadVelocidad;
  }
}

Intente hacerlo usted mismo

Toque de suelo

Para evitar que el cuadrado rojo caiga para siempre, necesitamos detener su caída cuando alcance el fondo del área de juego:

Ejemplo

  this.nuevaPosicion = function() {
    this.gravedadVelocidad += this.gravedad;
    this.x += this.velocidadX;
    this.y += this.velocidadY + this.gravedadVelocidad;
    this.chocarSuelo();
  }
  this.chocarSuelo = function() {
    var suelo = myGameArea.canvas.height - this.height;
    if (this.y > suelo) {
      this.y = suelo;
    }
  }

Intente hacerlo usted mismo

Acelerar

En el juego, cuando hay una fuerza que arrastra el cuadrado hacia abajo, debes diseñar un método para forzar que el componente se acelere.

Cuando alguien haga clic en el botón, se activa una función que hace que el cuadrado rojo vuele al aire:

Ejemplo

<script>
function acelerar(n) {
  myGamePiece.gravedad = n;
}
</script>
<button onmousedown="acelerar(-0.2)" onmouseup="acelerar(0.1)">Acelerar</button>

Intente hacerlo usted mismo

Un juego

Haga un juego basado en lo que hemos aprendido hasta ahora:

Ejemplo

Intente hacerlo usted mismo

Haga clic en el botón de aceleración para comenzar el juego.

¿Cuánto tiempo puedo vivir? Use el botón de aceleración para mantenerse en el aire.