如何在Term::Animation中同时实现角色悬浮与帧切换?
问题描述
我有一个人类角色对象:
- 当用
my @path作为运动路径时,角色能呈现悬浮效果,但不会切换帧; - 把
callback_args => [0,[@path]]改成callback_args => [0,0,0,1]后,角色能切换帧,但没了悬浮效果。
我发现最后一位数值≠0时会更新帧,这个数值对应帧切换速度,而且$up和$down的最后一位都≠0,我只修改Y轴(X/Y/Z中的Y)来实现上下移动。请问怎么同时保留悬浮效果和角色的两帧切换?
原代码
use strict; use warnings; use Curses; use Term::Animation 2.0; my $s = Term::Animation->new(); $s->color(1); # <-- uses the color2 type mask my @human= (q{ o /#\ / \ }, q{ \o> # / \ }); my $up = [0,-.3,0,.5]; my $down = [0,.3,0,.5]; my @path; for(1..14){ push(@path, $up); } for(1..14){ push(@path, $down)} $s->new_entity( shape => \@human, position => [ 5, 5, 1], callback_args => [0, [@path] ], color => 'w', wrap => 1, ); halfdelay( 2 ); for(1..500) { $s->animate(); my $in = lc( getch() ); if($in eq 'q') { last; } }
解决方案
问题出在Term::Animation的默认路径回调逻辑上:当传入路径数组时,它只会执行位置更新,忽略帧切换参数。要同时实现移动和帧切换,需要自定义回调函数,在每次动画循环里同时处理位置变化和帧更新。
修改后的代码如下:
use strict; use warnings; use Curses; use Term::Animation 2.0; my $s = Term::Animation->new(); $s->color(1); my @human = ( q{ o /#\ / \ }, q{ \o> # / \ } ); # 保存实体的状态:当前路径进度、帧索引、基础Y位置 my $entity_state = { path_step => 0, frame_idx => 0, base_y => 5, }; # 创建实体,绑定自定义回调 my $entity = $s->new_entity( shape => \@human, position => [5, 5, 1], callback => \&animate_human, callback_args => $entity_state, color => 'w', wrap => 1, ); # 自定义回调:同时处理悬浮移动和帧切换 sub animate_human { my ($entity, $state) = @_; # 定义上下移动的路径:14步向上,14步向下 my @path = ( (map { [0, -.3] } 1..14), (map { [0, .3] } 1..14) ); # 更新角色Y轴位置 my $current_offset = $path[$state->{path_step}][1]; $entity->position([5, $state->{base_y} + $current_offset, 1]); # 切换动画帧 $state->{frame_idx} = ($state->{frame_idx} + 1) % scalar(@human); $entity->frame($state->{frame_idx}); # 循环路径进度 $state->{path_step} = ($state->{path_step} + 1) % scalar(@path); } halfdelay(2); for (1..500) { $s->animate(); my $in = lc(getch()); last if $in eq 'q'; }
关键说明
- 自定义回调
animate_human在每次动画循环里,同时完成Y轴位置更新和帧切换,实现悬浮+帧动画的同步; - 用
$entity_state保存状态变量,记录当前的路径进度和帧索引,保证动画循环执行; - 路径数组只保留X/Y偏移,帧切换逻辑单独处理,避免默认回调的参数冲突。
内容的提问来源于stack exchange,提问作者Exponecial
相关产品推荐
相关产品推荐

