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

 执行程序:

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


转载于:https://www.cnblogs.com/cocos2dx-wk/p/3226937.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值