Movimiento del juego

Con la nueva forma de dibujar componentes, explicada en el capítulo Rotación del juego, los movimientos son más flexibles.


¿Cómo mover objetos?

Agregue una speedpropiedad al componentconstructor, que representa la velocidad actual del componente.

También haga algunos cambios en el newPos()método, para calcular la posición del componente, basado en speedy angle.

De manera predeterminada, los componentes miran hacia arriba y al establecer la propiedad de velocidad en 1, el componente comenzará a moverse hacia adelante.

Ejemplo

function component(width, height, color, x, y) {
  this.gamearea = gamearea;
  this.width = width;
  this.height = height;
  this.angle = 0;
  this.speed = 1;
  this.x = x;
  this.y = y;
  this.update = function() {
    ctx = myGameArea.context;
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.rotate(this.angle);
    ctx.fillStyle = color;
    ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
    ctx.restore();
  }
  this.newPos = function() {
    this.x += this.speed * Math.sin(this.angle);
    this.y -= this.speed * Math.cos(this.angle);
  }
}


Hacer giros

También queremos poder girar a la izquierda y a la derecha. Cree una nueva propiedad llamada moveAngle, que indique el valor de movimiento actual o el ángulo de rotación. En el newPos()método calcular el anglebasado en la moveAnglepropiedad:

Ejemplo

Establezca la propiedad moveangle en 1 y vea qué sucede:

function component(width, height, color, x, y) {
  this.width = width;
  this.height = height;
  this.angle = 0;
  this.moveAngle = 1;
  this.speed = 1;
  this.x = x;
  this.y = y;
  this.update = function() {
    ctx = myGameArea.context;
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.rotate(this.angle);
    ctx.fillStyle = color;
    ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
    ctx.restore();
  }
  this.newPos = function() {
    this.angle += this.moveAngle * Math.PI / 180;
    this.x += this.speed * Math.sin(this.angle);
    this.y -= this.speed * Math.cos(this.angle);
  }
}

Usa el teclado

¿Cómo se mueve el cuadrado rojo cuando se usa el teclado? En lugar de moverse hacia arriba y hacia abajo, y de lado a lado, el cuadrado rojo se mueve hacia adelante cuando usa la flecha "arriba" y gira hacia la izquierda y hacia la derecha cuando presiona las flechas izquierda y derecha.

Ejemplo