ゲームの動き

ゲームの回転の章で説明されているコンポーネントの新しい描画方法により、動きがより柔軟になります。


オブジェクトを移動する方法は?

コンポーネントの現在の速度を表すspeedプロパティをコンストラクターに追加します。component

また、メソッドにいくつかの変更を加えて、newPos()に基づいてコンポーネントの位置を計算します。speedangle

デフォルトでは、コンポーネントは上を向いており、speedプロパティを1に設定すると、コンポーネントは前進を開始します。

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


ターンする

また、左右に曲がることができるようにしたいと考えています。moveAngle現在の移動値または回転角を示す、という新しいプロパティを作成します。メソッドでは、プロパティに基づいて計算newPos()し ます。anglemoveAngle

moveangleプロパティを1に設定し、何が起こるかを確認します。

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

キーボードを使用する

キーボードを使用すると、赤い四角はどのように動きますか?赤い四角は、上下左右に移動するのではなく、「上」矢印を使用すると前方に移動し、左右の矢印を押すと左右に回転します。