您的位置:首页 > 移动开发 > Cocos引擎

【cocos2d-x官方文档】从v1.x到2.x的API更改

2013-10-26 15:20 423 查看
从v1.x到2.x的API变化

1. 新的API概念

1.1 静态构造函数

1.2 单例

1.3 事件回调

2. 数据结构:CCDictionary和CCArray

2.1 为什么CCMutableDictionary被移除了?

2.2 CCDictionary的主键类型

2.3 如何使用CCDictionary?

2.4 为什么CCMutableArray被移除了?

3. 用Classname::isStatus的方式来返回bool值

4. 类

Director类

CCActionManager,CCTouchDispatcher,CCScheduler类

Sprite类

SpriteBatchNode类

CCGeometry,CCPoint,CCSize,CCRect类

CCTouch类

Transitions类

Particle System类

Menu类

Animate类

MotionStreak类

Layer类

Animation类

ProgressTimer类

CCNode类

RenderTexture类

CCFileUtils类

CCString类

1.新的API概念

根据 Cocos2d Javascript API,我们将大多数API的更改适用到了C++。下面罗列了这些更改的基本概念。

1.1 静态构造函数

[v2.0] 用Classname::create替代Classname::ClassnameWithResource。请参考About Static Constructor API changes in cocos2d-x v2.0。Lua API集合和Javascript
API集合也使用了这种清晰的结构。

[v2.0] 使用createWithResource来避免冲突

[v2.0] 从::create()方法返回的CCObject*对象总是自动释放(auto-release)的。

1.2 单例

[v2.0.1] 所有单例都包含一个静态构造方法Singleton::getInstance(),和一个析构方法Singleton::destroyInstance(),替换了原来的@Classname::sharedClassname。这个变化同样适用于lua和javascript绑定。

1.3 事件回调

[v2.0.1] 事件回调, 例如:CCTouchDelegate::ccTouchesBegan/Moved/Ended/Cancelled(), 被重命名为CCSomethingDelegate::onSomethingDone(),包括:

Standard touch delegate: onTouchesBegan/Moved/Ended/Cancelled

Targeted touch delegate: onTouchBegan/Moved/Ended/Cancelled

Keypad delegate: onKeyBackClicked, onKeyMenuClicked

G-Sensor delegate: onAccelerometerChanged

2.数据结构:CCDictionary和CCArray

2.1 为什么CCMutableDictionary被取消了?

在gles20分支里, ‘CCMutableDictionary’ and ‘CCMutableArray’被取消了。你需要用 CCDictionary and CCArray来替换它们。

CCDictionary是用UTHash来实现的。 CCMutableDictionary是用stl实现的, 相比较而言 CCDictionary的效率会至少提高两倍。并且, CCDictionary没有使用cpp的模版,因此可以方便地绑定到脚本。

2.2 CCDictionary中主键支持的类型

目前, CCDictionary的主键支持两种类型: ‘std::stirng’和’int’。一个 CCDictionary实例只支持一种主键类型。

在你第一次调用 ‘setObject’的时候,主键类型会被确认下来。

2.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宏,在这种情况下,你只能使用旧的方法。

2.4 为什么CCMutableArray被取消了?

在cocos2d-x 1.0.1中,我们有 CCArray和 CCMutableArray,让用户十分困惑,同时, CCMutableArray使用了模版和stl,坏处和 CCMutableDictionary一样。旧的CCArray不支持反向遍历数组,现在我们提供了 CCARRAY_FOREACH_REVERSE宏来实现此功能。

3.使用Classname::isStatus方式来返回一个bool类型

对于bool类型:

getter方法从getIsBool()或者getBool()统一为isBool()。

setter方法从setIsBool(value)统一为setBool(value)。

所有使用频繁的方法都被加粗标记了。


function name before function name in v2.x
CCCamera::getDirtyCCCamera::isDirty
CCConfiguration::isSupportsNPOTCCConfiguration::supportsNPOT
CCConfiguration::isSupportsPVRTCCCConfiguration::supportsPVRTC
CCConfiguration::isSupportsBGRA8888CCConfiguration::supportsBGRA8888
CCConfiguration::isSupportsDiscardFramebufferCCConfiguration::supportsDiscardFramebuffer
CCConfiguration::isSupportsShareableVAOCCConfiguration::supportsShareable***O
CCNode::getIsVisibleCCNode::isVisible
CCNode::setIsVisibleCCNode::setVisible
CCNode::getIsRunningCCNode::isRunning
CCGridBase::setIsTextureFlippedCCGridBase::setTextureFlipped
CCRGBAProtocol::getIsOpacityModifyRGBCCRGBAProtocol::isOpacityModifyRGB
CCRGBAProtocol::setIsOpacityModifyRGBCCRGBAProtocol::setOpacityModifyRGB
CCLayer::getIsTouchEnabledCCLayer::isTouchEnabled
CCLayer::setIsTouchEnabledCCLayer::setTouchEnabled
CCMenu::getIsEnabledCCMenu::isEnabled
CCMenu::setIsEnabledCCMenu::setEnabled
CCParticleSystem::getIsActiveCCParticle::isActive
CCParticleSystem::getIsAutoRemovedOnFinishCCParticle::isAutoRemovedOnFinish
CCParticleSystem::setIsAutoRemovedOnFinishCCParticle::setAutoRemovedOnFinish
CCParticleSystem::getIsBlendActiveCCParticleSystem::isBlendActive
CCParticleSystem::setIsBlendActiveCCParticleSystem::setBlendActive
CCTexture2D::getIsHasPremultipliedAlphaCCTexture2D::hasPremultipliedAlpha
CCFileUtils::setIsPopupNotifyCCFileUtils::isPopupNotify
CCFileUtils::setIsPopupNotifyCCFileUtils::setPopupNotify
CCScriptSupport::getIsMultiTouchesCCScriptSupport::isMultiTouches
CCScriptSupport::setIsVisibleCCScriptSupport::setVisible
4.类

Director类

[v2.0-sync] CCDirector::setDisplayFPS(bool) -> setDisplayStats(bool)。现在左下的状态显示3个数字:

最上面的数字显示每帧调用了多少次OpenGL的draw方法。

中间的数字表示每帧耗费多少秒(SPF)。

最下面的数字是我们都很熟悉的FPS。

[v2.0-sync] CCDirector::isRetinaDisplay()被移除了。

[v2.0] *在Resources/下添加fps_images.png,并且添加到工程设置中。现在CCDirector使用CCLabelAtlas来显示FPS,这样做可以提高在android上的运行效率。

CCActionManager, CCTouchDispatcher, CCScheduler类

[v2.0-sync] CCActionManager, CCTouchDispatcher, CCScheduler现在是CCDirector的成员变量。但包含’cache’的单例类,比如CCTextureCache, CCAnimationCache, CCShaderCache还维持原状。

Sprite类

[v2.0-sync] CCSprite::displayedFrame() -> displayFrame()

SpriteBatchNode类

[v2.0-sync] CCSprite::spriteWithBatchNode(…)被移除,请使用: sprite = CCSprite::spriteWithTexture(batchNode->getTexture(), CCRect*); batchNode->addChild(sprite);代替。

[v2.0-sync] CCSprite::initWithBatchNode(…), initWithBatchNodeInPixels(…) 被移除,请使用CCSprite::setBatchNode(…)代替。

[v2.0-sync] bool CCSprite::isUsesBatchNode()被移除,请使用CCSpriteBatchNode* getSpriteBatchNode(),要判断返回值是否为NULL。

使用batch node创建sprite的示例代码:

// create batch node from image file
   CCSpriteBatchNode* batch = CCSpriteBatchNode::create("BatchNodeTexture.png");
// get the texture in batch node
   CCTexture2D* texture = batch->getTexture();
// create sprite from this texture
   CCSprite* sprite = CCSprite::createWithTexture(texture, CCRectMake(0,0,32,32));
// organize the child relation
   layer->addChild(batch);
   batch->addChild(sprite);

CCGeometry, CCPoint, CCSize, CCRect类

使用面向对象的方法替代静态函数

v2.0.2] 使用p1.equals(p2)代替CCPoint::CCPointEqualToPoint(p1, p2)

[v2.0.2] 使用s1.equals(s2)代替CCSize::CCSizeEqualToSize(s1, s2)

[v2.0.2] 使用r.getMinX(), r.getMaxY()系列代替CCRect:CCRectGetMinX(r), CCRect::CCRectGetMaxY(r) 系列

[v2.0.2] 使用r1.equals(r2)代替CCRect::CCRectEqualsToRect(r1, r2)

[v2.0.2] 使用r1.contrainsPoint(p1)代替CCRect::CCRectContainsPoint(r1, p1)

[v2.0.2] 使用r1.intersectsRect(r2)代替CCRect::CCRectIntersectsRect(r1, r2)

CCTouch类

CCTouch中添加了一些方便的API

[v2.0.2] locationInView()重命名为getLocationInView()

[v2.0.2] previousLocationInView()重命名为CCTouch::getPreviousLocationInView()

[v2.0.2] 添加getLocation()方法,直接返回OpenGL坐标

[v2.0.2] 添加getPreviousLocation()方法,直接返回OpenGL坐标

[v2.0.2] 添加getDelta()方法,返回OpenGL坐标系中当前位置和上一位置间的变化量

变换

[v2.0-sync] CCTransitionRadialCW -> CCTransitionProgressRadialCW

[v2.0-sync] CCTransitionRadialCCW -> CCTransitionProgressRadialCCW

粒子系统

[v2.0-sync] ARCH_OPTIMAL_PARTICLE_SYSTEM -> CCParticleSystemQuad,

[v2.0-sync] CCParticleSystemQuad::initIndices() -> setupIndices()

[v2.0] CCParticleSystemPoint被移除,请使用CCParticleSystemQuad代替。

菜单

[v2.0] CCMenuItemImage::initFromNormalImage -> initWithNormalImage

Animate类

[v2.0-sync] CCAnimate::actionWithDuration(ccTime duration, CCAnimation *pAnimation, bool bRestoreOriginalFrame)被移除,用CCAnimation::setDelayPerUnit(float)代替。

MontionStreak类

[v2.0-sync] CCMotionStreak::streakWithFade和initWithFade改变了参数,请参考CCMotionStreak.h来获得更多细节。

Layer类

[v2.0] CCLayerColor::layerWithColorWidthHeight被重命名为layerWithColor

Animation类

[v2.0-sync] CCAnimation::setDelay(float) / getDelay()重命名为setDelayPerUnit(float)/getDelay()

[v2.0] CCAnimation::initWithFrames( CCMuatableArray<>* )重命名为initWithSpriteFrames(CCArray*)

[v2.0-sync] CCAnimation::addFrame(CCSpriteFrame*)重命名为addSpriteFrame(CCSpriteFrame*)

[v2.0-sync] CCAnimation::animationWithFrames重命名为animationWithSpriteFrames

[v2.0-sync] CCAnimation::addFrameWithFileName -> addSpriteFrameWithFileName

[v2.0-sync] CCAnimation::addFrameWithTexture -> addSpriteFrameWithTexture

ProgressTimer类

[v2.0-sync] CCProgressTimer::initWithFile(char*) and initWithTexture(CCTexture2D*) 被移除,用 initWithSprite(CCSprite*) 代替。

[v2.0-sync] CCProgressTimer::progressWithFile and progressWithTexture被移除,使用 progressWithSprite代替。

CCNode类

[v2.0-sync] CCNode::get/setPositionInPixels, get/setAnchorPointInPixels, get/setContentSizeInPixels, boundingBoxInPixels()被移除,替换为不带”InPixel”后缀的方法。

RenderTexture类

[v2.0] CCRenderTexture::saveBuffer(…)更改为saveToFile(…)

CCFileUtils类

[v2.0] CCFileUtils::dictionaryWithContentsOfFile被更改为 CCDictionary::createWithContentsOfFile, 添加CCArray::createWithContentsOfFile方法。

CCString类

1. 更多有用的方法。

/** create a string with std string, you can also pass a c string pointer because the default constuctor of std::string can access a c string pointer.
*  @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* create(const std::string& str);
 
/** 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* createWithFormat(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* createWithData(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* createWithContentsOfFile(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);


本文由 sharyu 翻译,转载请注明原出处!! http://www.ityran.com/archives/3220
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: