【cocos2dx 3.2】Flappy Bird开发超详细讲解(四)让地图滚动起来吧

来源:互联网 发布:安卓ehviewer网络错误 编辑:程序博客网 时间:2024/05/29 04:54

本文可随意转载,转载请声明一下出处就好了。

鉴于上一期代码量太大,这一期就简单点吧。这一期我们来实现让草地无限滚动的动画。我们新建一个类,命名为LandLayer。其实草地滚动的原理就是让两块草地一直改变它的X轴的坐标。无限滚动就是加个判断,当草地1滚出屏幕的时候让它接在草地2后边。

先预览一下效果吧:

好吧,由于不是gif格式的动态图片,大家也看不到效果,大家自行调试看效果吧。

我么来看看代码:

//LandLayer.h

#ifndef _LANDLAYER_H_#define _LANDLAYER_H_#include "cocos2d.h"USING_NS_CC;class LandLayer:public Layer{public:static Scene* createScene();virtual bool init();CREATE_FUNC(LandLayer);void landMove(float);private://两块草地Sprite* land1;Sprite* land2;};#endif


//LandLayer.cpp

#include "LandLayer.h"#include "define.h"Scene* LandLayer::createScene(){auto scene = Scene::create();auto layer = LandLayer::create();scene->addChild(layer);return scene;}bool LandLayer::init(){if (!Layer::init()){return false;}auto winSize = Director::getInstance()->getWinSize();//添加草地一的图片和背景位置,setAliasTexParameters是为了防止两块草地滚动起来的时候出现黑边land1 = Sprite::createWithSpriteFrameName("land.png");land1->setAnchorPoint(Point::ZERO);land1->setPosition(Point::ZERO);land1->getTexture()->setAliasTexParameters();this->addChild(land1);//添加草地二的图片和背景位置,草地二的位置是在草地一的右边,这边减2是防止两块草地之间出现空隙land2 = Sprite::createWithSpriteFrameName("land.png");land2->setAnchorPoint(Point::ZERO);land2->setPosition(Point(land1->getPositionX()+land1->getContentSize().width-2,land1->getPositionY()));land2->getTexture()->setAliasTexParameters();this->addChild(land2);//添加定时器,调用草地滚动的函数,让草地滚动起来吧!this->schedule(schedule_selector(LandLayer::landMove));return true;}//草地滚动函数void LandLayer::landMove(float){//通过不断改变草地x轴的位置来实现草地滚动land1->setPositionX(land1->getPositionX() - LAND_OFFSET);land2->setPositionX(land2->getPositionX() - LAND_OFFSET);//判断条件,当草地一滚出屏幕的时候让草地一接在草地二后面,草地二同理if (land1->getPositionX()==-land1->getContentSize().width){land1->setPositionX(land2->getPositionX()+land2->getContentSize().width-2);}else if (land2->getPositionX()==-land2->getContentSize().width){land2->setPositionX(land1->getPositionX() + land1->getContentSize().width - 2);}}


然后我们在开始界面调用草地层,很简单,就两句话。

//添加滚动的草地auto land = LandLayer::create();this->addChild(land);

记得导入草地层的头文件哦,下次就不提醒了哦。
本期源码地址链接: http://pan.baidu.com/s/1sjuMqJj 密码: oyf3

0 0
原创粉丝点击