在游戏中,人物行走,其实是背景向相反方向移动,给玩家形成了一个人物向前移动的错觉。
详细步骤如下,懒得码字了,代码中注释得很清楚:
1 做一个人物无限原地踏步的动画,代码如下所示:
//创建人物精灵 CCSprite *mainsprite = CCSprite::create("s_1.png"); //动画部分,创建动画动作 CCAnimation * animation = CCAnimation::create(); //给动画动作添加帧 animation->addSpriteFrameWithFileName("s_1.png"); animation->addSpriteFrameWithFileName("s_2.png"); animation->addSpriteFrameWithFileName("s_3.png"); animation->addSpriteFrameWithFileName("s_4.png"); animation->addSpriteFrameWithFileName("s_5.png"); animation->addSpriteFrameWithFileName("s_6.png"); animation->setDelayPerUnit(0.05f); //设置动画帧时间 animation->setRestoreOriginalFrame(true); //动画执行后还原初始状态 //运行奔跑动画 //将主角精灵放在屏幕放下角 mainsprite->setPosition(ccp(mainsprite->getContentSize().width/2 , mainsprite->getContentSize().height)); //CCActionInterval *run = CCMoveBy::create(10, ccp((size.width - mainsprite->getContentSize().width/2), (size.height - mainsprite->getContentSize().height/2))); mainsprite->runAction(CCRepeatForever::create(CCAnimate::create(animation))); this->addChild(mainsprite, 4);
2. 添加背景图片到场景中,背景图片精灵为awakenjoys的保护数据成员,代码如下:
#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" class Awakenjoys : public cocos2d::CCLayer { public: // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone virtual bool init(); // there's no 'id' in cpp, so we recommand to return the exactly class pointer static cocos2d::CCScene* scene(); // a selector callback void menuCloseCallback(CCObject* pSender); // implement the "static node()" method manually CREATE_FUNC(Awakenjoys); void update(float dt); protected: cocos2d::CCSprite *bgSprite; cocos2d::CCSprite *bgSprite1; }; #endif // __HELLOWORLD_SCENE_H__
3. 调用scheduleUpdate定时器(每帧都会执行一次)进行滚动背景处理:
//创建背景图1精灵 bgSprite = CCSprite::create("bgroup.jpg"); bgSprite->setPosition(ccp(0, 0)); //屏幕左下角 this->addChild(bgSprite, -1); //添加到场景中 //创建背景图2精灵 bgSprite1 = CCSprite::create("bgroup1.jpg"); bgSprite1->setPosition(ccp(0, 0)); //屏幕左下角 this->addChild(bgSprite1, -2); //添加到场景中 bgSprite->setAnchorPoint(ccp(0, 0)); //设置锚点位置为屏幕左下角 bgSprite1->setAnchorPoint(ccp(1, 0)); //设置锚点位置为屏幕右下角 //调用scheduleUpdate进行滚动地图处理 scheduleUpdate();
4. scheduleUpdate()定时器内容:
void Awakenjoys::update(float dt) { CCPoint bgSprite_p = bgSprite->getPosition(); CCPoint bgSprite1_p = bgSprite->getPosition(); bgSprite->setPosition(ccp(bgSprite_p.x -4, bgSprite_p.y)); bgSprite1->setPosition(ccp(bgSprite1_p.x -4, bgSprite1_p.y)); if (bgSprite_p.x < 0) { float temp = bgSprite_p.x + CCDirector::sharedDirector()->getWinSize().height; bgSprite->setPosition(ccp(temp, bgSprite_p.y)); } if (bgSprite1_p.x < 0) { float temp = bgSprite1_p.x + CCDirector::sharedDirector()->getWinSize().height; bgSprite1->setPosition(ccp(temp, bgSprite1_p.y)); }