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