本章由 sharyu (泰然教程组)翻译,转载请注明出处并通知泰然。
Cocos2d-x v2.0迁移指南
这个指南会在每个cocos2d-x v2.0版本发布时更新。
概况
- 包含一些API变化
- 包含一些新的特性
- 支持OpenGL ES 2.0,不再支持OpenGL ES 1.1
- 支持iOS,Android和win32
与cocos2d-iphone v20同步更新
Cocos2d-X v20是从cocos2d-iphone v20同步过来的,因此它包含了cocos2d-iphone v20的更新。
因此你可以根据 migrate_to_v2.0来查看这些更新
下面是经常使用到的类和接口的列表
- CCTransitionRadialCW重命名为CCTransitionProgressRadialCW
- CCTransitionRadialCCW重命名为CCTransitionProgressRadialCCW
- ARCH_OPTIMAL_PARTICLE_SYSTEM更改为CCParticleSystemQuad
- CCParticleSystemPoint在gles20分支上被移除
- CCMenuItemImage::initFromNormalImage重命名为initWithNormalImage
- CCDirector::setDisplayFPS(bool)重命名为setDisplayStats(bool)
- CCAnimate::initWithDuration(ccTime duration, CCAnimation *pAnimation, bool bRestoreOriginalFrame)被移除,用CCAnimation::setDelayPerUnit(float)来代替
- CCAnimate::actionWithDuration(ccTime duration, CCAnimation *pAnimation, bool bRestoreOriginalFrame) method被移除,用CCAnimation::setDelayPerUnit(float)来代替
- CCMotionStreak::streakWithFade和initWithFade更改了参数,请参考CCMotionStreak.h
- CCLayerColor::layerWithColorWidthHeight重命名为layerWithColor
- CCAnimation::setDelay(float) / getDelay()重命名为setDelayPerUnit(float)/getDelay()
- CCAnimation::initWithFrames( CCMuatableArray<>* )重命名为initWithSpriteFrames(CCArray*)
- CCAnimation::addFrame(CCSpriteFrame*)重命名为addSpriteFrame(CCSpriteFrame*)
- CCAnimation::animationWithFrames重命名为animationWithSpriteFrames
- CCAnimation::addFrameWithFileName -> addSpriteFrameWithFileName
- CCAnimation::addFrameWithTexture -> addSpriteFrameWithTexture
- CCProgressTimer::initWithFile(char*) and initWithTexture(CCTexture2D*)被移除,用initWithSprite(CCSprite*)代替
- CCProgressTimer::progressWithFile and progressWithTexture被移除,用progressWithSprite代替
- CCNode::get/setPositionInPixels, get/setAnchorPointInPixels, get/setContentSizeInPixels, boundingBoxInPixels()被移除,用去掉"InPixel"后缀的方法代替
- CCParticleSystemQuad::initIndices()重命名为setupIndices()
- CCDirector::isRetinaDisplay()被移除
- CCRednerTexture::saveBuffer(…)更改为saveToFile(...)
- bool CCSprite::isUsesBatchNode()被移除,用CCSpriteBatchNode* getSpriteBatchNode()代替,需要判断返回值是否为NULL
- 重要! CCSprite::spriteWithBatchNode(…)被移除,请使用:sprite = CCSprite::spriteWithTexture(batchNode->getTexture(), CCRect*); batchNode->addChild(sprite);代替
- CCSprite::initWithBatchNode(...), initWithBatchNodeInPixels(…)被移除,用CCSprite::setBatchNode(…)代替
- CCSprite::displayedFrame()重命名为displayFrame()
Cocos2d-x特有的更新
下面是Cocos2d-x特有的更新。
CCDictionary和CCArray
1. 为什么CCMutableDictionary被移除了?
在gles20分支里, ‘CCMutableDictionary’ and ‘CCMutableArray’被取消了。你需要用 CCDictionary and CCArray来替换它们。
CCDictionary是用UTHash来实现的。 CCMutableDictionary是用stl实现的, 相比较而言 CCDictionary的效率会至少提高两倍。并且, CCDictionary没有使用cpp的模版(template),因此可以方便地绑定到脚本。
2. 主键类型?
目前, CCDictionary的主键支持两种类型: ‘std::stirng’和’int’。一个 CCDictionary实例只支持一种主键类型。
在你第一次调用 ‘setObject’的时候,主键类型会被确认下来。
3. 如何使用CCDictionary?
CCDictionary和 CCMutableDictionary的用法基本相同。我们保留了相同的API,移除了遍历字典时用到的’begin’,’end’和’next’方法。取而代之,我们使用了 CCDICT_FOREACH宏。使用 CCDICT_FOREACH的方法和 CCARRAY_FOREACH的用法极为相似。
下面的代码阐述了如何遍历 CCDictionary:
- CCMutableDictionary
- CCDictionary std::vector keys = theDict->allKeys();
- CCDictElement* pElement = NULL;
- std::vector::iterator it;
- CCDICT_FOREACH(theDict, pElement)
- for (it = keys.begin(); it != keys.end(); it++)
- {
- {
- CCObjectSubClass* pSubClassObj = (CCObjectSubClass*)pElement->getObject();
- std::string oneKey = *it;
- // You can also get the current key, but make sure you know the key type.
- CCObjectSubClass* pSubClassObj = theDict->objectForKey(oneKey);
- std::string oneStrKey = pElement->getStrKey(); // if the key type is string.
- // do some operation by using pSubClass pointer.
- // int oneIntKey = pElement->getIntKey(); // if the key type is integer.
- // do some operation by using pSubClass pointer.
- }
- }
我们保留了 CCDictionary::allKeys方法,这样就可以按照与 CCMutableDictionary同样的方法遍历字典,但是我们强烈不建议这么做。因为 CCDICT_FOREACH的性能比获取所有主键然后使用CCARRAY_FOREACH来遍历高的多。
如果你希望在lua中遍历 CCDictionary,当然,你无法使用 CCDICT_FOREACH宏,在这种情况下,你只能使用旧的方法。
4. 为什么CCMutableArray被移除了?
在cocos2d-x 1.0.1中,我们有 CCArray和 CCMutableArray,让用户十分困惑,同时, CCMutableArray使用了模版和stl,坏处和 CCMutableDictionary一样。旧的CCArray不支持反向遍历数组,现在我们提供了CCARRAY_FOREACH_REVERSE宏来实现此功能。
5. 将CCFileUtils::dictionaryWithContentsOfFile移动到CCDictionary::dictionaryWithContentsOfFile,添加了CCArray::arrayWithContentsOfFile方法。
CCControlExtension
Cocos2d-X中的CCControlExtension是由Angus C翻译成C++版本的,用法和obj-c版本的相同。如果你希望更详细的了解,请访问他的主页 http://yannickloriot.com/2011/08/create-a-control-object-with-cocos2d-for-iphone/
触摸事件
我们为CCTouch添加了一个新方法’getID’。
这个id用于多点触摸,它可以为你在屏幕上的手指定义独有的名称。
可以参考测试工程中的MultiTouchTest。
支持CocosBuilder
Cocos2d-X在gles20分支中支持了CocosBuilder。
CCString (在gles20分支中添加了很多有用的方法)
CCString在gles20分支中被改进了
1. 更多有用的方法。
- /* static funcitons */
- /** create a string with c string
- * @return A CCString pointer which is an autorelease object pointer,
- * it means that you needn't do a release operation unless you retain it.
- */
- static CCString* stringWithCString(const char* pStr);
- /** create a string with format, it's similar with the c function 'sprintf', the default buffer size is (1024*100) bytes,
- * if you want to change it, you should modify the kMaxStringLen macro in CCString.cpp file.
- * @return A CCString pointer which is an autorelease object pointer,
- * it means that you needn't do a release operation unless you retain it.
- */
- static CCString* stringWithFormat(const char* format, ...);
- /** create a string with binary data
- * @return A CCString pointer which is an autorelease object pointer,
- * it means that you needn't do a release operation unless you retain it.
- */
- static CCString* stringWithData(unsigned char* pData, unsigned long nLen);
- /** create a string with a file,
- * @return A CCString pointer which is an autorelease object pointer,
- * it means that you needn't do a release operation unless you retain it.
- */
- static CCString* stringWithContentsOfFile(const char* pszFileName);
2. 一些接口的变化
- toInt ---> intValue
- toUint ---> uintValue
- toDouble ---> doubleValue
- toFloat ---> floatValue
- toBool ---> boolValue
- toStdStirng(deprecated)
- getCString(new api for getting c string)
3. 有用的宏
#define CCStringMake(str) CCString::stringWithCString(str)
#define ccs CCStringMake
这些宏可以很容易地 创建一个自动释放的CCString对象,比如,如果我们想创建许多CCString对象,并且将他们添加到CCArray中,下面代码会使你地代码更简洁。
- CCArray *stringArray = CCArray::arrayWithObjects(
- ccs("Hello"),
- ccs("Variable"),
- ccs("Size"),
- ccs("!"),
- NULL);
CCDirector使用CCLabelAtlas来显示fps
如果你将工程由1.1升级到2.0,你需要向Resources/目录添加一个fps_images.png文件,并且添加到项目配置中。
更改一些函数名称,使它们更可读并且更有意义
所有频繁使用的函数都加粗标记了。
function name pre-modify 修改前 | function name after modification 修改后 |
CCCamera::getDirty | CCCamera::isDirty |
CCConfiguration::isSupportsNPOT | CCConfiguration::supportsNPOT |
CCConfiguration::isSupportsPVRTC | CCConfiguration::supportsPVRTC |
CCConfiguration::isSupportsBGRA8888 | CCConfiguration::supportsBGRA8888 |
CCConfiguration::isSupportsDiscardFramebuffer | CCConfiguration::supportsDiscardFramebuffer |
CCConfiguration::isSupportsShareableVAO | CCConfiguration::supportsShareableAVO |
CCNode::getIsVisible | CCNode::isVisible |
CCNode::setIsVisible | CCNode::setVisible |
CCNode::getIsRunning | CCNode::isRunning |
CCGridBase::setIsTextureFlipped | CCGridBase::setTextureFlipped |
CCRGBAProtocol::getIsOpacityModifyRGB | CCRGBAProtocol::isOpacityModifyRGB |
CCRGBAProtocol::setIsOpacityModifyRGB | CCRGBAProtocol::setOpacityModifyRGB |
CCLayer::getIsTouchEnabled | CCLayer::isTouchEnabled |
CCLayer::setIsTouchEnabled | CCLayer::setTouchEnabled |
CCMenu::getIsEnabled | CCMenu::isEnabled |
CCMenu::setIsEnabled | CCMenu::setEnabled |
CCParticleSystem::getIsActive | CCParticle::isActive |
CCParticleSystem::getIsAutoRemovedOnFinish | CCParticle::isAutoRemovedOnFinish |
CCParticleSystem::setIsAutoRemovedOnFinish | CCParticle::setAutoRemovedOnFinish |
CCParticleSystem::getIsBlendActive | CCParticleSystem::isBlendActive |
CCParticleSystem::setIsBlendActive | CCParticleSystem::setBlendActive |
CCTexture2D::getIsHasPremultipliedAlpha | CCTexture2D::hasPremultipliedAlpha |
CCFileUtils::setIsPopupNotify | CCFileUtils::isPopupNotify |
CCFileUtils::setIsPopupNotify | CCFileUtils::setPopupNotify |
CCScriptSupport::getIsMultiTouches | CCScriptSupport::isMultiTouches |
CCScriptSupport::setIsVisible | CCScriptSupport::setVisible |
v2.0.2中的API更改
- onEventCallback形式
◦ CCTouchDelegate::ccTouchesBegan/Moved/Ended/Cancelled重命名为 onTouchesBegan/Moved/Ended/Cancelled
◦ CCTouchDelegate::ccTouchBegan/Moved/Ended/Cancelled重命名为onTouchBegan/Moved/Ended/Cancelled
◦ CCKeypadDelegate::keyBackClicked(), keyMenuClicked()重命名为onKeyBackClicked(), onKeyMenuClicked()
◦ CCAccelerometerDelegate::didAccelerate(…)重命名为onAccelerometerChanged(…)
- CCTouch中添加一些好用的API
◦ locationInView()重命名为getLocationInView()
◦ previousLocationInView()重命名为CCTouch::getPreviousLocationInView()
◦ 添加getLocation()方法,直接返回OpenGL坐标
◦ 添加getPreviousLocation()方法,直接返回OpenGL坐标
◦ 添加getDelta()方法,返回OpenGL坐标系中当前位置和上一位置间的变化量
- CCGeometry, 使用面向对象的函数替代静态方法
◦ 使用p1.equals(p2)代替CCPoint::CCPointEqualToPoint(p1, p2)
◦ 使用s1.equals(s2)代替CCSize::CCSizeEqualToSize(s1, s2)
◦ 使用r.getMinX(), r.getMaxY()系列代替CCRect:CCRectGetMinX(r), CCRect::CCRectGetMaxY(r)系列
◦ 使用r1.equals(r2)代替CCRect::CCRectEqualsToRect(r1, r2)
◦ 使用r1.contrainsPoint(p1)代替CCRect::CCRectContainsPoint(r1, p1)
◦ 使用r1.intersectsRect(r2)代替CCRect::CCRectIntersectsRect(r1, r2)
- CCLabelTTF::create(label, dimension, hAlign, FontName, FontSize)的变量顺序更改为 CCLabelTTF::create(label, FontName, FontSize, dimension, hAlign ); 以和CCLabelTTF::create(label, FontName, FontSize)保持近似。 CCLabelTTF::initWithXxx系列的参数顺序也做的调整。