Unity游戏冲刺(Dash)功能失效求助:为何无法正常运行?
Unity 冲刺功能无响应且调试日志无输出的修复方案
核心问题
你的冲刺逻辑里canDash变量从未被初始化为true,默认值是false,所以Input.GetKeyDown(KeyCode.Q)&& canDash这个条件永远不成立,调试日志自然不会输出,冲刺协程也不会启动。
具体修复步骤
- 初始化
canDash变量
在Start()方法中添加一行初始化代码,让游戏启动时就允许冲刺:
void Start() { CurrentHealth = MaxHealth; rb = GetComponent<Rigidbody2D>(); canDash = true; // 新增:初始化冲刺权限 }
- 优化冲刺方向的稳定性
当前冲刺方向依赖transform.localScale.x,如果角色缩放不是严格的1或-1(比如做了拉伸缩放),会导致冲刺速度异常。建议用Mathf.Sign()来确保方向正确:
rb.velocity = new Vector2(Mathf.Sign(transform.localScale.x) * dashingPower, 0f);
- 确认输入焦点与按键绑定
测试时确保游戏窗口处于激活状态,避免按键输入被其他窗口拦截;如果后续想改用输入轴绑定,可以在Unity的Input Manager中添加自定义轴,但当前用KeyCode.Q的写法是没问题的。
修改后的完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Core : MonoBehaviour { public float speed; public float move; private Rigidbody2D rb; public float jump = 6f; public Transform groundCheck; public float groundCheckRadius; public LayerMask groundLayer; private bool isTouchingGround; public int MaxHealth = 100; public int CurrentHealth; bool isgrounded; private bool canDash; private bool isDashing; private float dashingPower = 24f; private float dashingTime = 0.2f; private float dashingCoolDown = 1f; void Start() { CurrentHealth = MaxHealth; rb = GetComponent<Rigidbody2D>(); canDash = true; // 初始化冲刺权限 } void Update() { if (isDashing) { return; } isTouchingGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer); if (Input.GetButtonDown("Jump") && isTouchingGround) { rb.AddForce(new Vector2(rb.velocity.x, jump)); } move = Input.GetAxis("Horizontal"); rb.velocity = new Vector2(move * speed, rb.velocity.y); if (Input.GetKeyDown(KeyCode.Q) && canDash) { Debug.Log("deste um Dash"); StartCoroutine(Dash()); } } void takeDamage(int amount) { CurrentHealth += amount; if (CurrentHealth <= 0) { // 添加死亡动画或游戏逻辑 } } private IEnumerator Dash() { canDash = false; isDashing = true; float originalGravity = rb.gravityScale; rb.gravityScale = 0f; // 用Mathf.Sign确保方向正确 rb.velocity = new Vector2(Mathf.Sign(transform.localScale.x) * dashingPower, 0f); yield return new WaitForSeconds(dashingTime); rb.gravityScale = originalGravity; isDashing = false; yield return new WaitForSeconds(dashingCoolDown); canDash = true; } }
内容的提问来源于stack exchange,提问作者aquele puto pro gamer
相关产品推荐
相关产品推荐

