Cocos2d-x的CCParallaxNode类可用于实现2d游戏中不同层次地图以不同速率运动的景深效果。具体效果可以查看以下URL:
http://www.56.com/u93/v_OTEzMzE3NjI.html
以下例子中的素材为《IOS5 cocos2d 游戏开发实战》(第2版的),我将objective-c语言描述的例子改成了c++版本的,主要代码如下:
//主角精灵 CCSprite *qqSprite = CCSprite::create("qq.jpg"); qqSprite->setPosition(ccp(size.width/2, size.height/2)); this->addChild(qqSprite, 10); //背景地图精灵 CCSprite *pSprite1 = CCSprite::create("parallax1.png"); CCSprite *pSprite2 = CCSprite::create("parallax2.png"); CCSprite *pSprite3 = CCSprite::create("parallax3.png"); CCSprite *pSprite4 = CCSprite::create("parallax4.png"); //设置背景地图的锚点 pSprite1->setAnchorPoint(ccp(0, 1)); pSprite2->setAnchorPoint(ccp(0, 1)); pSprite3->setAnchorPoint(ccp(0, 0.5f)); pSprite4->setAnchorPoint(ccp(0, 0)); //设置移动速率 CCPoint topoffset = ccp(0, size.height); CCPoint midoffset = ccp(0, size.height / 2); CCPoint downoffset = CCPointZero; //创建CCParallaxNode节点,并将地图加入该节点 CCParallaxNode *parallaxnode = CCParallaxNode::create(); parallaxnode->addChild(pSprite1, 1, ccp(0.8, 0), topoffset); parallaxnode->addChild(pSprite2, 2, ccp(1, 0), topoffset); parallaxnode->addChild(pSprite3, 4, ccp(3, 0), midoffset); parallaxnode->addChild(pSprite4, 3, ccp(4, 0), downoffset); this->addChild(parallaxnode, 0, 100); //分别向左和向右移动的动作 CCMoveBy *move1 = CCMoveBy::create(5, ccp(-200, 0)); CCMoveBy *move2 = CCMoveBy::create(15, ccp(200, 0)); //运作序列 CCFiniteTimeAction *sequence = CCSequence::create(move1, move2, NULL); //CCSequence放入CCRepeatForever时,需要转化数据类型,否则会提示类型不兼容的错误 CCRepeatForever *repeat = CCRepeatForever::actionWithAction(static_cast<CCSequence *>(sequence)); parallaxnode->runAction(sequence);