AniSimpleFastSwipeGestureRecognizer.cpp
2.32 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
//
//  AniFastSwipeGestureRecognizer.cpp
//  SteveMaggieCpp
//
//  Created by Katarzyna Kalinowska-Górska on 19.05.2017.
//
//
#include <stdio.h>
#include "AniSimpleFastSwipeGestureRecognizer.h"
#include "AniMathUtils.h"
/*Detect fast swipe with the finger in one of the four basic directions */
AniSimpleFastSwipeGestureRecognizer::AniSimpleFastSwipeGestureRecognizer() : AniGestureRecognizer({cocos2d::EventListener::Type::TOUCH_ONE_BY_ONE})
{
    _onFastSwipeDetected = [](std::string direction, cocos2d::Point startLocation, cocos2d::Point endLocation, float velocity){
//        cocos2d::log("AniFastSwipeGestureRecognizer: onFastSwipeDetected with direction "+direction);
    };
}
void AniSimpleFastSwipeGestureRecognizer::setOnFastSwipeDetectedCallback(std::function<void(std::string direction, cocos2d::Point startLocation, cocos2d::Point endLocation, float velocity)> callback)
{
    _onFastSwipeDetected = callback;
}
AniSimpleFastSwipeGestureRecognizer::~AniSimpleFastSwipeGestureRecognizer(){
}
///////////////////////////////////////////////////////////////////////////
// internal
///////////////////////////////////////////////////////////////////////////
    
// touch handlers
bool AniSimpleFastSwipeGestureRecognizer::onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event)
{
    _startTime = cocos2d::utils::getTimeInMilliseconds()/1000.0;
    _startLocation = touch->getLocation();
    return true;
}
    
void AniSimpleFastSwipeGestureRecognizer::onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event)
{
    auto currentTime = cocos2d::utils::getTimeInMilliseconds()/1000.0;
    auto timeDiff = (currentTime - _startTime);
    auto newLocation = touch->getLocation();
    
    auto xVel = (newLocation.x - _startLocation.x) / timeDiff;
    auto yVel = (newLocation.y - _startLocation.y) / timeDiff;
    
    auto absXVel = std::abs(xVel);
    auto absYVel = std::abs(yVel);
    
    if(absXVel >= MIN_SWIPE_VELOCITY && absXVel >= absYVel){
        auto direction = AniMathUtils::signum(xVel) < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
        _onFastSwipeDetected(direction, _startLocation, newLocation, absXVel);
        
    } else if(absYVel >= MIN_SWIPE_VELOCITY){
        auto direction = AniMathUtils::signum(yVel) < 0 ? DIRECTION_DOWN : DIRECTION_UP;
        _onFastSwipeDetected(direction, _startLocation, newLocation, absYVel);
    }
}