AniLongPressGestureRecognizer.cpp 2.01 KB
//
//  AniLongPressGestureRecognizer.cpp
//  SteveMaggieCpp
//
//  Created by Katarzyna Kalinowska-Górska on 19.05.2017.
//
//

#include <stdio.h>
#include "AniLongPressGestureRecognizer.h"
#include "AniMathUtils.h"

AniLongPressGestureRecognizer::AniLongPressGestureRecognizer(float waitTime) : AniGestureRecognizer({cocos2d::EventListener::Type::TOUCH_ONE_BY_ONE})
{
    _waitTime = waitTime;
    _callbackScheduled = false;

    _onLongPressDetected = [](cocos2d::Point){
        cocos2d::log("on long press detected");
    };
}

AniLongPressGestureRecognizer::~AniLongPressGestureRecognizer()
{
};

void AniLongPressGestureRecognizer::setOnLongPressDetectedCallback(std::function<void(cocos2d::Point touchLocation)> callback)
{
    _onLongPressDetected = callback;
}

///////////////////////////////////////////////////////////////////////////
// internal
///////////////////////////////////////////////////////////////////////////
    
// touch handlers

bool AniLongPressGestureRecognizer::onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event)
{
    _startTime = cocos2d::utils::getTimeInMilliseconds();
    _startLocation = touch->getLocation();
    
    _callback = [&](float){
        _onLongPressDetected(_startLocation);
    };
    
    _view->scheduleOnce(_callback, _waitTime, "lpgr_callback");
    _callbackScheduled = true;
    
    return true;
}

void AniLongPressGestureRecognizer::onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event)
{
     if(_callbackScheduled){
        auto delta = _startLocation.distance(touch->getLocation());
        if(delta > MAX_DELTA){
//                log("cancelling callback due to delta = "+delta);
            _view->unschedule("lpgr_callback");
            _callbackScheduled = false;
        }
    }
}

void AniLongPressGestureRecognizer::onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event)
{
    if(_callbackScheduled){
//            log("cancelling callback due to touch ended too soon");
        _view->unschedule("lpgr_callback");
        _callbackScheduled = false;
    }
}