cocos2d-x实现打字机效果

前端之家收集整理的这篇文章主要介绍了cocos2d-x实现打字机效果前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
打字机的效果,一般出现在对话和游戏的剧情介绍中(现在已经很少用了,有几个人一个字一个字的看剧情呀)。
这里有两种方案实现了打字机的效果。一种是使用系统字体,一种是使用TTF字体。下面一一介绍。
1.使用LabelTTF实现。
在cocos3.x中Label有了新的API,新的Label将每个字符作为一个Letter来存储。通过getLetter(int index)方法得到。得到的Letter实际上是一个个精灵(Sprite)。
要实现打字机的效果,可以先将Label中的所有Letter设置为不可见(setVisible),然后,一个一个的设置为可见,那么,最终的效果就是打字机的效果了。
代码


  1. Label * l = Label ::createWithTTF ( StringRes:: getText ("print_text" ),"ygyxsziti2.0.ttf",20 );
  2. addChild (l );
  3. l ->setPosition ( Vec2( 400,240 ));
  4. int index = 0 ;
  5. while ( l ->getLetter ( index) != nullptr )
  6. {
  7. l ->getLetter ( index)-> setVisible (false );
  8. index ++;
  9. }
  10. int s = l ->getString (). size();
  11. log ("index:%d___s:%d",index,s );
  12.  
  13. index = 0;
  14. while ( l ->getLetter ( index) != nullptr )
  15. {
  16. l ->getLetter ( index)-> runAction (
  17. Sequence ::create (
  18. DelayTime ::create ( index * 0.1f ),Show ::create (),nullptr )
  19. );
  20. index ++;
  21. }

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

猜你在找的Cocos2d-x相关文章