Unity新旧Input System切换后Dash功能失效问题求助
问题解决:Unity新Input System下Dash功能失效修复
核心问题分析
你的代码存在两个致命问题导致Dash不生效:
- 方向计算完全错误:新Input System的
DashAction里,你把dirX赋值成了transform.position.x(物体的世界坐标X值),这和旧代码里获取水平输入轴的逻辑完全不同。用坐标值乘以dashDistance会得到异常大的速度值,要么直接超出物理限制,要么方向完全不符合预期。 - 缺失关键状态校验:旧代码里触发Dash前会检查
dashing和canDash状态,但新的Dash回调函数里没有这些判断,导致即使在Dash过程中或冷却阶段,双击依然会触发协程,造成状态混乱。
修复后的完整代码
1. 先声明Input Action引用
在类中添加对应的Input Action变量(需提前在Input Action Asset中创建好Horizontal和Dash动作):
public InputAction horizontalAction; public InputAction dashAction; private bool canDash = true; private bool dashing = false; private bool firstButtonPressed = false; private float lastDashTime; public float timePresses = 0.3f; // 双击间隔阈值 public float dashDistance = 10f; public float dashingTime = 0.2f; public float dashingCooldown = 1f; private Rigidbody2D heroBody;
2. 修正Dash回调与双击逻辑
private void Awake() { dashAction.performed += Dash; heroBody = GetComponent<Rigidbody2D>(); } private void OnEnable() { horizontalAction.Enable(); dashAction.Enable(); } private void OnDisable() { horizontalAction.Disable(); dashAction.Disable(); } public void Dash(InputAction.CallbackContext context) { if (context.performed) { // 先校验状态,避免重复触发 if (dashing || !canDash) return; if (Time.time - lastDashTime < timePresses) { StartCoroutine(DashAction()); Debug.Log("DUPLO CLIQUE"); firstButtonPressed = false; } else if (!firstButtonPressed) { firstButtonPressed = true; lastDashTime = Time.time; } else { firstButtonPressed = false; } } } private IEnumerator DashAction() { // 用新Input System获取水平输入方向(-1=左,1=右) float dirX = horizontalAction.ReadValue<float>(); // 处理输入为0的情况:双击时没按住方向键,用角色当前朝向判断 if (dirX == 0) { dirX = transform.localScale.x > 0 ? 1 : -1; } canDash = false; dashing = true; float originalGravity = heroBody.gravityScale; heroBody.gravityScale = 0f; // 用正确的方向值计算Dash速度 heroBody.velocity = new Vector2(dirX * dashDistance, 0f); yield return new WaitForSeconds(dashingTime); heroBody.gravityScale = originalGravity; dashing = false; yield return new WaitForSeconds(dashingCooldown); canDash = true; }
额外注意事项
- 若使用代码内的手动双击判断,无需在Input Action中设置
Double Click,仅绑定Key Down事件即可;若依赖Input Action的双击检测,可移除代码内的双击逻辑,直接触发DashAction。 - 测试时可在
DashAction中打印dirX和heroBody.velocity的值,确认方向和速度是否符合预期。
内容的提问来源于stack exchange,提问作者AMFr3it4s
相关产品推荐
相关产品推荐

