所谓的位置问题

来源:互联网 发布:听音识谱软件手机 编辑:程序博客网 时间:2024/05/19 21:03

http://bit6211.iteye.com/blog/1684512

cocos2d-x学习耗时点备忘之二——嵌套Sprite的boundingBox位置校正备忘

    博客分类: 
  • cocos2d-x
 

     在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
原创粉丝点击