如何实现玩家攻击时仅小幅移动,非攻击时正常移动?
问题修复方案
核心问题分析
- 攻击状态切换逻辑错误:
attack()函数中仅在一帧内就将状态切回MOVE,导致攻击状态根本无法持续,玩家自然能正常移动。 - 攻击状态未处理移动逻辑:原代码在攻击时直接跳过物理更新,既没实现小幅移动,也导致状态管理失效。
- 输入拼写错误:
Input.get_vector中的"rihgt"应为"right",会导致右方向输入无效。
修改后的完整代码
extends CharacterBody2D @export var speed: float = 100 @export var accel: float = 10 @export var attack_speed: float = 30 # 攻击时的小幅移动速度 @export var dashing = false @export var dashdistance: float = 300 @export var attacking = false @export var attackdistance: float = 100 @export var dasheffect = preload("res://dasheffect.tscn") @onready var anime = $AnimatedSprite2D @onready var sword: Node2D = get_node("sword") @onready var sword_anime: AnimationPlayer = get_node("sword/SwordAnimationPlayer") enum States { MOVE, ATTACK } var state = States.MOVE func _process(_delta: float) -> void: var mouse_direction: Vector2 = (get_global_mouse_position() - global_position).normalized() sword.rotation = mouse_direction.angle() if mouse_direction.x > 0 and anime.flip_h: anime.flip_h = false elif mouse_direction.x < 0 and not anime.flip_h: anime.flip_h = true func _physics_process(delta): match state: States.MOVE: move(delta) States.ATTACK: attack_move(delta) # 攻击状态下处理小幅移动 func move(delta): var direction: Vector2 = Input.get_vector("left", "right", "up", "down") # 修复拼写错误 velocity.x = move_toward(velocity.x, speed * direction.x, accel) velocity.y = move_toward(velocity.y, speed * direction.y, accel) if velocity != Vector2.ZERO: anime.play("run") else: anime.play("idle") dash() move_and_slide() if Input.is_action_just_pressed("attack"): state = States.ATTACK attacking = true sword_anime.play("swing") anime.play("attack") func attack_move(delta): # 攻击状态下允许小幅移动 var direction: Vector2 = Input.get_vector("left", "right", "up", "down") velocity.x = move_toward(velocity.x, attack_speed * direction.x, accel) velocity.y = move_toward(velocity.y, attack_speed * direction.y, accel) move_and_slide() # 等待攻击动画结束后切回移动状态 if sword_anime.is_playing() == false: state = States.MOVE attacking = false func dash(): var mouse_direction: Vector2 = (get_global_mouse_position() - global_position).normalized() if Input.is_action_just_pressed("ui_accept"): velocity = mouse_direction.normalized() * dashdistance dashing = true await get_tree().create_timer(0.2) dashing = false
关键修改点
- 新增
attack_speed变量控制攻击时的移动速度,实现小幅移动效果。 - 重构攻击状态逻辑:将攻击动画播放和状态切换分离,通过监听动画是否结束来切回移动状态,确保攻击过程持续。
- 修复方向输入的拼写错误,保证右方向键正常工作。
- 在
_physics_process中根据状态分别处理移动或攻击移动,不再提前return跳过物理更新。
内容的提问来源于stack exchange,提问作者Space Kim
相关产品推荐
相关产品推荐

