如何在Godot中根据移动方向播放动画
Godot俯视角8方向移动动画高效实现方案
不用再逐个判断按键组合了,直接利用你已经获取的direction向量就能搞定,代码简洁还能解决卡顿问题。以下是具体实现步骤:
1. 准备动画资源
确保你的AnimationPlayer节点下已经创建好对应8个方向的移动动画(命名建议:up、up_right、right、down_right、down、down_left、left、up_left),再加一个静止动画idle。
2. 修改移动代码
直接基于现有移动逻辑扩展动画控制,核心是通过方向向量的角度判断当前移动方向,避免冗余的按键判断:
extends CharacterBody2D var speed = 100 # 提前获取动画播放器节点 @onready var anim_player = $AnimationPlayer # 定义方向到动画名称的映射(常量,避免重复创建) const ANIMATION_MAP = [ "right", "up_right", "up", "up_left", "left", "down_left", "down", "down_right" ] func _physics_process(delta): var direction = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down").normalized() velocity = direction * speed # 处理动画切换逻辑 if direction.length_squared() < 0.01: # 静止状态:仅当前动画不是idle时才切换,避免频繁调用导致卡顿 if anim_player.current_animation != "idle": anim_player.play("idle") else: # 通过向量角度计算当前方向索引 var angle = direction.angle() # 将角度转换为0-7的索引(对应8个方向) var direction_index = round(angle / (PI / 4)) % 8 var target_anim = ANIMATION_MAP[int(direction_index)] # 仅目标动画与当前动画不同时播放,减少不必要的动画切换 if anim_player.current_animation != target_anim: anim_player.play(target_anim) move_and_slide()
关键优化点说明
- 避免冗余判断:直接用
direction向量的角度推导移动方向,不用再写一堆if Input.is_action_pressed("ui_up") and Input.is_action_pressed("ui_right")这类判断 - 减少卡顿根源:只有当前动画和目标动画不一致时才调用
play,避免每一帧重复触发动画切换 - 性能优化:用
length_squared()判断静止状态(无需开根号,比length()更高效),将动画映射数组设为常量,避免每次函数调用都重新创建
额外平滑建议
如果动画切换还是不够流畅,可以在AnimationPlayer的动画属性里设置Blend Time(混合时长),或者把anim_player.play(target_anim)改成anim_player.play_with_blend(target_anim, 0.1),给动画切换加个短过渡。
内容的提问来源于stack exchange,提问作者Rebecca Marshall
相关产品推荐
相关产品推荐

