Movimento di gioco

Con il nuovo modo di disegnare i componenti, spiegato nel capitolo Rotazione del gioco, i movimenti sono più flessibili.


Come spostare gli oggetti?

Aggiungi una speedproprietà al componentcostruttore, che rappresenta la velocità corrente del componente.

Apportare anche alcune modifiche al newPos()metodo, per calcolare la posizione del componente, in base a speede angle.

Per impostazione predefinita, i componenti sono rivolti verso l'alto e, impostando la proprietà della velocità su 1, il componente inizierà ad andare avanti.

Esempio

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


Fare turni

Vogliamo anche essere in grado di fare svolte a destra ea sinistra. Crea una nuova proprietà chiamata moveAngle, che indica il valore di spostamento corrente o l'angolo di rotazione. Nel newPos()metodo calcola anglein base alla moveAngleproprietà:

Esempio

Imposta la proprietà moveangle su 1 e guarda cosa succede:

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 la tastiera

Come si muove il quadrato rosso quando si utilizza la tastiera? Invece di spostarsi su e giù e da un lato all'altro, il quadrato rosso si sposta in avanti quando si utilizza la freccia "su" e gira a sinistra ea destra quando si premono le frecce sinistra e destra.

Esempio