Developers Manual > Cocos2d-x > How To > How To Subclass Sprite And Add Event Listeners

How To Subclass Sprite And Add Event Listeners

Cocos2d-x 3.0 adds a new EventDispatcher mechanism. Now Sprites can have events attached directly to them. This How To will show you how to subclass Sprite and add event listeners.

in your header file:

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

#include "cocos2d.h"

class MySprite : public cocos2d::Sprite
{
    public:
        MySprite();
        ~MySprite();
        static MySprite* create();

        void initOptions();

        void addEvents();
        void touchEvent(cocos2d::Touch* touch, cocos2d::Vector2 _p);

    private:

};

#endif // _MYSPRITE_HPP_

in your source file:

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "MySprite.hpp"

using namespace cocos2d;

MySprite::MySprite() {}

MySprite::~MySprite() {}

MySprite* MySprite::create()
{
    MySprite* pSprite = new MySprite();

    if (pSprite->initWithSpriteFrameName("MySprite.png"))
    {
        pSprite->autorelease();

        pSprite->initOptions();

        pSprite->addEvents();

        return pSprite;
    }

    CC_SAFE_DELETE(pSprite);
    return NULL;
}

void MySprite::initOptions()
{
    // do things here like setTag(), setPosition(), any custom logic.
}

void MySprite::addEvents()
{
    auto listener = cocos2d::EventListenerTouchOneByOne::create();
    listener->setSwallowTouches(true);

    listener->onTouchBegan = [&](cocos2d::Touch* touch, cocos2d::Event* event)
    {   
        cocos2d::Vector2 p = touch->getLocation();
        cocos2d::Rect rect = this->getBoundingBox();

        if(rect.containsPoint(p))
        {
            return true; // to indicate that we have consumed it.
        }

        return false; // we did not consume this event, pass thru.
    };

    listener->onTouchEnded = [=](cocos2d::Touch* touch, cocos2d::Event* event)
    {
        MySprite::touchEvent(touch);
    };

    cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(listener, 30);
}

void MySprite::touchEvent(cocos2d::Touch* touch, cocos2d::Vector2 _point)
{
    CCLOG("touched MySprite");
}

Where you need the Sprite:

1
2
3
MySprite* _mySprite = MySprite::create();

addChild(_mySprite, 1); // add the sprite someplace.

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