Herní pohyb

S novým způsobem kreslení komponent, vysvětleným v kapitole Rotace hry, jsou pohyby flexibilnější.


Jak přesouvat objekty?

Přidejte speeddo componentkonstruktoru vlastnost, která představuje aktuální rychlost komponenty.

Proveďte také některé změny v newPos()metodě pro výpočet polohy součásti na základě speeda angle.

Ve výchozím nastavení jsou komponenty otočeny nahoru a nastavením vlastnosti speed na 1 se komponenta začne pohybovat vpřed.

Příklad

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


Zatáčky

Chceme také umět zatáčet doleva a doprava. Vytvořte novou vlastnost s názvem moveAngle, která označuje aktuální hodnotu pohybu nebo úhel otočení. V newPos()metodě vypočítejte na anglezákladě moveAnglevlastnosti:

Příklad

Nastavte vlastnost moveangle na 1 a uvidíte, co se stane:

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

Použijte klávesnici

Jak se pohybuje červený čtverec při používání klávesnice? Namísto pohybu nahoru a dolů a ze strany na stranu se červený čtverec posouvá dopředu, když použijete šipku „nahoru“ a otáčí se doleva a doprava, když stisknete šipku doleva a doprava.

Příklad