juego de gravedad
Algunos juegos tienen fuerzas que tiran del componente del juego en una dirección, como la gravedad tira los objetos al suelo.
Gravedad
Para agregar esta funcionalidad a nuestro constructor de componentes, primero agregue una gravity
propiedad, que establece la gravedad actual. Luego agregue una gravitySpeed
propiedad, que aumenta cada vez que actualizamos el marco:
Ejemplo
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;
}
}
golpea el fondo
Para evitar que el cuadrado rojo caiga para siempre, detén la caída cuando toque el fondo del área de juego:
Ejemplo
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;
}
}
Acelerar
En un juego, cuando tienes una fuerza que tira hacia abajo, debes tener un método para forzar al componente a acelerar.
Active una función cuando alguien haga clic en un botón y haga que el cuadrado rojo vuele por el aire:
Ejemplo
<script>function accelerate(n) {
myGamePiece.gravity = n;
}</script>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">ACCELERATE</button>
Un juego
Haz un juego basado en lo que hemos aprendido hasta ahora: