AniLongPressGestureRecognizer.cpp
2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//
//  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;
    }
}