TouchInterceptingLayer.cpp 2.57 KB
//
//  TouchInterceptingLayer.cpp
//  SteveMaggieCpp
//
//  Created by Katarzyna Kalinowska-Górska on 12.05.2017.
//
//

#include "TouchInterceptingLayer.h"

// create

TouchInterceptingLayer * TouchInterceptingLayer::create(const cocos2d::Color4B& color, bool sceneGraphPriority)
{
    TouchInterceptingLayer * layer = new (std::nothrow) TouchInterceptingLayer();
    if(layer && layer->initWithColor(color, sceneGraphPriority))
    {
        layer->autorelease();
        return layer;
    }
    CC_SAFE_DELETE(layer);
    return nullptr;
}

// overrides

bool TouchInterceptingLayer::initWithColor(const cocos2d::Color4B& color, bool sceneGraphPriority)
{
    if(!LayerColor::initWithColor(color))
    {
        return false;
    }
    
    _onTouchCallback = nullptr;
    this->configureTouchListener(sceneGraphPriority);
    
    return true;
}

//void TouchInterceptingLayer::onEnter()
//{
//    cocos2d::LayerColor::onEnter();
//}

void TouchInterceptingLayer::configureTouchListener(bool sceneGraphPriority)
{
    auto touchListener = cocos2d::EventListenerTouchOneByOne::create();
    touchListener->setSwallowTouches(true);
    touchListener->onTouchBegan = [&](cocos2d::Touch* touch, cocos2d::Event* event){
        
        if(_onTouchCallback){
            _onTouchCallback(touch);
        }
        
        return true;
    };

    touchListener->onTouchMoved = [&](cocos2d::Touch* touch, cocos2d::Event* event){
    
        if(_onTouchMovedCallback){
            _onTouchMovedCallback(touch);
        }
    };

    touchListener->onTouchEnded = [&](cocos2d::Touch* touch, cocos2d::Event* event){
    
        if(_onTouchEndedCallback){
            _onTouchEndedCallback(touch);
        }
    };

    if(sceneGraphPriority){
        _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
    } else {
        _eventDispatcher->addEventListenerWithFixedPriority(touchListener, TouchEventListenerPriority);
    }
}

//setters

void TouchInterceptingLayer::setOnTouchCallback(const std::function<void(cocos2d::Touch*)>& onTouchCallback)
{
    this->_onTouchCallback = onTouchCallback;
}

void TouchInterceptingLayer::setOnTouchMovedCallback(const std::function<void(cocos2d::Touch*)>& onTouchCallback)
{
    this->_onTouchMovedCallback = onTouchCallback;
}

void TouchInterceptingLayer::setOnTouchEndedCallback(const std::function<void(cocos2d::Touch*)>& onTouchCallback)
{
    this->_onTouchEndedCallback = onTouchCallback;
}

void TouchInterceptingLayer::clearTouchHandlers()
{
    _onTouchCallback = nullptr;
    _onTouchMovedCallback = nullptr;
    _onTouchEndedCallback = nullptr;
}