cocos2d-x中滚动视图的实现

来源:互联网 发布:parsley.min.js 编辑:程序博客网 时间:2024/05/21 06:43
原文地址:cocos2d-x中滚动视图的实现作者:伤心的小果冻
滚动视图


#ifndef__HELLOWORLD_SCENE_H__
#define__HELLOWORLD_SCENE_H__

#include"cocos2d.h"

classHelloWorld : public cocos2d::CCLayer
{
public:
    // Method 'init' incocos2d-x returns bool, instead of 'id' in cocos2d-iphone (anobject pointer)
    virtual boolinit();

    // there's no 'id'in cpp, so we recommend to return the class instancepointer
    staticcocos2d::CCScene* scene();
   
    // a selectorcallback
    voidmenuCloseCallback(CCObject* pSender);

    // preprocessormacro for "static create()" constructor ( node() deprecated)
   CREATE_FUNC(HelloWorld);
    voidGameLogic(float dt);
   
};

#endif //__HELLOWORLD_SCENE_H__




#include"HelloWorldScene.h"
#include"SimpleAudioEngine.h"

using namespacecocos2d;
using namespaceCocosDenshion;

CCScene*HelloWorld::scene()
{
    // 'scene' is anautorelease object
    CCScene *scene =CCScene::create();
   
    // 'layer' is anautorelease object
    HelloWorld *layer =HelloWorld::create();

    // add layer as achild to scene
   scene->addChild(layer);

    // return thescene
    returnscene;
}

// on "init"you need to initialize your instance
boolHelloWorld::init()
{
   //////////////////////////////
    // 1. super initfirst
    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);
    returntrue;
}
voidHelloWorld::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);
    }

}
voidHelloWorld::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的跟随效果





原创粉丝点击