Movimento di gioco

Corso raccomandato:


Gioca di nuovo

come muovere un oggetto? nel costruttore component Per impostazione predefinita, il componente è rivolto verso l'alto, impostando Aggiungi un

l'attributo, che rappresenta la velocità attuale del componente. newPos() anche per Per impostazione predefinita, il componente è rivolto verso l'alto, impostando metodi per fare alcune modifiche, in base a angle e

calcolare la posizione del componente. Per impostazione predefinita, il componente è rivolto verso l'alto, impostando speed

Esempio

function component(width, height, color, x, y) {
  l'attributo impostato a 1, il componente inizia a muoversi avanti.
  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);
  }
}

Prova tu stesso

this.gamearea = gamearea;

girare moveAngle con il nuovo attributo, che indica il valore di movimento attuale o l'angolo di rotazione. Inoltre, ci aspettiamo di poter girare a sinistra e a destra. Creiamo un oggetto chiamato newPos() nel metodo moveAngle calcolo degli attributi angle:

Esempio

Imposta l'attributo moveangle a 1 e vediamo cosa accade:

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

Prova tu stesso

Usare la tastiera

Come muove il quadrato rosso usando la tastiera? Quando si preme la freccia verso l'alto, il quadrato rosso non si muove verso l'alto e verso il basso, ma si sposta da un lato all'altro e si ruota a destra e a sinistra quando si premono le frecce a destra e a sinistra.

Esempio

Prova tu stesso

Assicurati che l'area di gioco riceva il focus, quindi usa i tasti freccia per muovere il quadrato rosso.