Movimiento de juego

Al utilizar el nuevo método de dibujo del componente explicado en el capítulo de rotación del juego, la acción ahora es más flexible.


¿Cómo mover un objeto?

en component Añadir un velocidad propiedad, que representa la velocidad actual del componente.

también hay que cambiar newPos() hacer algunos cambios en el método velocidad y ángulo calcular la posición del componente.

Por defecto, el componente mira hacia arriba, al usar velocidad propiedad 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);
  }
}

Pruebe usted mismo

giro

También esperamos poder girar a la izquierda y a la derecha. Cree un nombre de moveAngle nuevas propiedades, que indican el valor de movimiento actual o el ángulo de rotación. En newPos() método en función de moveAngle cálculo de propiedad ángulo:

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

Pruebe usted mismo

Uso del teclado

¿Cómo se mueve el cuadrado rojo cuando se usa el teclado? Al usar la flecha 'arriba', el cuadrado rojo no se mueve hacia arriba y hacia abajo, sino que se desplaza de un lado a otro hacia adelante y gira a la izquierda y a la derecha al presionar las teclas de flecha.

Ejemplo

Pruebe usted mismo

Asegúrese de que el área de juego tenga el foco y luego use las teclas de flecha para mover el cuadrado rojo.