KKGLabelOnlyButton.cpp 2.35 KB
//
//  KKGLabelButton.cpp
//  SteveAndMaggieWorld
//
//  Created by Katarzyna Kalinowska-Górska on 11/11/2022.
//

#include "KKGLabelOnlyButton.hpp"
#include "HGeometryUtils.h"

KKGLabelOnlyButton* KKGLabelOnlyButton::create(const std::string& text, cocos2d::Color4B& textColor, const std::string& font, float fontSize, std::function<void(KKGLabelOnlyButton*)> onPress){
    KKGLabelOnlyButton *ret = new (std::nothrow) KKGLabelOnlyButton();
    if (ret->init(text, textColor, font, fontSize, onPress))
    {
        ret->autorelease();
        return ret;
    }
    CC_SAFE_DELETE(ret);
    return nullptr;
}

bool KKGLabelOnlyButton::init(const std::string& text, cocos2d::Color4B& textColor, const std::string& font, float fontSize, std::function<void(KKGLabelOnlyButton*)> onPress){
    if(!cocos2d::Node::init()){
        return false;
    }
    
    m_label = cocos2d::Label::createWithTTF(text, font, fontSize);
            //cocos2d::Label::createWithSystemFont(text, "Arial", fontSize);
    addChild(m_label);
     m_label->setTextColor(textColor);
    setContentSize(m_label->getContentSize());
    m_label->setAnchorPoint(cocos2d::Vec2::ONE/2);
    m_label->setPosition(getContentSize()/2);
    setCascadeOpacityEnabled(true);
    
    auto touchListener = cocos2d::EventListenerTouchOneByOne::create();
    
    touchListener->onTouchBegan = [&](cocos2d::Touch* touch, cocos2d::Event* event){
        auto convertedTouchLocation = _parent->convertToNodeSpace(touch->getLocation());
        if(HGeometryUtils::getBoundingBoxToWorld(this).containsPoint(touch->getLocation())){
            setScale(0.9f);
            return true;
        }
        return false;
    };
    
//    touchListener->onTouchMoved = CC_CALLBACK_2(Menu::onTouchMoved, this);
    touchListener->onTouchEnded = [&, onPress](cocos2d::Touch* touch, cocos2d::Event* event){
        setScale(1.f);
        auto convertedTouchLocation = _parent->convertToNodeSpace(touch->getLocation());
        if(getBoundingBox().containsPoint(convertedTouchLocation)){
//        if(HGeometryUtils::getBoundingBoxToWorld(this).containsPoint(touch->getLocation())){
            onPress(this);
        }
    };
    
    touchListener->onTouchCancelled = [&](cocos2d::Touch* touch, cocos2d::Event* event){
            setScale(1.f);
    };
    
    _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);

    return true;
}