新建2dx工程。

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

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

 如图:

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

在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为一张空白图片Cocos2d-x中判断点击是否在触摸屏区域

实现方法:

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;
}

 执行程序:

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

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

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

相关文章:

  • 2021-06-05
  • 2022-12-23
  • 2022-02-16
  • 2021-11-05
  • 2022-12-23
  • 2022-12-23
  • 2021-06-03
  • 2021-09-22
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-21
  • 2021-07-08
  • 2022-12-23
相关资源
相似解决方案