Automatically disappearing message prompt box in cocos2dx

Toast is a very good prompt provided by the Android system. It can be used in the program to notify the user of some short information, which will automatically disappear after a period of time and will not occupy any screen space.

Toast.makeText(this,"Hello!",Toast.LENGTH_SHORT).show();

In game development with cocos2dx, sometimes we occasionally use this function of automatically disappearing to the message prompt, so how do we achieve it?

In fact, the idea is very simple. Cocos2dx provides several types of timers. For the effect we want to achieve here, we can consider using scheduleOnce, set the time interval, and hide or destroy the Tips prompt box when it is executed once. want the effect.

The specific implementation is as follows:

#ifndef __TIPS_H__
#define __TIPS_H__

#include <string>
#include "cocos2d.h"

USING_NS_CC;

//提示显示位置枚举
enum emShowPos
{
    EM_TIPS_TOP = 0,
    EM_TIPS_CENTER,
    EM_TIPS_BOTTOM,
};


/**
 * @breif 提示框(带自动消失)
 */
class Tips : public Node
{
public:
    /**
     * @breif Tips调用接口
     * @[param] sContent    消息内容
     * @[param] tipsPos     消息显示位置
     * @[param] fShowTime   消息显示持续时间
     */
    static void Show(const std::string &sContent, emShowPos tipsPos = EM_TIPS_TOP, float fShowTime = 2.0f)
    {
        cocos2d::Size visibleSize = Director::getInstance()->getVisibleSize();

        //提示框背景
        ui::Scale9Sprite *pBg = ui::Scale9Sprite::create("bg.png", Rect(0, 0, visibleSize.width, 60));
        pBg->setPosition(Vec2(visibleSize.width / 2, visibleSize.height/2));

        //创建消息文本标签控件
        LabelTTF *pTextLabel = LabelTTF::create(sContent.c_str(), "arial", 32, pBg->getContentSize());
        pTextLabel->setAnchorPoint(Vec2(0.5,1));
        pTextLabel->setPosition(Vec2(pBg->getContentSize().width/2, pBg->getContentSize().height));
        pTextLabel->setColor(Color3B(255,0,0));
        pBg->addChild(pTextLabel);

        Tips *pTipsNode = new Tips();
        pTipsNode->addChild(pBg);
        pTipsNode->scheduleOnce(schedule_selector(Tips::onScheduleOnce), fShowTime);

        Scene *pScene = Director::getInstance()->getRunningScene();
        pScene->addChild(pTipsNode);
    }

private:
    void onScheduleOnce(float fDelay)
    {
        this->removeFromParent();
    }
};

In the above code, we use the Show method to pass the message content, message display position and message duration to control the display of Tips. This is just to achieve the basic effect. In actual use, it can be extended to separate requirements, such as passing TipImage to prompt the picture parameters, so as to realize the message prompt box with pictures and so on.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324600680&siteId=291194637