在cocos2d-x中,常通过Sprite的boundingBox()方法来获取该Sprite的边框,这个边框最常用的用途就是做为碰撞框了。但是如果你在一个Sprite(比如A)中通过addChild加入一个子Sprite(比如B),则B通过boundingBox()获取到的边框,比如boundingBox_B相对于父Layer来说,位置是不准的,这会导致明明按中了B,却得不到该有的响应。
一个校正的代码如下,首先是加入子Sprite的方法:
StartPanel::StartPanel() {
initWithFile("startpage.png");
CCDirector *pDirector = CCDirector::sharedDirector();
CCSize winSize = pDirector->getWinSize();
float screenWidth = winSize.width;
float screenHeight = winSize.height;
CCSize backgroundSize = this->getContentSize();
backgroundWidth = backgroundSize.width;
backgroundHeight = backgroundSize.height;
scaleX = screenWidth / backgroundWidth;
scaleY = screenHeight / backgroundHeight;
this->setScaleX(scaleX);
this->setScaleY(scaleY);
this->setPosition(ccp(screenWidth * 0.5f, screenHeight * 0.5f));
play = CCSprite::spriteWithFile("play.png");
float scaleDuration = 1.0f;
CCScaleBy* bigScale = CCScaleBy::actionWithDuration(scaleDuration, 2.0f);
CCScaleBy* smallScale = CCScaleBy::actionWithDuration(scaleDuration, 0.5f);
CCSequence* scaleSequence = CCSequence::actionOneTwo(bigScale, smallScale);
CCRepeatForever* scaleForever = CCRepeatForever::actionWithAction(scaleSequence);
play->runAction(scaleForever);
play->setPosition(ccp(backgroundWidth * 0.5f, backgroundHeight * 0.3f));
this->addChild(play);
}
其中StartPanel本身是一个Sprite,然后加入了Play这个子Sprite,同时StartPanel和Play都进行了自身的缩放(Play是一个实时的缩放动画)。则Play的boundingBox()的校正代码如下:
CCRect StartPanel::getPlayBoundingBox() {
if(play != NULL) {
CCRect oldBoundingBox = play->boundingBox();
float offsetX = this->getPosition().x - backgroundWidth * 0.5f * scaleX;
float offsetY = this->getPosition().y - backgroundHeight * 0.5f * scaleY;
CCRect newBoundingBox = CCRectMake(oldBoundingBox.origin.x * scaleX + offsetX, oldBoundingBox.origin.y * scaleY + offsetY, oldBoundingBox.size.width * scaleX, oldBoundingBox.size.height * scaleY);
return newBoundingBox;
} else {
return CCRectZero;
}
}
效果图如下:
完毕,特此记录。