如何在GDScript三消游戏中用Tween实现方块平滑交换而非瞬移
用GDScript的Tween实现三消方块交换动画
我正在跟着YouTube教程用GDScript开发一款三消游戏,想调整脚本用Tween实现两个方块的位置交换动画,目前的交换函数是瞬间完成位置切换,尝试的Tween代码无法正常工作,以下是修正方案:
原交换函数(无动画)
func swap_pieces(column, row, direction): var first_piece = all_pieces[column][row]; var other_piece = all_pieces[column+direction.x][row+direction.y]; all_pieces[column][row] = other_piece; all_pieces[column + direction.x][row + direction.y] = first_piece; first_piece.position = grid_to_pixel(column + direction.x, row + direction.y); other_piece.position = grid_to_pixel(column, row);
错误尝试的问题点
原Tween代码中,tween_property的目标位置传成了节点对象(other_piece、first_piece),但实际需要传入的是目标坐标值,导致动画无法正确执行。
修正后的带动画交换函数
func swap_pieces(column, row, direction): var first_piece = all_pieces[column][row] var other_piece = all_pieces[column + direction.x][row + direction.y] # 计算两个方块的目标像素位置 var first_target_pos = grid_to_pixel(column + direction.x, row + direction.y) var other_target_pos = grid_to_pixel(column, row) # 创建Tween实例,设置并行动画 var tween = create_tween() tween.set_parallel(true) # 为两个方块添加位置动画,时长0.3秒(可按需调整) tween.tween_property(first_piece, "position", first_target_pos, 0.3) tween.tween_property(other_piece, "position", other_target_pos, 0.3) # 动画完成后同步更新数组中的方块引用,避免状态不一致 tween.finished.connect(func(): all_pieces[column][row] = other_piece all_pieces[column + direction.x][row + direction.y] = first_piece )
关键说明
- 必须传递目标坐标值给
tween_property,而非节点对象 - 使用
set_parallel(true)让两个方块的交换动画同时播放,保证视觉同步 - 动画完成后再更新
all_pieces数组,避免动画过程中数组状态与视觉显示不一致 - 动画时长(示例中0.3秒)可根据游戏手感调整
内容的提问来源于stack exchange,提问作者jon vie
相关产品推荐
相关产品推荐

