打字机的效果,一般出现在对话和游戏的剧情介绍中(现在已经很少用了,有几个人一个字一个字的看剧情呀)。
这里有两种方案实现了打字机的效果。一种是使用系统字体,一种是使用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" );