2013年9月20日金曜日

cocos2d-xでスクロールするレイヤーCCScrollLayerを使う

どうも、俺@久しぶりの書き込みです。

最近もほぼ毎日iOS/Androidのゲームアプリ開発に精を出しています。

今日はcocos2d-xを使ってスクロール出来るレイヤーの紹介です。
画面をスワイプしてページングする、アレです。
先日リリースしたゲームアプリ「ゴー!ゴー!カート」のコース選択画面で使っています。


GitHubに上がっているyandongliu / CCScrollLayerを使わせて頂きましたが、やりたい事がほぼこれで全て実装できました。
※cocos2d-x v2.0.2での動作保証がされています。それ以上のバージョンのcocos2d-xを使う場合はしっかり動作検証が必要です。

基本的な使い方は、スクロールして表示するコンテンツ(Layer)を配列にaddObject()しておいて、その配列をCCScrollLayerにセットする、という流れです。


ではまずGitHubからCCScrollLayerをcloneします。

git clone https://github.com/yadongliu/CCScrollLayer.git
で、中のCCScrollLayer.hとCCScrollLayer.mをXCodeのプロジェクト内に放り込みます。
これで準備OKです。

それでは表示する各コンテンツ(Layer)を作成しておきます。

// ヘッダ ContentsLayer.h
class ContentsLayer: public cocos2d::CCLayer
{
public:
  ContentsLayer();
  virtual bool init();
};

// 実装 ContentsLayer.m
#include "ContentsLayer.h"

ContentsLayer::ContentsLayer()
{
}
bool ContentsLayer::init()
{
  if (!CCLayer::init()) {
    return false;
  }

  // 適当なSpriteでも載せておく
  CCSprite *sprite = CCSprite::create("hoge.png");
  sprite->setPosition(ccp(200,200));
  this->addChild(sprite);

  return true;
}

次にスクロールさせたいSceneのヘッダファイルでこのファイルを読み込み宣言しておきます。

#include "CCScrolLayer.h"
#include "ContentsLayer.h"
class MyScene: public: cocos2d::CCLayer
{
public:
  MyScene();
  static cocos2d::CCScene *scene();
  // その他の宣言
private:
  // CCScrollLayerをクラス変数としておく(あとあと操作しやすいので、、各自お好みで、、)
  cocos2d::CCScrollLayer *_myScrollLayer;
};

次に実装ファイルに処理を書いていきます。


// コンストラクタやinit()で
bool MyScene::init()
{
  if (!CCLayer::init()) {
    return false;
  }

  // とりあえず4画面スクロールさせる
  CCArray *contentsList = CCArray::create();
  ContentsLayer *contents1 = new ContentsLayer();
  ContentsLayer *contents2 = new ContentsLayer();
  ContentsLayer *contents3 = new ContentsLayer();
  ContentsLayer *contents4 = new ContentsLayer();

  contents1->init();
  contents2->init();
  contents3->init();
  contents4->init();

  contentsList->addObject(contents1);
  contentsList->addObject(contents2);
  contentsList->addObject(contents3);
  contentsList->addObject(contents4);

  // CCScrollLayerへセット
  _myScrollLayer = new CCScrollLayer();

  // 4画面分の配列をセット。
  _myScrollLayer->initWithLayers(contentsList, 0);

  // ページインジケーターのポジション(任意)
  _myScrollLayer->setPageIndicatorPosition(ccp(100, 20));

  // 最初に表示しておくページ番号
  _myScrollLayer->selectPage(0);

  this->addChild(_myScrollLayer);

  // レイヤーは解放しておく
  contents1->release();
  contents2->release();
  contents3->release();
  contents4->release();

  return true;
}

とりあえずこれだけで動きます。 4画面分スクロールできるはずです。 他にも使えそうなメソッドがいくつか用意されていて、
CCArray *getPages() // 表示できる画面を配列で返す
unsigned int getCurrentScreen() // 現在のページ番号を返す

や、CCScrollLayerDelegateという便利なデリゲートもあります。

詳しくはソースを読んでみてください。
すごく短くて読みやすいです。


以上でぇぇぇぇぇす。