Developers Manual > Cocos2d-x > How To > How To Create A HUD

How To Create A HUD

What is a HUD?

A HUD, or "Heads Up User Display" is a way of displaying data to the user without them having to look away from what the are doing. HUDS are almost certainly used in most every game. Here are some examples of HUDS is game we all know:

m_kfm

m_pitfall

m_excite

m_mario

What information goes in a HUD?

Anything! Score, Health, Messages, Achievements, Power-Ups, Progress indicators, Timers

How do you make a HUD?

Think of a HUD as a type of Layer*, more specifically in Cocos2d-x a type of LayerColor*. API

Lets create a simple HUD that when called tells the user a message.

header:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#ifndef  _MESSAGEHUD_HPP_
#define  _MESSAGEHUD_HPP_

#include "cocos2d.h"

class MessageHUD : public cocos2d::LayerColor
{
    public:
        MessageHUD();
        ~MessageHUD();

        static MessageHUD* createLayer(const std::string& _message);
        void initOptions(const std::string& _message);

        virtual void draw (cocos2d::Renderer * renderer, const cocos2d::Mat4 & transform, bool transformUpdated);

        inline virtual cocos2d::Label* getMessageLabel() { return _messageLabel; };

    private:
        cocos2d::Label* _messageLabel;
};

#endif // _MESSAGEHUD_HPP_

source:

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
#include "MessageHUD.hpp"

MessageHUD::MessageHUD() {}

MessageHUD::~MessageHUD() {}

MessageHUD* MessageHUD::createLayer(const std::string& _message)
{   
    MessageHUD* a = new MessageHUD();
    a->create();
    a->setColor(cocos2d::Color3B(0, 0, 0));

    a->setContentSize(cocos2d::Size::Size(1, 1));
    a->setAnchorPoint(cocos2d::Vec2(0, 0)); 

    a->initOptions(_message);

    return a;
}

void MessageHUD::initOptions(const std::string& _message)
{
    _messageLabel = cocos2d::Label::createWithBMFont("Marker Felt Small.fnt", _message.c_str());
    _messageLabel->setColor(cocos2d::Color3B(255, 215, 0));

    addChild(_messageLabel, 1);

    _messageLabel->setPosition(cocos2d::Vec2(cocos2d::Director::getInstance()->getVisibleSize().width, cocos2d::Director::getInstance()->getVisibleSize().height));

}

void MessageHUD::draw(cocos2d::Renderer * renderer, const cocos2d::Mat4 & transform,
                         bool transformUpdated) {}

to create:

1
2
MessageHUD* _hud = MessageHUD::createLayer("The Enemy is approaching!");
this->addChild(_hud, 2);

m_kfm.png (172 kB) slackmoehrle, 2014-05-16 21:49

m_excite.jpg (39.3 kB) slackmoehrle, 2014-05-16 21:49

m_mario.png (147.9 kB) slackmoehrle, 2014-05-16 21:49

m_pitfall.png (4.1 kB) slackmoehrle, 2014-05-16 21:49

Sign up for our newsletter to keep up with the latest developments, releases and updates for Cocos2d-x.