Cocos2d-x中判断点击是否在触摸屏区域


新建2dx工程。

在HelloWorld头文件加入以下语句:

    virtual void registerWithTouchDispatcher();//注册触屏事件 覆写register方法
    
    virtual bool ccTouchBegan(cocos2d::CCTouch* touch, cocos2d::CCEvent* event);//覆写touchBegan方法
    
public:
    CCRect mPlayBounds;//定义一个区域

 如图:

在init()方法中加入以下语句:

setTouchEnabled(true);//开启触摸
    
    //绘制一个矩形
    mPlayBounds = CCRectMake(size.width / 2-200, size.height / 2-200 , 420, 420);
    CCLog("%f,%f",mPlayBounds.origin.x,mPlayBounds.origin.y);
    
    CCSprite *sp = CCSprite::create("blank.png",mPlayBounds);
    sp->setAnchorPoint(ccp(0, 0));
    sp->setPosition(mPlayBounds.origin);
    sp->setColor(ccRED);
    this->addChild(sp);

 sp只是为了方便查看,blank.png为一张空白图片

实现方法:

void HelloWorld::registerWithTouchDispatcher()
{
    //注册触摸监听
    CCDirector* pDirector = CCDirector::sharedDirector();
    pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
}

bool HelloWorld::ccTouchBegan(cocos2d::CCTouch* touch, cocos2d::CCEvent* event)
{
    //取得触摸点
    CCPoint location = touch->getLocationInView();
    //将触摸点转换为GL坐标系的点
    location = CCDirector::sharedDirector()->convertToGL(location);
    
    //如果触摸点在矩形范围内则执行代码
    if (mPlayBounds.containsPoint(location))
    {
        CCMessageBox("成功", "提示");
    }
    return true;
}

 执行程序:

可根据需要调整位置,当点击黑色区域无反应,当点击红色区域出现事件响应:



免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM