嵌套Sprite的boundingBox位置校正

在cocos2d-x中,常通过Sprite的boundingBox()方法来获取该Sprite的边框,这个边框最常用的用途就是做为碰撞框了。但是如果你在一个Sprite(比如A)中通过addChild加入一个子Sprite(比如B),则B通过boundingBox()获取到的边框,比如boundingBox_B相对于父Layer来说,位置是不准的,这会导致明明按中了B,却得不到该有的响应。

     一个校正的代码如下,首先是加入子Sprite的方法:

Cpp代码   收藏代码
  1. StartPanel::StartPanel() {  
  2.   
  3.     initWithFile("startpage.png");  
  4.   
  5.     CCDirector *pDirector = CCDirector::sharedDirector();  
  6.     CCSize winSize = pDirector->getWinSize();  
  7.     float screenWidth = winSize.width;  
  8.     float screenHeight = winSize.height;  
  9.   
  10.     CCSize backgroundSize = this->getContentSize();  
  11.     backgroundWidth = backgroundSize.width;  
  12.     backgroundHeight = backgroundSize.height;  
  13.     scaleX = screenWidth / backgroundWidth;  
  14.     scaleY = screenHeight / backgroundHeight;  
  15.   
  16.     this->setScaleX(scaleX);  
  17.     this->setScaleY(scaleY);  
  18.   
  19.     this->setPosition(ccp(screenWidth * 0.5f, screenHeight * 0.5f));  
  20.   
  21.     play = CCSprite::spriteWithFile("play.png");  
  22.   
  23.     float scaleDuration = 1.0f;  
  24.     CCScaleBy* bigScale = CCScaleBy::actionWithDuration(scaleDuration, 2.0f);  
  25.     CCScaleBy* smallScale = CCScaleBy::actionWithDuration(scaleDuration, 0.5f);  
  26.     CCSequence* scaleSequence = CCSequence::actionOneTwo(bigScale, smallScale);  
  27.     CCRepeatForever* scaleForever = CCRepeatForever::actionWithAction(scaleSequence);  
  28.     play->runAction(scaleForever);  
  29.   
  30.     play->setPosition(ccp(backgroundWidth * 0.5f, backgroundHeight * 0.3f));  
  31.     this->addChild(play);  
  32. }  

 

其中StartPanel本身是一个Sprite,然后加入了Play这个子Sprite,同时StartPanel和Play都进行了自身的缩放(Play是一个实时的缩放动画)。则Play的boundingBox()的校正代码如下:

Cpp代码   收藏代码
  1. CCRect StartPanel::getPlayBoundingBox() {  
  2.     if(play != NULL) {  
  3.         CCRect oldBoundingBox = play->boundingBox();  
  4.   
  5.         float offsetX = this->getPosition().x - backgroundWidth * 0.5f * scaleX;  
  6.         float offsetY = this->getPosition().y - backgroundHeight * 0.5f * scaleY;  
  7.   
  8.         CCRect newBoundingBox = CCRectMake(oldBoundingBox.origin.x * scaleX + offsetX, oldBoundingBox.origin.y * scaleY + offsetY, oldBoundingBox.size.width * scaleX, oldBoundingBox.size.height * scaleY);  
  9.         return newBoundingBox;  
  10.     } else {  
  11.         return CCRectZero;  
  12.     }  
  13. }  

 效果图如下:

效果图


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值