滚动视图
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
class HelloWorld : public cocos2d::CCLayer
{
public:
// Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer)
virtual bool init();
// there's no 'id' in cpp, so we recommend to return the class instance pointer
static cocos2d::CCScene* scene();
// a selector callback
void menuCloseCallback(CCObject* pSender);
// preprocessor macro for "static create()" constructor ( node() deprecated )
CREATE_FUNC(HelloWorld);
void GameLogic(float dt);
};
#endif // __HELLOWORLD_SCENE_H__
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
using namespace cocos2d;
using namespace CocosDenshion;
CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
/
//添加背景图片
CCSprite *backGround1 = CCSprite::create("123.png");
CCSprite *backGround2 = CCSprite::create("123.png");
//设置位置
backGround1->setPosition(ccp(0,0));
backGround2->setPosition(ccp(0,850));
//设置锚点
backGround1->setAnchorPoint(ccp(0,0));
backGround2->setAnchorPoint(ccp(0,0));
//添加到Layer当中
addChild(backGround1,1,888);
addChild(backGround2,1,999);
//每0.01秒执行一
次Gamelogic函数
schedule(schedule_selector(HelloWorld::GameLogic),0.01);
return true;
}
void HelloWorld::GameLogic(float dt)
{
CCSprite *bg1 = CCSprite::create();
bg1 = (CCSprite *)this->getChildByTag(888);//获取tag为888的精灵(背景1)
CCSprite *bg2 = CCSprite::create();
bg2 = (CCSprite *)this->getChildByTag(999);//
获取tag为000的精灵(背景2)
bg1->setPositionY(bg1->getPositionY()-5);//背景1向下移动
bg2->setPositionY(bg1->getPositionY()+850);//背景2跟随背景1向下移动
if(bg2->getPositionY() == 0)
{
bg1->setPositionY(0);
}
}
void HelloWorld::menuCloseCallback(CCObject* pSender)
{
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
这里面有两句代码要说明一下
bg1->setPositionY(bg1->getPositionY()-5);//背景1向下移动
bg2->setPositionY(bg1->getPositionY()+850);//背景2跟随背景1向下移动
第一句中背景移动的距离应该为背景图片的因数,否则会出现背景移动移动着就出现黑屏的bug,例如在本Demo中背景图片的高度为850,那么5,10,85等数可以整除850 不会出现bug
第二句代码中背景2随着背景1移动,背景2总是在背景1的上面,所以设置背景2的位置为背景1的位置加上背景1的高度,实现背景2 的跟随效果