LoginSignup
6
3

More than 5 years have passed since last update.

phina.jsでブラウザ風タッチスクロール

Last updated at Posted at 2017-12-06

やりたいこと

・クリックやタップに反応させて、レイヤー全体をスクロールさせる
・今回はy方向のみ
・ブラウザのスクロールのように指が離れた後も緩やかにスクロール

サンプルコード

準備

・レイヤーを準備
・スクロール領域用にRectangleShapeを追加
・スクロール領域に連動して動かしたい要素をレイヤーに追加

// MainScene クラスを定義
phina.define('MainScene', {
  superClass: 'DisplayScene',
  init: function() {

    var self = this;

    this.superInit();

    // レイヤー
    this.uiLayer = DisplayElement().addChildTo(self);

    // スクロールできる領域
    var uiBase = RectangleShape({
      width: 500,
      height: 3000,
      x: self.gridX.center(),
      y: self.gridY.center(),
    }).addChildTo(this.uiLayer);

    uiBase.setInteractive(true);

    // 領域上に要素を置く
    var tomapiko = Sprite('tomapiko').addChildTo(uiBase);
  },
});

スクロール処理 

・pointstartでスクロール開始を検知
・pointmoveで動いた量を拾ってレイヤーを移動させる
・pointend時に加速量を保持しておく
・updateを用いて減速しながら移動させる

// MainScene クラスを定義
phina.define('MainScene', {
  superClass: 'DisplayScene',
  init: function() {

    var self = this;

    this.superInit();

    // レイヤー
    this.uiLayer = DisplayElement().addChildTo(self);

    // スクロールできる領域
    var uiBase = RectangleShape({
      width: 500,
      height: 3000,
      x: self.gridX.center(),
      y: self.gridY.center(),
    }).addChildTo(this.uiLayer);

    uiBase.setInteractive(true);

    // 領域上に要素を置く
    var tomapiko = Sprite('tomapiko').addChildTo(uiBase);

    // スクロール用処理
    uiBase.on('pointstart', function(pointed){
      this.pointing = true;
    });
    uiBase.on('pointmove', function(pointed){
      self.uiLayer.y += pointed.pointer.dy;
    });
    uiBase.on('pointend', function(pointed){
      this.pointing = false;
      this.vy = pointed.pointer.fy;
    });
    uiBase.update = function() {
      if(this.pointing === false){
        this.vy = this.vy * 0.8;
        if(Math.round(this.vy * 0.8) === 0){
          this.vy = 0;
        }
        self.uiLayer.y += this.vy;
      }
    }

  },
});

fpsと減速量について

ぬるぬる動かしたければfpsを60にするとよいと思います。
30だと若干カクカクした感じになります

減速量に0.8という数値を用いていますが、もう少し大きい数値を使ったほうがスムーズに動く感じを出せます。
お好みで。

課題

本当は、ポップアップダイアログ内でスクロールみたいのを作りたかったのですが、表示領域を限定する方法が分からず、実現できていません。
⇒解決しました。コメント欄参照

終わりに

phinajsは、動きのあるゲームに強いのは言うまでもありませんが、
結構何でもできちゃうので、2Dであれば作れないゲームはほとんどないのではないでしょうか。

UI部分を独自に実装していけば、今風のソーシャルゲームとかも作れるんじゃないかな。

★よろしければtwitterでも絡んでください
twitter

6
3
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3