COCOS2DX 触屏事件

http://blog.csdn.net/zhy_cheng/article/details/8273435转自此大牛

.h文件

    //要实现触屏事件,首先覆盖父类的onEnter函数,在这个函数中设置触屏事件。
    virtual void onEnter();
    virtual void onExit();
    //几类点击事件
    virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
    virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
    virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);
    virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);

.cpp

void Demo2::onEnter()
{
    CCLog("onEnter");
    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(
        this,//在那个类中实现触屏回调函数
        0, //优先级
        true);//触摸时间是否被该目标截获
}

void Demo2::onExit()
{
    CCLog("onExit");
    //移除监听
    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
}

bool Demo2::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
    CCLog("ccTouchBegan");

    CCPoint p=pTouch->getLocation(); //获取触摸点
    float x=p.x;
    float y=p.y;
    char *buf=new char[40];
    memset(buf,0,10);//全部置0
    sprintf(buf,"x=%f,y=%f",x,y);//格式化到buf中
    CCLog(buf);
    delete []buf;        
    return true;//这表示触摸消息是否被处理,若为true则接着往下传,false则不往下传,其他函数则无法捕获
}
void Demo2::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
    CCLog("ccTouchMoved");
    CCPoint p=pTouch->getLocation();
    float x=p.x;
    float y=p.y;
    char *buf=new char[40];
    memset(buf,0,10);
    sprintf(buf,"x=%f,y=%f",x,y);

    CCLog(buf);
    delete []buf;
}
void Demo2::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
    CCLog("ccTouchEnded");
    CCPoint p=pTouch->getLocation();
    float x=p.x;
    float y=p.y;
    char *buf=new char[40];
    memset(buf,0,10);
    sprintf(buf,"x=%f,y=%f",x,y);

    CCLog(buf);
    delete []buf;
}
void Demo2::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent)
{
    CCLog("ccTouchCancelled");
    CCPoint p=pTouch->getLocation();
    float x=p.x;
    float y=p.y;
    char *buf=new char[40];
    memset(buf,0,10);
    sprintf(buf,"x=%f,y=%f",x,y);

    CCLog(buf);
    delete []buf;
}

 但是用此代码后,发现原有的退出按钮不能接受点击事件了,这是怎么回事呢?

 测试一下,发现原来是没有调用父类CCLayer类的onEnter函数,加上此函数过后,按钮可以正常使用。

void Demo2::onEnter()
{
    CCLayer::onEnter();
    CCLog("onEnter");
    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(
        this,//在那个类中实现触屏回调函数
        0, //优先级
        false);//触摸时间是否被该目标截获,截获了就不向子类传递
}

void Demo2::onExit()
{
    CCLayer::onExit();
    CCLog("onExit");
    //移除监听
    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
}

 

posted @ 2014-01-08 13:46  phk52  阅读(130)  评论(0)    收藏  举报