Unity 2D中如何实现稳定一致的玩家冲刺速度?
问题解决思路与方案
核心问题分析
碰撞后Rigidbody2D.velocity归零,导致冲刺时playerRB.velocity.normalized得到的是零向量,施加的冲刺力自然无效或极弱。
解决方案
1. 改用玩家输入方向作为冲刺核心依据
玩家冲刺的意图是当前的移动方向,而非碰撞后被重置的速度方向,直接用输入方向能彻底规避速度归零的问题。
2. 增加方向 fallback 逻辑
如果玩家没有按下移动键(输入方向为零),再尝试用当前速度方向,最后兜底用玩家默认朝向(比如transform.right),保证冲刺总有有效方向。
3. 优化输入缓存
在Update中提前缓存输入方向,避免FixedUpdate和冲刺逻辑中重复获取输入导致的帧同步问题。
修改后的完整代码
public class PlayerMovement : MonoBehaviour { private Rigidbody2D playerRB; private float dashForce = 75f; public float playerSpeed = 175f; private Vector2 currentInputDirection; // 缓存当前输入方向 void Start() { playerRB = GetComponent<Rigidbody2D>(); } void Update() { // 每帧缓存输入方向,保证冲刺时获取的是玩家当前的移动意图 currentInputDirection = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normalized; if (Input.GetKeyDown(KeyCode.Space)) Dash(); } void FixedUpdate() { playerRB.AddForce(currentInputDirection * playerSpeed); } void Dash() { // 冲刺期间切换碰撞层 gameObject.layer = LayerMask.NameToLayer("dashIgnore"); StartCoroutine(EnableCollisionsAfterDelay(0.2f)); // 优先使用输入方向作为冲刺方向 Vector2 dashDirection = currentInputDirection; // 输入方向无效时, fallback 到当前速度方向 if (dashDirection.magnitude < 0.1f) { dashDirection = playerRB.velocity.normalized; // 速度方向也无效时,用玩家默认朝向兜底 if (dashDirection.magnitude < 0.1f) dashDirection = transform.right; } dashTrail.emitting = true; playerRB.AddForce(dashDirection * dashForce, ForceMode2D.Impulse); } IEnumerator EnableCollisionsAfterDelay(float delay) { yield return new WaitForSeconds(delay); gameObject.layer = LayerMask.NameToLayer("Player"); dashTrail.emitting = false; } }
关键修改说明
- 新增
currentInputDirection在Update中缓存输入,避免碰撞后速度归零导致的方向丢失 - 冲刺方向优先级:玩家输入方向 > 当前速度方向 > 玩家默认朝向,确保冲刺始终有有效方向
- 修正了方法名大小写,符合C#编码规范
内容的提问来源于stack exchange,提问作者Thirstymidget28
相关产品推荐
相关产品推荐

