加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cocos2d-x实现打字机效果

发布时间:2020-12-14 18:52:37 所属栏目:百科 来源:网络整理
导读:打字机的效果,一般出现在对话和游戏的剧情介绍中(现在已经很少用了,有几个人一个字一个字的看剧情呀)。 这里有两种方案实现了打字机的效果。一种是使用系统字体,一种是使用TTF字体。下面一一介绍。 1.使用LabelTTF实现。 在cocos3.x中Label有了新的API
打字机的效果,一般出现在对话和游戏的剧情介绍中(现在已经很少用了,有几个人一个字一个字的看剧情呀)。
这里有两种方案实现了打字机的效果。一种是使用系统字体,一种是使用TTF字体。下面一一介绍。
1.使用LabelTTF实现。
在cocos3.x中Label有了新的API,新的Label将每个字符作为一个Letter来存储。通过getLetter(int index)方法得到。得到的Letter实际上是一个个精灵(Sprite)。
要实现打字机的效果,可以先将Label中的所有Letter设置为不可见(setVisible),然后,一个一个的设置为可见,那么,最终的效果就是打字机的效果了。
上代码:


  Label * l = Label ::createWithTTF ( StringRes:: getText ("print_text" ),"ygyxsziti2.0.ttf",20 );
         addChild (l );
         l ->setPosition ( Vec2( 400,240 ));
         int index = 0 ;
         while ( l ->getLetter ( index) != nullptr )
         {
                 l ->getLetter ( index)-> setVisible (false );
                 index ++;
         }
         int s = l ->getString (). size();
         log ("index:%d___s:%d",index,s );

         index = 0;
         while ( l ->getLetter ( index) != nullptr )
         {
                 l ->getLetter ( index)-> runAction (
                         Sequence ::create (
                         DelayTime ::create ( index * 0.1f ),Show ::create (),nullptr )
                         );
                 index ++;
         }

2.上面的方式是不适用系统字体的,也就是不适用createWidthSystemFont,这种方案主要针对系统字体,思路是不断改变Label的显示内容(显示内容一个字一个字的增加)。
上代码:
static std:: string content = "aaaabbbbccccddd  eeefff,dossad  ";
         static int n = 0 ;
         static Label * l2 = Label:: create ();
         l2 ->setString ( "");
         l2 ->setAnchorPoint ( Vec2( 0,0.5f ));
         l2 ->setSystemFontSize ( 20);
         addChild (l2 );
         l2 ->setPosition ( Vec2( 400,100 ));
         this ->schedule ([&]( float dt ){
                 std :: string str = content. substr (0,n );
                 //n += 3;//中文加3
                 n += 1;//英文加1
                 l2 ->setString ( str);
                 if ( n > content. length ())
                 {
                         unschedule ("schedule_callback" );
                 }
         },0.1f,"schedule_callback" );

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读