cocos2dx学习笔记-给精灵类添加事件

本文记录了在cocos2dx中为精灵类添加事件监听的过程,从最初在OnEnter方法中直接初始化事件失败,到后来通过新增初始化方法并正确添加事件回调,最终实现精灵的拖动功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看了看cocos2dx测试项目TouchesTest代码学到的一点东西吧。

在最开始设计自己的精灵类的时候,只是单单继承Sprite,在类里面然后直接添加事件监听的回调方法。

class ObjSth : public cocos2d::Sprite
{
public:
    virtual void onEnter() override;
    virtual void onExit() override;

public:
    //添加事件监听的三个回调成员函数
    bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event);
    void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event);
    void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event);
};

在OnEnter()方法里实现事件的初始化。

void ObjSth::onEnter()
{
    Sprite::onEnter();

    // Register Touch Event
    auto listener = EventListenerTouchOneByOne::create(); 
    listener->setSwallowTouches(true);

    listener->onTouchBegan = CC_CALLBACK_2(ObjSth::onTouchBegan, this);
    listener->onTouchMoved = CC_CALLBACK_2(ObjSth::onTouchMoved, this);
    listener->onTouchEnded = CC_CALLBACK_2(ObjSth::onTouchEnded, this);

    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}

比如在屏幕中添加一个精灵,添加事件实现拖动。

在游戏场景中这么写:

bool Game Scene::init()
{
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    auto Obj = Sprite::create("001.png");
    Obj->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
    this->addChild(Ball, 0);

    return true;
}

自己想当然写的,果然怎么运行也不成功。
设置断点压根不会运行到回调函数那里。

研究了下,做了如下改变。
类部分,添加了两个和初始化有关的方法:

class ObjSth : public cocos2d::Sprite
{
public:
    virtual void onEnter() override;
    virtual void onExit() override;

public:
    //添加如下两个关于初始化成员函数
    static ObjSth* createWithTexture(cocos2d::Texture2D* aTexture);

    //添加事件监听的三个回调成员函数
    bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event);
    void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event);
    void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event);
};

实现如下:

ObjSth* ObjSth::createWithTexture(Texture2D* aTexture)
{
    ObjSth* pObjSth = new (std::nothrow) ObjSth();
    pObjSth->initWithTexture(aTexture);
    pObjSth->autorelease();

    return pObjSth;
}

在游戏场景中这么写:

bool Game Scene::init()
{
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    auto paddleTexture = Director::getInstance()->getTextureCache()->addImage("001.png");

    auto Ball = ObjSth::createWithTexture(paddleTexture);
    Ball->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
    this->addChild(Ball, 0);

    return true;
}

终于运行成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值