触摸事件是游戏中必不可少的一部分,但是有时候我们不想使整个精灵都可以接受触摸响应的,所以我们要设精灵的一部分响应。
同样先给个效果图

这样当我们点击两个精灵重叠的部分时就不好判断由那个精灵接收触摸事件因此我们要设置精灵的一部分接受触摸事件
同样我们先初始化两个精灵
- bool HelloWorld::init()
- {
-
-
- if ( !CCLayer::init() )
- {
- return false;
- }
-
-
-
-
-
-
- CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
- "CloseNormal.png",
- "CloseSelected.png",
- this,
- menu_selector(HelloWorld::menuCloseCallback) );
- pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) );
-
-
- CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
- pMenu->setPosition( CCPointZero );
- this->addChild(pMenu, 1);
-
-
-
-
-
-
- CCLabelTTF* pLabel = CCLabelTTF::create("设置精灵的触摸范围", "Thonburi", 34);
- plabel1 = CCLabelTTF::create("你触摸了精灵重叠区域","Thonburi",34);
-
- size = CCDirector::sharedDirector()->getWinSize();
-
-
- pLabel->setPosition( ccp(size.width / 2, size.height - 20) );
-
-
- this->addChild(pLabel, 1);
-
-
- pSprite = CCSprite::create("Icon-72.png");
- pSprite1 = CCSprite::create("Icon-72.png");
-
-
- pSprite->setPosition(ccp(size.width/2, size.height/2) );
- pSprite1->setPosition(ccp(size.width/2-50, size.height/2-50) );
- plabel1->setPosition(ccp(size.width/2, size.height/2-120));
- plabel1->setVisible(false);
-
- this->addChild(pSprite, 0);
- this->addChild(pSprite1,1);
- this->addChild(plabel1);
- this->setTouchEnabled(true);
- return true;
- }
接下来我们给精灵的一小部分设置为可触摸
- void HelloWorld::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent){
- CCTouch *touch = (CCTouch *)pTouches->anyObject();
- CCPoint beginLoc = touch->locationInView();
- beginLoc = CCDirector::sharedDirector()->convertToGL(beginLoc);
-
- CCRect rect = pSprite1->boundingBox();
- int x = rect.origin.x;
- int y = rect.origin.y;
- int w = rect.size.width;
- int h = rect.size.height;
-
- rect = CCRect(210, 130, 20, 20);
- CCLog("%d==%d==%d==%d",x,y,w,h);
- if(CCRect::CCRectContainsPoint(rect, beginLoc)){
- plabel1->setVisible(true);
- }
- }
这样就可以设置我们想要的触摸区域了 不会再为精灵重叠由那个精灵响应触摸事件而烦恼了。 |