Godot 4.2.2 2D平台游戏Dash斜向冲刺距离过短问题求助
问题分析与解决方案
你的斜向冲刺距离变短的核心原因有两个:
dash()函数中重复执行了dash_charge -= 1和dashing = true,虽不直接影响冲刺距离,但会导致冲刺次数异常减少。- 在
_physics_process中调用包含await的函数,可能引发协程与物理帧的执行冲突,导致冲刺速度未被稳定应用。
当前代码依赖协程暂停实现冲刺时长,容易出现时序问题,改用物理帧内的计时器变量会更可靠。
修复后的完整代码
extends CharacterBody2D @onready var sprite_0001_png = $"Sprite-0001_png" const dash_time = 0.1 const dash_speed = 600 var dashing = false var dash_charge = 1 var dash_timer = 0.0 # 添加冲刺计时器变量 var movement_lock = false const SPEED = 250 const JUMP_VELOCITY = -600 var death = 0 var player_pos var mouse_pos func _process(delta): mouse_pos = get_global_mouse_position() player_pos = get_global_position() var gravity = ProjectSettings.get_setting("physics/2d/default_gravity") func player_die(): velocity = Vector2(0, 0) movement_lock = true await get_tree().create_timer(1).timeout get_tree().reload_current_scene() movement_lock = false func _physics_process(delta): # 处理冲刺计时与状态重置 if dashing: dash_timer -= delta if dash_timer <= 0: dashing = false movement_lock = false else: # 仅在非冲刺状态检测冲刺输入 handle_dash_input() # 重力处理 if not movement_lock and not is_on_floor(): velocity.y += gravity * delta # 恢复冲刺次数 if is_on_floor() and dash_charge < 1: dash_charge += 1 # 跳跃处理 if not movement_lock and Input.is_action_just_pressed("jump") and is_on_floor(): velocity.y = JUMP_VELOCITY # 移动处理 if not movement_lock: var direction = Input.get_axis("move_left", "move_right") if direction: velocity.x = direction * SPEED else: velocity.x = move_toward(velocity.x, 0, 15) # Sprite翻转 sprite_0001_png.flip_h = velocity.x < 0 move_and_slide() # 拆分冲刺输入处理为独立函数 func handle_dash_input(): if dash_charge > 0 and Input.is_action_just_pressed("dash"): velocity = Vector2.ZERO movement_lock = true dash_charge -= 1 dashing = true dash_timer = dash_time # 计算鼠标方向并归一化 var dir = (mouse_pos - player_pos).normalized() # 避免鼠标与玩家重合时的零向量 if dir == Vector2.ZERO: dir = Vector2.RIGHT # 默认向右 velocity = dir * dash_speed
关键修改点
- 移除了
dash()函数中的重复代码,避免冲刺次数异常消耗。 - 用
dash_timer变量替代await协程,在物理帧内处理冲刺计时,逻辑更稳定。 - 将冲刺输入处理拆分为独立函数,仅在非冲刺状态下检测输入,防止重复触发。
- 添加零向量判断,解决鼠标与玩家位置重合时无法冲刺的问题。
修改后,无论水平、垂直还是斜向冲刺,都会以dash_speed * dash_time的固定距离移动,彻底解决斜向距离减半的问题。
内容的提问来源于stack exchange,提问作者rock w
相关产品推荐
相关产品推荐

