Cocos2d-xで使用できる便利なプログラム[XTlayer]

#はじめに
[Edwin van Poeijer](http://www.vanpoeijer.com)によって作られた
Cocos2d-xで面倒なタッチジェスチャーを簡易的に実装出来るようにしたプログラム

元々2.x系で作られたのち3.x系初期の移行時に完全に作られなかった
それを改良して使用できるようにしている
バージョンは3.x系(3.4~3.16)で動作確認済み

#機能
以下の機能がすぐに使用可能

- ダブルタップ
- 長押しタップ
- スワイプ

#XTLayer
```cpp:XTLayer.h
/****************************************************************************
 Copyright (c) 2013      Edwin van Poeijer
 
 http://www.vanpoeijer.com
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

#ifndef __XTLayer__
#define __XTLayer__

#include "cocos2d.h"

class XTLayer : public cocos2d::Layer
{
public:
    enum XTTouchDirection { LEFT,RIGHT,UP,DOWN };
    enum XTGesture { TAP,LONGTAP,SWIPE };
    
    XTLayer();
    ~XTLayer();
    
private:
    XTTouchDirection _xtTouchDirection;
    
    // Default settings
    float _xtSwipeThreshold;
    float _xtSwipeTime;
    float _xtTapThreshold;
    float _xtTapTime;
    float _xtLongTapTreshold;
    float _xtLongTapTime;
    float _xtDoubleTapTime;
    
    // Touch positions
    cocos2d::Vec2 xtGestureStartPoint;
    cocos2d::Vec2 xtActualPoint;
    cocos2d::Vec2 xtPreviousPoint;
    cocos2d::Vec2 xtGestureEndPoint;
    
    bool  _touchHasMoved;
    long  _xtTouchStart;
    int   _xtNumberOfTaps;
    long  millisecondNow();
    void  tapHandler(float dt);
    
    struct timezone {
        int tz_minuteswest;
        int tz_dsttime;
    };
    
    #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
    int gettimeofday(struct timeval *tv, struct timezone *tz);
    #endif
public:
    // Gesture settings
    float xtSwipeThreshold()             { return _xtSwipeThreshold;   }
    void  xtSwipeThreshold(float value)  { _xtSwipeThreshold -= value; }
    float xtSwipeTime()                  { return _xtSwipeTime;        }
    void  xtSwipeTime(float value)       { _xtSwipeTime = value;       }
    float xtTapTreshold()                { return _xtTapThreshold;     }
    void  xtTapTreshold(float value)     { _xtTapThreshold = value;    }
    float xtTapTime()                    { return _xtTapTime;          }
    void  xtTapTime(float value)         { _xtTapTime = value;         }
    float xtLongTapTreshold()            { return _xtLongTapTreshold;  }
    void  xtLongTapTreshold(float value) { _xtLongTapTreshold = value; }
    float xtLongTapTime()                { return _xtLongTapTime;      }
    void  xtLongTapTime(float value)     { _xtLongTapTime = value;     }
    float xtDoubleTapTime()              { return _xtDoubleTapTime;    }
    void  xtDoubleTapTime(float value)   { _xtDoubleTapTime = value;   }
    
    // Override of touches
    virtual bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* unused_event) override;
    virtual void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* unused_event) override;
    virtual void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* unused_event) override;
    virtual void onTouchCancelled(cocos2d::Touch* touch, cocos2d::Event* unused_event) override;
    
    virtual void onTouchesBegan(const std::vector<cocos2d::Touch*>& _touches, cocos2d::Event* unused_event) override;
    virtual void onTouchesMoved(const std::vector<cocos2d::Touch*>& _touches, cocos2d::Event* unused_event) override;
    virtual void onTouchesEnded(const std::vector<cocos2d::Touch*>& _touches, cocos2d::Event* unused_event) override;
    virtual void onTouchesCancelled(const std::vector<cocos2d::Touch*>& _touches, cocos2d::Event* unused_event) override {}
    
    // Callbacks
    virtual void xtTouchesBegan(const std::vector<cocos2d::Touch*>& _touches, cocos2d::Event* event){}
    virtual void xtTouchesMoved(const std::vector<cocos2d::Touch*>& _touches, cocos2d::Event* event){}
    virtual void xtTouchesEnded(const std::vector<cocos2d::Touch*>& _touches, cocos2d::Event* event){}
    
    // Easy touch callbacks
    virtual void xtTouchesBegan(cocos2d::Point position){}
    virtual void xtTouchesMoved(cocos2d::Point position){}
    virtual void xtTouchesEnded(cocos2d::Point position){}
    
    // Gesture Callbacks
    virtual void xtTapGesture(cocos2d::Point position) {}
    virtual void xtDoubleTapGesture(cocos2d::Point position) {}
    virtual void xtLongTapGesture(cocos2d::Point position) {}
    virtual void xtSwipeGesture(XTTouchDirection direction, float distance, float speed) {}
    
    
    // v3.0 helper
    virtual void xtTouchEnabled(bool enabled);
    virtual void xtTouchMode(cocos2d::Touch::DispatchMode mode);
    
    // v3.0 event
    virtual void onExit() override;
};

#endif /* defined(__XTLayer__) */
```

```cpp:XTLayer.cpp
//
//  TouchController.cpp
//  quadro
//
//  Created by EAA van Poeijer on 12-02-13.
//
//

#include "XTLayer.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include    <windows.h>
#include    <time.h>
#include "dinput.h"

#define EPOCHFILETIME (116444736000000000i64)
#endif

//USING_NS_CC;

XTLayer::XTLayer()
{
    this->_xtSwipeThreshold = 30;
    this->_xtSwipeTime = 500;
    this->_xtTapThreshold =10;
    this->_xtTapTime = 250;
    this->_xtLongTapTreshold = 10;
    this->_xtLongTapTime = 2000;
    this->_xtDoubleTapTime = 250;
    this->_xtNumberOfTaps = 0;
}

XTLayer::~XTLayer()
{
}

long XTLayer::millisecondNow()
{
    struct timeval now;
    gettimeofday(&now, nullptr);
    return (now.tv_sec * 1000 + now.tv_usec / 1000);
}

// Override of touches
bool XTLayer::onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* unused_event)
{
    std::vector<cocos2d::Touch*> touches;
    touches.push_back(touch);
    this->onTouchesBegan(touches, unused_event);
    
    return true;
}

void XTLayer::onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* unused_event)
{
    std::vector<cocos2d::Touch*> touches;
    touches.push_back(touch);
    this->onTouchesMoved(touches, unused_event);
}

void XTLayer::onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* unused_event)
{
    std::vector<cocos2d::Touch*> touches;
    touches.push_back(touch);
    this->onTouchesEnded(touches, unused_event);
}

void XTLayer::onTouchCancelled(cocos2d::Touch* touch, cocos2d::Event* unused_event)
{
    std::vector<cocos2d::Touch*> touches;
    touches.push_back(touch);
    this->onTouchesCancelled(touches, unused_event);
}

void XTLayer::onTouchesBegan(const std::vector<cocos2d::Touch*>& _touches, cocos2d::Event* event)
{
    this->_touchHasMoved = false;
    this->_xtTouchStart  = this->millisecondNow();
    
    auto fingerOne = _touches.at(0);
    cocos2d::Point pointOne = cocos2d::Director::getInstance()->convertToUI(fingerOne->getLocationInView());
    
    cocos2d::Point location = this->convertToNodeSpace(pointOne);
    this->xtGestureStartPoint= location;//touch locationInView:touch->view);
    this->xtPreviousPoint = location;
    
    // Passthrough
    this->xtTouchesBegan(location);
    this->xtTouchesBegan(_touches, event);
    
}

void XTLayer::onTouchesMoved(const std::vector<cocos2d::Touch *>& _touches, cocos2d::Event* event)
{
    this->_touchHasMoved = true;
    
    auto fingerOne = _touches.at(0);
    cocos2d::Point pointOne = cocos2d::Director::getInstance()->convertToUI(fingerOne->getLocationInView());
    
    cocos2d::Point location = this->convertToNodeSpace(pointOne);
    this->xtActualPoint = location;
    
    // log("Position:%f,%f",location.x,location.y);
    // Passthrough
    this->xtTouchesMoved(location);
    this->xtTouchesMoved(_touches, event);
    
}

void XTLayer::onTouchesEnded(const std::vector<cocos2d::Touch *>& _touches, cocos2d::Event* event)
{
    long endTime   = this->millisecondNow();
    long deltaTime = endTime - this->_xtTouchStart;
    // log("Deltatime %ld",deltaTime);
    
    auto fingerOne = _touches.at(0);
    cocos2d::Point pointOne = cocos2d::Director::getInstance()->convertToUI(fingerOne->getLocationInView());
    
    cocos2d::Point location = this->convertToNodeSpace(pointOne);
    this->xtGestureEndPoint= location;//touch locationInView:touch->view);
    
    // Calculate the distance
    float deltaX = this->xtGestureStartPoint.x - this->xtGestureEndPoint.x;
    float deltaY = this->xtGestureStartPoint.y - this->xtGestureEndPoint.y;
    
    cocos2d::Size screenSize = cocos2d::Director::getInstance()->getWinSize();
    
    float horSwipeDistancePercentage = fabs((deltaX / screenSize.width ) * 100);
    float verSwipeDistancePercentage = fabs((deltaY / screenSize.height) * 100);
    
    // Calculate the direction
    // First horizontal or vertical
    if (fabs(deltaX) > fabs(deltaY) && horSwipeDistancePercentage > this->_xtSwipeThreshold && deltaTime < this->_xtSwipeTime) // horizontal
    {
        if (deltaX < 0)
            this->_xtTouchDirection = LEFT;
        if (deltaX > 0)
            this->_xtTouchDirection = RIGHT;
        float speed = fabs(deltaX) / deltaTime;
        this->xtSwipeGesture(this->_xtTouchDirection, fabs(deltaX), speed);
    }
    else if (fabs(deltaX) < fabs(deltaY) && verSwipeDistancePercentage > this->_xtSwipeThreshold && deltaTime <this->_xtSwipeTime)// Vertical
    {
        if (deltaY < 0)
            this->_xtTouchDirection = DOWN;
        if (deltaY > 0)
            this->_xtTouchDirection = UP;
        float speed = fabs(deltaY) / deltaTime;
        this->xtSwipeGesture(this->_xtTouchDirection, fabs(deltaY), speed);
    }
    else if (deltaTime >= this->_xtLongTapTime)// No movement, tap detected
    {
        this->xtLongTapGesture(location);
    }
    else
    {
        if (this->_xtNumberOfTaps == 0)
        {
            this->_xtTouchStart = this->millisecondNow();
            this->schedule(schedule_selector(XTLayer::tapHandler), (this->_xtDoubleTapTime / 1000), 1, 0);
        }
        this->_xtNumberOfTaps++;
    }
    
    this->xtTouchesEnded(location);
    this->xtTouchesEnded(_touches, event);
}

void XTLayer::tapHandler(float dt)
{
    this->unschedule(schedule_selector(XTLayer::tapHandler));
    
    if (this->_xtNumberOfTaps == 1 && !this->_touchHasMoved) // singletap
    {
        this->_xtNumberOfTaps = 0;
        this->xtTapGesture(this->xtGestureEndPoint);
    }
    else if (this->_xtNumberOfTaps == 2) // double tap
    {
        this->_xtNumberOfTaps = 0;
        this->xtDoubleTapGesture(this->xtGestureEndPoint);
    }
    else
    {
        this->_xtNumberOfTaps = 0;
    }
}

/*
 *  for v3.0
 */

/*!
 *  @brief  xtTouchEnabled
 *  - see Layer::setTouchEnabled
 */
void XTLayer::xtTouchEnabled(bool enabled)
{
    if (_touchEnabled != enabled)
    {
        _touchEnabled = enabled;
        if (enabled)
        {
            if (_touchListener != nullptr)
                return;
            
            if (_touchMode == cocos2d::Touch::DispatchMode::ALL_AT_ONCE)
            {
                // Register Touch Event
                auto listener = cocos2d::EventListenerTouchAllAtOnce::create();
                
                listener->onTouchesBegan = CC_CALLBACK_2(XTLayer::onTouchesBegan, this);
                listener->onTouchesMoved = CC_CALLBACK_2(XTLayer::onTouchesMoved, this);
                listener->onTouchesEnded = CC_CALLBACK_2(XTLayer::onTouchesEnded, this);
                listener->onTouchesCancelled = CC_CALLBACK_2(XTLayer::onTouchesCancelled, this);
                
                _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
                _touchListener = listener;
            }
            else
            {
                // Register Touch Event
                auto listener = cocos2d::EventListenerTouchOneByOne::create();
                listener->setSwallowTouches(_swallowsTouches);
                
                listener->onTouchBegan = CC_CALLBACK_2(XTLayer::onTouchBegan, this);
                listener->onTouchMoved = CC_CALLBACK_2(XTLayer::onTouchMoved, this);
                listener->onTouchEnded = CC_CALLBACK_2(XTLayer::onTouchEnded, this);
                listener->onTouchCancelled = CC_CALLBACK_2(XTLayer::onTouchCancelled, this);
                
                _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
                _touchListener = listener;
            }
        }
        else
        {
            _eventDispatcher->removeEventListener(_touchListener);
            _touchListener = nullptr;
        }
    }
}

/*!
 *  @brief  xtTouchMode
 *  - see Layer::setTouchMode
 */
void XTLayer::xtTouchMode(cocos2d::Touch::DispatchMode mode)
{
    if(_touchMode != mode)
    {
        _touchMode = mode;
        
        if (_touchEnabled)
        {
            xtTouchEnabled(false);
            xtTouchEnabled(true);
        }
    }
}

/*!
 *  @brief  onExit
 *
 *  remove _touchListener from _eventDispatcher
 */
void XTLayer::onExit()
{
    xtTouchEnabled(false);
    Layer::onExit();
}

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
int XTLayer::gettimeofday(struct timeval *tv, struct timezone *tz)
{
    FILETIME        tagFileTime;
    LARGE_INTEGER   largeInt;
    __int64         val64;
    static int      tzflag;
    
    if (tv)
    {
        GetSystemTimeAsFileTime(&tagFileTime);
        
        largeInt.LowPart = tagFileTime.dwLowDateTime;
        largeInt.HighPart = tagFileTime.dwHighDateTime;
        val64 = largeInt.QuadPart;
        val64 = val64 - EPOCHFILETIME;
        val64 = val64 / 10;
        tv->tv_sec = (long)(val64 / 1000000);
        tv->tv_usec = (long)(val64 % 1000000);
    }
    
    if (tz)
    {
        if (!tzflag)
        {
            _tzset();
            tzflag++;
        }
        
        //Visual C++ 6.0C?CnCjCaC!CΩAEAE
        //tz->tz_minuteswest = _timezone / 60;
        //tz->tz_dsttime = _daylight;
        
        long _Timezone = 0;
        _get_timezone(&_Timezone);
        tz->tz_minuteswest = _Timezone / 60;
        
        int _Daylight = 0;
        _get_daylight(&_Daylight);
        tz->tz_dsttime = _Daylight;
    }
    
    return 0;
}
#endif
```

#使い方
XTLayerを継承しシーンを作る

```cpp:Sample.h
#ifndef __Sample__
#define __Sample__

#include "cocos2d.h"
#include "XTLayer.h"

class Sample : public XTLayer
{
protected:
    
private:
    
    void update(float dt);
    
public:
    ~Sample();
    Sample();
    
    virtual bool init();
    static cocos2d::Scene* scene();
    CREATE_FUNC(Sample);
    
    //virtual void xtTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
    //virtual void xtTouchesMoved(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
    //virtual void xtTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
    
    virtual void xtTouchesBegan(cocos2d::Vec2 position);
    virtual void xtTouchesMoved(cocos2d::Vec2 position);
    virtual void xtTouchesEnded(cocos2d::Vec2 position);
    
    virtual void xtTapGesture(cocos2d::Vec2 position);
    virtual void xtDoubleTapGesture(cocos2d::Vec2 position);
    virtual void xtLongTapGesture(cocos2d::Vec2 position);
    virtual void xtSwipeGesture(XTTouchDirection direction, float distance, float speed);

};

#endif /* defined(__Sample__) */
```

```cpp:Sample.cpp
#include "Sample.h"

USING_NS_CC;

Sample::~Sample(){}
Sample::Sample(){}

bool Sample::init(){
    
    if (!Layer::init()) return false;
    
    auto listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = CC_CALLBACK_2(Sample::onTouchBegan, this);
    listener->onTouchMoved = CC_CALLBACK_2(Sample::onTouchMoved, this);
    listener->onTouchEnded = CC_CALLBACK_2(Sample::onTouchEnded, this);
    listener->setSwallowTouches(true);
    this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
    
    //scheduleUpdate();
    
    return true;
}

void Sample::xtTouchesBegan(Vec2 position){}
void Sample::xtTouchesMoved(Vec2 position){}
void Sample::xtTouchesEnded(Vec2 position){}
void Sample::xtTapGesture(Vec2 position){}
void Sample::xtDoubleTapGesture(Vec2 position){}
void Sample::xtLongTapGesture(Vec2 position){}
void Sample::xtSwipeGesture(XTTouchDirection direction, float distance, float speed){
    std::string directionStr = "";
    switch (direction) {
        case XTLayer::UP: directionStr = "UP"; break;
        case XTLayer::DOWN: directionStr = "DOWN"; break;
        case XTLayer::LEFT: directionStr = "LEFT"; break;
        case XTLayer::RIGHT: directionStr = "RIGHT"; break;
        default:break;
    }
    //log("xtSwipeGesture direction: %s, distance: %f, speed: %f", directionStr.c_str(), distance, speed);
}

void Sample::update(float dt){

}
```