触摸事件是游戏中必不可少的一部分,但是有时候我们不想使整个精灵都可以接受触摸响应的,所以我们要设精灵的一部分响应。
同样先给个效果图
这样当我们点击两个精灵重叠的部分时就不好判断由那个精灵接收触摸事件因此我们要设置精灵的一部分接受触摸事件
同样我们先初始化两个精灵
- bool HelloWorld::init()
- {
- //////////////////////////////
- // 1. super init first
- if ( !CCLayer::init() )
- {
- return false;
- }
- /////////////////////////////
- // 2. add a menu item with "X" image, which is clicked to quit the program
- // you may modify it.
- // add a "close" icon to exit the progress. it's an autorelease object
- CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
- "CloseNormal.png",
- "CloseSelected.png",
- this,
- menu_selector(HelloWorld::menuCloseCallback) );
- pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) );
- // create menu, it's an autorelease object
- CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
- pMenu->setPosition( CCPointZero );
- this->addChild(pMenu, 1);
- /////////////////////////////
- // 3. add your codes below...
- // add a label shows "Hello World"
- // create and initialize a label
- CCLabelTTF* pLabel = CCLabelTTF::create("设置精灵的触摸范围", "Thonburi", 34);
- plabel1 = CCLabelTTF::create("你触摸了精灵重叠区域","Thonburi",34);
- // ask director the window size
- size = CCDirector::sharedDirector()->getWinSize();
- // position the label on the center of the screen
- pLabel->setPosition( ccp(size.width / 2, size.height - 20) );
- // add the label as a child to this layer
- this->addChild(pLabel, 1);
- // add "HelloWorld" splash screen"
- pSprite = CCSprite::create("Icon-72.png");
- pSprite1 = CCSprite::create("Icon-72.png");
- // position the sprite on the center of the screen
- 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);
- // add the sprite as a child to this layer
- 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; //得到矩形框的左下角x坐标
- int y = rect.origin.y; //得到矩形框的左下角x坐标
- int w = rect.size.width; //得到矩形框的宽
- int h = rect.size.height; //得到矩形框的高
- rect = CCRect(210, 130, 20, 20); //重新设置精灵的矩形框x坐标为210,Y坐标为130,宽w为20,高h为20
- CCLog("%d==%d==%d==%d",x,y,w,h);
- if(CCRect::CCRectContainsPoint(rect, beginLoc)){
- plabel1->setVisible(true);
- }
- }
这样就可以设置我们想要的触摸区域了 不会再为精灵重叠由那个精灵响应触摸事件而烦恼了。