LoginSignup
5

More than 5 years have passed since last update.

posted at

updated at

phina.jsでアクセサリを使ってみよう&作ってみよう!

この記事は、phina.js Advent Calendar 2016 12月8日の記事です。
昨日→phina.jsでアイコンフォントを使ってみよう by pentamaniaさん
明日→phina.jsのゲーム制作にあたって工夫したところと、JavaScript入門者が陥ったつまづきポイントについて。 by rrf_hhさん

アクセサリって?

phina.jsにおけるアクセサリとは、SpriteShapedisplayElement等にアタッチして機能を付加する事が出来るクラスです。
phina標準のアクセサリには、TweenerDraggable等があります。
これらを利用すると、そのクラスに応じた機能を簡単に利用する事ができ、また再利用が可能となります。

使い方

Draggableアクセサリを例にとって使い方を説明します。

以下のサンプルでは、★をドラッグして移動する事が出来ます。
http://runstant.com/minimo/projects/AccessorySample1

実際に動かしているのは以下のコードの部分です。

var shape = phina.display.StarShape();
//~中略~

//Shapeをドラッグで動かす
shape.setInteractive(true);
shape.on('pointmove', function(e) {
  this.x += e.pointer.dx;
  this.y += e.pointer.dy;
});

Shapeinteractiveフラグをtrueにして、pointmoveイベントでポインタの移動量を捉え、Shapeの移動を行っています。

アクセサリを使用して、同じ機能を実現したのが以下のサンプルです。
http://runstant.com/minimo/projects/AccessorySample2

ShapeにDraggerアクセサリをアタッチしています。
実際に使っているのはこの部分です。

var shape = phina.display.StarShape();
//~中略~

var drg = phina.accessory.Draggable();
drg.attachTo(shape);

DraggableからShapeAttachToして、Shapeに機能を付加しています。

複数のShapeにDraggableをアタッチしたい場合は、それぞれ新規に定義して、AttachToを行います。

色んなオブジェクトへDraggableをアタッチするサンプル
http://runstant.com/minimo/projects/AccessorySample3
Shape、Spriteどちらも同様にアタッチして機能を付加する事が出来ます。

1つのアクセサリを、複数のオブジェクトにアタッチするのは、問題無く動作する場合もあるのですが、解除時に問題が出る場合があるので止めておいた方が無難です。
それぞれ、新規にアクセサリを定義してアタッチを行ってください。

作ってみよう

この様に便利なアクセサリですが、自分で欲しい機能を作成する事も出来ます。
Draggableの応用で、タップしたらエフェクトが発生するアクセサリを作ってみましょう。

TapEffect
phina.define('phina.accessory.TapEffect', {
  superClass: 'phina.accessory.Accessory',
  init: function() {
    this.superInit();

    var self = this;
    this.on('attached', function() {
      this.target.setInteractive(true);
      this.target.on('pointend', function(e) {
        //10個星を出す
        for (var i = 0; i < 10; i++) {
          var s = phina.display.StarShape()
            .addChildTo(this)
            .setScale(0.5);
          var x = s.x+Math.randint(-50, 50);
          var y = s.y+Math.randint(-50, 50);
          s.tweener.clear()
            .to({x: x, y: y, alpha: 0}, 500,"easeOutSine")
            .call(function() {
              this.remove();
            }.bind(s));
        }
      });
    });
  },
});

targetがタップされたらエフェクトとして、10個星を出してランダムな方向にTweenerで移動させています。

コードの説明

this.on('attached', function() {
  this.target.setInteractive(true);
  this.target.on('pointend', function(e) {
    //10個星を出す
    for (var i = 0; i < 10; i++) {
        //~中略~
    }
});

やっている事は単純です。
アクセサリがオブジェクトにアタッチされるとattachedというイベントがアクセサリを対象に発火しますので、イベント内で設定されたtargetpointendイベント内で星を出す処理を追加しています。
再利用を考えるなら、detachedイベント内でオブジェクトからアクセサリを除去する処理を入れた方が良いでしょう。

おしまい

この様に、アクセサリを利用する事によって、オブジェクトの種類に関わらず、簡単に機能を追加する事が出来ます。
是非活用してみてください。

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
What you can do with signing up
5