AniTouchableSprite.cpp 1.38 KB
//
//  AniTouchableSprite.cpp
//  SteveMaggieCpp
//
//  Created by Katarzyna Kalinowska-Górska on 17.05.2017.
//
//

#include <stdio.h>
#include "cocos2d.h"
#include "AniTouchableSprite.h"
#include "AniGeometryUtils.h"

AniTouchableSprite* AniTouchableSprite::createWithFile(const std::string& filename)
{
    AniTouchableSprite * sprite = new (std::nothrow) AniTouchableSprite();
    if(sprite && sprite->initWithFile(filename))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}

 bool AniTouchableSprite::initWithFile(const std::string& filename)
 {
    if(!cocos2d::Sprite::initWithFile(filename)){
        return false;
    }
    
    this->interactionEnabled = true;
    this->touchBeganCallback = [](AniTouchableSprite* sprite){};
    
    this->configureTouchHandlers();
    
    return true;
 }

 void AniTouchableSprite::configureTouchHandlers()
 {
    auto touchListener = cocos2d::EventListenerTouchOneByOne::create();
    touchListener->onTouchBegan = [&](cocos2d::Touch* touch, cocos2d::Event* event){
       
      if(interactionEnabled && AniGeometryUtils::getBoundingBoxToWorld(this).containsPoint(touch->getLocation())){
      
        this->touchBeganCallback(this);
        return true;
      }
       
       return false;
    };
    
    _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
 }