ToyTouchableSprite.cpp
1.38 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
//
//  ToyTouchableSprite.cpp
//  SteveMaggieCpp
//
//  Created by Katarzyna Kalinowska-Górska on 17.05.2017.
//
//
#include <stdio.h>
#include "cocos2d.h"
#include "ToyTouchableSprite.h"
#include "ToyGeometryUtils.h"
ToyTouchableSprite* ToyTouchableSprite::createWithFile(const std::string& filename)
{
    ToyTouchableSprite * sprite = new (std::nothrow) ToyTouchableSprite();
    if(sprite && sprite->initWithFile(filename))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}
 bool ToyTouchableSprite::initWithFile(const std::string& filename)
 {
    if(!cocos2d::Sprite::initWithFile(filename)){
        return false;
    }
    
    this->interactionEnabled = true;
    this->touchBeganCallback = [](ToyTouchableSprite* sprite){};
    
    this->configureTouchHandlers();
    
    return true;
 }
 void ToyTouchableSprite::configureTouchHandlers()
 {
    auto touchListener = cocos2d::EventListenerTouchOneByOne::create();
    touchListener->onTouchBegan = [&](cocos2d::Touch* touch, cocos2d::Event* event){
       
      if(interactionEnabled && ToyGeometryUtils::getBoundingBoxToWorld(this).containsPoint(touch->getLocation())){
      
        this->touchBeganCallback(this);
        return true;
      }
       
       return false;
    };
    
    _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
 }