Cocos2d-x教程(29)-3.x版本遮罩層實現捕魚達人滾動數字錶盤,cocos2d-x-3.x
歡迎加入Cocos2d-x 交流群:193411763
轉載時請註明原文出處 : http://blog.csdn.net/u012945598/article/details/38340845
源碼:http://download.csdn.net/detail/u012945598/7704725
之前在第八篇教程中講解了遮罩層實現捕魚達人滾動數字錶盤(文章連結:http://blog.csdn.net/u012945598/article/details/17049419),後來有很多朋友問3.x版本中遮罩無效,導致方法不能使用,其實方法還是能用的,只是代碼需要略加修改,筆者這裡重新貼出ScrollLabel類的實現。各位可直接copy替換即可。
ScrollLabel.h檔案
#include <iostream>
#include "cocos2d.h"
#include <stdlib.h>
USING_NS_CC;
class ScrollLabel :publicNode{
public:
virtual bool init();
CREATE_FUNC(ScrollLabel);
std::vector<Label *> labels;/* 用來儲存label的數組 */
Node * visibleNode; /* 建立一個節點,將label添加到節點上,便於移動 */
void setNumber(int var ,bool up); /*設定滾動到哪個數位方法,參數var是滾動到的數字 */
/* ----- 修改內容 ------- */
/* 重載CCNode中的visit方法,此處不使用draw方法 */
virtual void visit(Renderer* renderer,constkmMat4 &parentTransform,bool parentTransformUpdated);
void onAfterVisitScissor();
void onBeforeVisitScissor();
public:
CustomCommand _beforeVisitCmdScissor;
CustomCommand _afterVisitCmdScissor;
};
ScrollLabel.cpp 檔案
#include "ScrollLabel.h"
bool ScrollLabel::init(){
visibleNode=Node::create();
this->addChild(visibleNode);
/*建立十個標籤,數字0-9 */
for(int i=0;i<10;i++){
char str[2];
str[0]='0'+i;
str[1]='\0';
Label * single=Label::create();
single->setSystemFontSize(20.0);
single->setColor(Color3B(0,0,0));//設定標籤字型顏色
single->setTag(i);
single->setString(str);
single->setAnchorPoint(Point(0,0));//將錨點設為0,0便於設定座標
single->setPosition(Point(0,20 *i));
visibleNode->addChild(single);
labels.push_back(single); //將標籤存入數組中
}
return true;
}
void ScrollLabel::setNumber(int var,bool up =true){
this->stopAllActions();
/*擷取到要移動到的label的座標*/
Label * label=labels[var];
Point moveToPosition =Point(visibleNode->getPositionX(),-(label->getPositionY()));
/*建立一個動作,移動到該label的位置*/
MoveTo * moveAction =MoveTo::create(5, moveToPosition);
visibleNode->runAction(moveAction);
}
void ScrollLabel::visit(Renderer* renderer,constkmMat4 &parentTransform,bool parentTransformUpdated){
_beforeVisitCmdScissor.init(_globalZOrder);
_beforeVisitCmdScissor.func =CC_CALLBACK_0(ScrollLabel::onBeforeVisitScissor,this);
renderer->addCommand(&_beforeVisitCmdScissor);
Node::visit(renderer, parentTransform, parentTransformUpdated);
_afterVisitCmdScissor.init(_globalZOrder);
_afterVisitCmdScissor.func =CC_CALLBACK_0(ScrollLabel::onAfterVisitScissor,this);
renderer->addCommand(&_afterVisitCmdScissor);
}
void ScrollLabel::onBeforeVisitScissor()
{
Point pos=Point(0,0);
pos=visibleNode->getParent()->convertToWorldSpace(pos);
Rect clippingRect =Rect(pos.x, pos.y,20,20);
glEnable(GL_SCISSOR_TEST);
auto glview =Director::getInstance()->getOpenGLView();
glview->setScissorInPoints(clippingRect.origin.x, clippingRect.origin.y, clippingRect.size.width, clippingRect.size.height);
}
void ScrollLabel::onAfterVisitScissor()
{
glDisable(GL_SCISSOR_TEST);
}
使用方法和以前相同:
ScrollLabel * m_scroll=ScrollLabel::create();
m_scroll->setPosition(Point(568,320));
this->addChild(m_scroll);
m_scroll->setNumber(5,true);
最後附上一張: