cocos2dx 3.x 公告栏 通知栏 滚动字幕 区域弹幕 区域显示 实现

本文介绍游戏中常见的滚动播放的公告栏实现

要点

  • 文字内容横向或者纵向滚动
  • 文字只在区域内显示,超出区域部分不显示

相关头文件

** "2d/CCClippingNode.h" **
注意:在cocos2dx 3.x版本中,方法名中的CC命名方式已经弃用,但是文件名中的CC依然有,所以此处的头文件名中的CC打头无法去除

实现

头文件

#pragma once
#include "cocos2d.h"
#include "2d/CCClippingNode.h"
USING_NS_CC;

class PannelNews :public Node
{
protected:
  Node* _holder;
  Sprite* _newsBg;
  Label* _news;
  DrawNode* _shap;
  ClippingNode* _cliper;

public:
  PannelNews();
  ~PannelNews();
  virtual bool init() override;

  void layout();
  void scrollText(float);

  CREATE_FUNC(PannelNews);
};

源文件

#include "PannelNews.h"

PannelNews::PannelNews()
{
  _holder = NULL;
  _newsBg = NULL;
  _news = NULL;
  _shap = NULL;
  _cliper = NULL;
}

PannelNews::~PannelNews() {}

bool PannelNews::init()
{
  if (!Node::init())
    return false;
  setPosition(Point(640.f, 585.f));
  _holder = Node::create();
  addChild(_holder);
  _newsBg = Sprite::create("newsBg.png");
  _holder->addChild(_newsBg);

  _shap = DrawNode::create();
  Point point[4] = { Point(60.f,0.f), Point(710.f,0.f), Point(710.f,35.f),   Point(60.f,35.f)};
  //标记显示的矩形区域

  _shap->drawPolygon(point, 4, Color4F(355, 255, 255, 255), 2, Color4F(255, 255, 255, 255));
  //剪切用于显示的矩形区域,参数对应:用于标识区域的Point(Vec2)数组指针,数组长度,填充颜色,边框宽度,边框颜色
  _cliper = ClippingNode::create();
  _cliper->setStencil(_shap);
  _cliper->setAnchorPoint(Point(0.5, 0.5));
  _newsBg->addChild(_cliper);

  _news = Label::createWithSystemFont(UserDefault::getInstance()->getStringForKey(KEY_LOCAL_NEWS, "公告内容"), "Microsoft Yahei", 24);
  _news->setColor(Color3B(214, 213, 213));
  _cliper->addChild(_news);

  layout();
  return true;
}

void PannelNews::layout()
{
 _news->setAnchorPoint(Point::ZERO);
 _news->setPosition(Point(720, 10));//设置公告文字内容的初始位置
 schedule(schedule_selector(PannelNews::scrollText));//实现公告文字滚动
}

void PannelNews::scrollText(float)
{
 _news->getPosition().x < (-1 * _news->getContentSize().width) ? _news->setPositionX(720) : _news->setPositionX(_news->getPositionX() - 2);
}
  • ClippingNode可以用于设定一个区域作为其显示区域,其子节点只可在该区域内才可显示,超出区域部分则无法显示,可用于公告、通知、聊天框、区域弹幕、弹幕游戏的保护罩等

你可能感兴趣的:(cocos2dx 3.x 公告栏 通知栏 滚动字幕 区域弹幕 区域显示 实现)