ゲーム動作

通过利用游戏旋转章节中讲解的绘制组件的新方式,动作现在更加灵活了。


コース推薦:

ゲームの回転セクションで説明されている新しいコンポーネントの描画方法を使用して、アクションがもっと柔軟になります。 もう一度遊んでみましょう。 以下で、物体の移動方法について説明します。 デフォルトでは、コンポーネントは上を向いています。以下のように component

コンストラクタに以下を追加します。 newPos() 属性も変更します。この属性は、コンポーネントの現在の速度を表します。 デフォルトでは、コンポーネントは上を向いています。以下のように メソッドを変更して、以下に基づいて angle および

計算コンポーネントの位置を設定します。 デフォルトでは、コンポーネントは上を向いています。以下のように speed

インスタンス

function component(width, height, color, x, y) {
  属性を 1 に設定すると、コンポーネントが前方に動き始めます。
  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);
  {}
{}

自分で試してみてください

this.gamearea = gamearea;

「回転」を作成します。 moveAngle の新しい属性に基づいて、現在の移動値または回転角度を示します。以下で左回転と右回転が可能になります。 newPos() メソッドで moveAngle 属性計算 angle:

インスタンス

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

自分で試してみてください

キーボードを使用する

キーボードを使用する際、赤いブロックはどう移動するか?「上」矢印を使用すると、赤いブロックは上か下に移動しません。代わりに、一方からもう一方に移動し、左か右の矢印を押すと左右に回転します。

インスタンス

自分で試してみてください

ゲームエリアに焦点を合わせ、矢印キーを使用して赤いブロックを移動してください。