Chapter 12

Scene遷移で値を渡す

alkn203
alkn203
2021.09.12に更新

scene-value

Scene遷移で値を渡す方法

ゲーム作りでシーン管理は欠かせませんが、シーンをまたいで値を引き渡す方法を説明します。

値の引き渡し方

// タッチで次のシーンへ
onpointstart: function(e) {
  // 次のシーンに渡したいパラメータをオブジェクト配列で指定
  this.exit({
    touchedPos: e.pointer.x,
  });  
},
  • exit関数の引数にオブジェクト配列で引き渡します。
  • オブジェクト配列に追加することで、パラメータは好きなだけ渡すことができます。
  • 今回の例ではタッチされた位置のx座標を渡しています。

## 値の受け取り方

/*
 * シーン02
 */
phina.define("Scene02", {
  // 継承
  superClass: 'DisplayScene',
  // 初期化
  init: function(param) {
    // 親クラス初期化
    this.superInit(param);
    // 背景色
    this.backgroundColor = 'blue';
    // ラベル
    Label({
      text: 'Scene02',
      fontSize: 48,
      fill: 'white',
    }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center());

    Label({
      // 前のシーンから引き渡されたパラメータから取得
      text: 'x:' + param.touchedPos,
      fontSize: 24,
      fill: 'white',
    }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center(2));
  },
  // タッチで次のシーンへ
  onpointstart: function() {
    this.exit();  
  },
});
  • Sceneのコンストラクタの引数paramから値を引き受けることができます。
  • 今回の例では値をラベルに表示しています。

サンプルコード

コードを見る
// グローバルに展開
phina.globalize();
/*
 * シーン01
 */
phina.define("Scene01", {
  // 継承
  superClass: 'DisplayScene',
  // 初期化
  init: function() {
    // 親クラス初期化
    this.superInit();
    // 背景色
    this.backgroundColor = 'black';
    // ラベル
    Label({
      text: 'Scene01',
      fontSize: 48,
      fill: 'yellow',
    }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center());
  },
  // タッチで次のシーンへ
  onpointstart: function(e) {
    // 次のシーンに渡したいパラメータをオブジェクト配列で指定
    this.exit({
      touchedPos: e.pointer.x,
    });  
  },
});
/*
 * シーン02
 */
phina.define("Scene02", {
  // 継承
  superClass: 'DisplayScene',
  // 初期化
  init: function(param) {
    // 親クラス初期化
    this.superInit(param);
    // 背景色
    this.backgroundColor = 'blue';
    // ラベル
    Label({
      text: 'Scene02',
      fontSize: 48,
      fill: 'white',
    }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center());

    Label({
      // 前のシーンから引き渡されたパラメータから取得
      text: 'x:' + param.touchedPos,
      fontSize: 24,
      fill: 'white',
    }).addChildTo(this).setPosition(this.gridX.center(), this.gridY.center(2));
  },
  // タッチで次のシーンへ
  onpointstart: function() {
    this.exit();  
  },
});
/*
 * メイン処理
 */
phina.main(function() {
  // アプリケーションを生成
  var app = GameApp({
    // Scene01 から開始
    startLabel: 'scene01',
    // シーンのリストを引数で渡す
    scenes: [
      {
        className: 'Scene01',
        label: 'scene01',
        nextLabel: 'scene02',
      },
      {
        className: 'Scene02',
        label: 'scene02',
        nextLabel: 'scene01',
      },
    ]
  });
  // 実行
  app.run();
});

runstantプロジェクト

https://runstant.com/alkn203/projects/04de5832