Cocos2Dx实现中英文打字机效果

Cocos2Dx实现中英文打字机效果

基于CSDN上的博文修改成了工具类,直接使用u8字符串

// TypewriterLabelUtil.h

#ifndef __TYPEWRITER_LABEL_UTIL_H__
#define __TYPEWRITER_LABEL_UTIL_H__

#include "cocos2d.h"
USING_NS_CC;

class TypewriterLabelUtil {
public:
    // 创建带有打字机效果的 Label 控件
    static Label* createTypewriterLabel(const std::string& text, const std::string& fontName, int fontSize, float typingSpeed);
};

#endif
// TypewriterLabelUtil.cpp

#include "TypewriterLabelUtil.h"

Label* TypewriterLabelUtil::createTypewriterLabel(const std::string& text, const std::string& fontName, int fontSize, float typingSpeed) {
    auto label = Label::createWithSystemFont("", fontName, fontSize);

    Vector<FiniteTimeAction*> actions;
    int i = 0;
    while (i <= text.length()) {
        auto delay = DelayTime::create(typingSpeed);
        actions.pushBack(delay);

        // 判断当前字符是否为中文字符
        if (text[i] > -127 && text[i] < 0) i += 3; 
        else i += 1;

        std::string str = text.substr(0, i);
        auto func = [label, str]() { label->setString(str); };
        auto call = CallFunc::create(func);
        actions.pushBack(call);
    }

    label->runAction(Sequence::create(actions));

    return label;
}
//使用例
string s1 = u8"你好,Cocos!我是日本人。";
auto label = TypewriterLabelUtil::createTypewriterLabel(s1, "微软雅黑", 24, 0.1f);
this->addChild(label);

其实我有一些问题,比如为什么

auto func = [label, str]() { label->setString(str); };
auto call = CallFunc::create(func);

写成label->setString(str);就不行?
感觉c++的实际应用还是太少,以后慢慢摸索吧。