CCScrollLayer в Cocos2dx

Мне нужно сделать вертикальную прокрутку для моего слоя. Я пробовал CCScrollLayer, но он не работает. Как я могу это сделать?

MissionLayer.h

#include "cocos2d.h"

using namespace cocos2d;    
class MissionLayer : public CCLayer
{    
public:
    MissionLayer();
    virtual ~MissionLayer();
    CREATE_FUNC(MissionLayer);
};    

MissionLayer.cpp

MissionLayer::MissionLayer()
{
    // TODO Auto-generated constructor stub 
    CCSprite* sprite = CCSprite::create("tab2_scene.jpg");
    addChild(sprite,1);    
}    
MissionLayer::~MissionLayer() {
    // TODO Auto-generated destructor stub
}

person Sumit Kandoi    schedule 27.12.2013    source источник
comment
Вы пробовали CCClipingNode пример?   -  person Vikas Patidar    schedule 27.12.2013
comment
почему слой прокрутки не работает?   -  person LearnCocos2D    schedule 27.12.2013
comment
на самом деле, я использую его, но я не знаю, как правильно его реализовать   -  person Sumit Kandoi    schedule 27.12.2013


Ответы (2)


Прежде всего, включите касания в слое Mission.

setTouchEnabled(true); //in your constructor or init method

После этого для движения только по оси Y ваш (ccTouchesMoved/ccTouchMoved) будет выглядеть так

void MissionLayer::ccTouchesMoved(CCSet* pTouches, CCEvent* event)
{
 CCTouch *touch=(CCTouch*)pTouches->anyObject();
 CCPoint newTouchLocation = touch->getLocationInView();
 newTouchLocation = CCDirector::sharedDirector()->convertToGL(newTouchLocation);

 CCPoint oldTouchLocation = touch->getPreviousLocationInView();
 oldTouchLocation = CCDirector::sharedDirector()->convertToGL(oldTouchLocation);

 //get the difference in the finger touches when the player was dragging
 float differenceY = newTouchLocation.y- oldTouchLocation.y; //Only in Y axis  
 float newPosY=getPositionY()+differenceY;

 // Now we have to check new position comes in bounding box .
 // Let assume maxY,minY are upper or lower limit    

 if (newPosY>minY) {
    newPosY=minY;
 }   
 if (newPosY < maxY) {
    newPosY=maxY;
 }
 setPositionY(newPosY);
}    
person Vivek Bansal    schedule 27.12.2013
comment
jni/../../Classes/BullUI/CCScrollLayer.cpp:98:68: ошибка: недопустимая инициализация ссылки типа 'const cocos2d::CCPoint&' из выражения типа 'float' - person Sumit Kandoi; 30.12.2013
comment
В этой строке он показывает мне разницу с плавающей запятой Y = ccpSub(newTouchLocation.y, oldTouchLocation.y); - person Sumit Kandoi; 30.12.2013
comment
Я решил это. отредактировав эту строку, float разностьY = newTouchLocation.y - oldTouchLocation.y; - person Sumit Kandoi; 30.12.2013

Я надеюсь, что это поможет вам . В зависимости от ваших требований вы можете изменить вертикальную прокрутку.

В CCScrollLayer.h

#pragma once
#include "cocos2d.h"


    class CCScrollLayer : public cocos2d::CCLayer 
    {

    public:

        static CCScrollLayer* create(cocos2d::CCArray* layers,int widthOffset);

        bool init(cocos2d::CCArray *layers,int widthOffset);
            // Holds the current page being displayed
        int currentScreen;
        void moveToPage(int page);

    private:

        // Holds the current height and width of the screen
        int scrollHeight;
        int scrollWidth;

        // Holds the height and width of the screen when the class was inited
        int startHeight;
        int startWidth;



        // A count of the total screens available
        int totalScreens;

        // The initial point the user starts their swipe
        int startSwipe; 

        void moveToNextPage();
        void moveToPreviousPage();


        virtual bool ccTouchBegan(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent);
        virtual void ccTouchMoved(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent);
        virtual void ccTouchEnded(cocos2d::CCTouch* pTouch, cocos2d::CCEvent* pEvent);  

        virtual void onEnter();
        virtual void onExit();

        void changePageIndicator();

    };

В CCScrollLayer.cpp

#include "CCScrollLayer.h"

USING_NS_CC;

CCScrollLayer* CCScrollLayer::create(CCArray *layers, int widthOffset)
{   
    CCScrollLayer *pRet = new CCScrollLayer();
    if (pRet && pRet->init(layers, widthOffset))
    {
        pRet->autorelease();
        return pRet;
    }
    CC_SAFE_DELETE(pRet);
    return NULL;
}

bool CCScrollLayer::init(CCArray *layers, int widthOffset)
{   
    if (CCLayer::init())
    {       
        // Set up the starting variables
        if(!widthOffset)
        {
            widthOffset = 0;
        }   
        currentScreen = 1;

        // offset added to show preview of next/previous screens
        CCSize s=CCDirector::sharedDirector()->getWinSize();

        scrollWidth  = s.width - widthOffset;
        scrollHeight = s.height;
        startWidth = scrollWidth;
        startHeight = scrollHeight;

        // Loop through the array and add the screens
        unsigned int i;
        for (i=0; i<layers->count(); i++)
        {
            CCLayer* l = static_cast<CCLayer*>(layers->objectAtIndex(i));
            l->setAnchorPoint(ccp(0,0));
            l->setPosition(ccp((i*scrollWidth),0));
            addChild(l);            
        }

        // Setup a count of the available screens
        totalScreens = layers->count();
        return true;    
    }


    return false;

}

void CCScrollLayer::onEnter()
{

    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, false);
    CCLayer::onEnter();
}

void CCScrollLayer::onExit()
{
    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);

    CCLayer::onExit();
}   

void CCScrollLayer::changePageIndicator() {
    LevelSelectionScene* scene = (LevelSelectionScene*) this -> getParent();
    if(scene != NULL) {
        scene -> changePageIndicator(currentScreen);
    }
}

void CCScrollLayer::moveToPage(int page)
{   
    CCEaseBounce* changePage = CCEaseBounce::create(CCMoveTo::create(0.3f, ccp(-((page-1)*scrollWidth),0)));
    this->runAction(changePage);
    currentScreen = page;

    changePageIndicator();
}

void CCScrollLayer::moveToNextPage()
{   
    CCEaseBounce* changePage = CCEaseBounce::create(CCMoveTo::create(0.3f, ccp(-(((currentScreen+1)-1)*scrollWidth),0)));

    this->runAction(changePage);
    currentScreen = currentScreen+1;

    changePageIndicator();
}

void CCScrollLayer::moveToPreviousPage()
{   
    CCEaseBounce* changePage =CCEaseBounce::create(CCMoveTo::create(0.3f, ccp(-(((currentScreen-1)-1)*scrollWidth),0)));
    this->runAction(changePage);
    currentScreen = currentScreen-1;

    changePageIndicator();
}


bool CCScrollLayer::ccTouchBegan(CCTouch *touch, CCEvent *withEvent)
{

    CCPoint touchPoint = touch->getLocation(); // Get the touch position
    touchPoint = this->getParent()->convertToNodeSpace(touchPoint);


    startSwipe = (int)touchPoint.x;
    return true;
}

void CCScrollLayer::ccTouchMoved(CCTouch *touch, CCEvent *withEvent)
{   

    CCPoint touchPoint = touch->getLocation(); // Get the touch position
    touchPoint = this->getParent()->convertToNodeSpace(touchPoint);

    this->setPosition(ccp((-(currentScreen-1)*scrollWidth)+(touchPoint.x-startSwipe),0));
}

void CCScrollLayer::ccTouchEnded(CCTouch *touch, CCEvent *withEvent)
{
    CCPoint touchPoint = touch->getLocation(); // Get the touch position
    touchPoint = this->getParent()->convertToNodeSpace(touchPoint);

    int newX = (int)touchPoint.x;

    if ( (newX - startSwipe) < -scrollWidth / 7 && (currentScreen+1) <= totalScreens )
    {
        this->moveToNextPage();
    }
    else if ( (newX - startSwipe) > scrollWidth / 7 && (currentScreen-1) > 0 )
    {
        this->moveToPreviousPage();
    }
    else
    {
        this->moveToPage(currentScreen);        
    }   
}
person pankaj khanduja - Game Changer    schedule 05.12.2014