GDScript多帧跳跃动画编码问题求助(2D平台游戏)
解决方案:硬编码实现多帧跳跃动画
针对你的问题,核心是调整动画逻辑的优先级,确保跳跃动画不会被地面动画覆盖,同时通过运动状态判断来播放对应多帧动画。下面是修改后的代码及关键说明:
修改后的完整代码
extends KinematicBody2D const SPD = 100 const GRV = 15 const JUMPF = -350 const SPD_B = 50 var velocity = Vector2(0,0) # 修正拼写错误:valocity -> velocity func _process(delta): # 1. 处理水平输入与速度 var horizontal_input = 0 if Input.is_action_pressed("ui_right"): horizontal_input = 1 elif Input.is_action_pressed("ui_left"): horizontal_input = -1 var current_speed = SPD if Input.is_action_pressed("ui_sprint"): current_speed += SPD_B velocity.x = horizontal_input * current_speed # 2. 处理重力与跳跃 velocity.y += GRV if Input.is_action_just_pressed("ui_up") and is_on_floor(): velocity.y = JUMPF # 3. 执行移动 velocity = move_and_slide(velocity, Vector2.UP) velocity.x = lerp(velocity.x, 0, 0.3) # 4. 硬编码控制动画(核心部分) # 优先处理空中跳跃动画 if not is_on_floor(): # 根据Y轴速度判断跳跃阶段,播放对应多帧动画 if velocity.y < 0: # 上升阶段:播放jump_up动画 if $AnimatedSprite.animation != "jump_up": $AnimatedSprite.play("jump_up") else: # 下落阶段:播放jump_down动画 if $AnimatedSprite.animation != "jump_down": $AnimatedSprite.play("jump_down") # 保持角色朝向 if horizontal_input != 0: $AnimatedSprite.flip_h = horizontal_input < 0 else: # 地面状态动画 if horizontal_input != 0: if Input.is_action_pressed("ui_sprint"): if $AnimatedSprite.animation != "run": $AnimatedSprite.play("run") else: if $AnimatedSprite.animation != "walk": $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = horizontal_input < 0 else: if $AnimatedSprite.animation != "idle": $AnimatedSprite.play("idle") func _on_Area2D_body_entered(body): get_tree().reload_current_scene()
关键改动说明
动画优先级调整
把空中动画判断放在最前面,避免地面动画(idle/walk/run)覆盖跳跃动画,这是你之前代码的核心问题。避免动画重置
通过$AnimatedSprite.animation != "目标动画名"判断是否需要切换动画,防止每帧调用play()导致多帧动画被反复重置,无法完整播放。跳跃阶段区分
根据velocity.y的正负判断角色处于跳跃上升还是下落阶段,分别对应不同的多帧动画,让跳跃动作更自然。状态一致性
在空中时依然根据水平输入保持角色朝向,确保移动逻辑和视觉表现统一。
额外提示
- 确保你的
AnimatedSprite节点中已添加对应动画(jump_up、jump_down,如果只有一套跳跃动画,可合并为jump并简化判断逻辑)。 - 测试时注意调整动画的播放速度,让动画节奏与跳跃运动匹配。
内容的提问来源于stack exchange,提问作者Niko Kone
相关产品推荐
相关产品推荐

