Unity归一化移动后速度异常缓慢问题排查
问题分析与解决
你的代码核心问题是归一化时机搞反了——这直接导致你设置的速度值被无效化,不管把speed或runSpeed调多大,实际移动速度都会被锁死在1左右,自然异常缓慢。
错误根源
你先把输入轴乘以速度值得到targetVelocity,斜向移动时这个向量的幅值会是targetMovingSpeed × √2(比如速度设为5,斜向时幅值约为7),远大于1。随后的归一化操作会把这个向量的幅值直接压缩到1,等于完全丢弃了之前乘的速度值,最终刚体的移动速度就固定在1附近。
修正后的代码
正确逻辑是先处理输入向量的归一化,再乘以目标速度:
float targetMovingSpeed = IsRunning ? runSpeed : speed; // 先获取未缩放的原始输入 Vector2 rawInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")); // 对原始输入归一化,避免斜向速度超标 if (rawInput.magnitude > 1) { rawInput = rawInput.normalized; } // 再乘以目标速度得到最终移动向量 Vector2 targetVelocity = rawInput * targetMovingSpeed; // 应用移动 rigidbody.velocity = transform.rotation * new Vector3(targetVelocity.x, rigidbody.velocity.y, targetVelocity.y);
简化优化写法
可以用Vector2.ClampMagnitude替代手动判断,代码更简洁:
float targetMovingSpeed = IsRunning ? runSpeed : speed; Vector2 rawInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")); // 直接将输入向量的幅值限制在1以内 rawInput = Vector2.ClampMagnitude(rawInput, 1f); Vector2 targetVelocity = rawInput * targetMovingSpeed; rigidbody.velocity = transform.rotation * new Vector3(targetVelocity.x, rigidbody.velocity.y, targetVelocity.y);
修改后,横向、纵向、斜向移动的速度都会严格等于你设置的speed或runSpeed,既解决了斜向速度超标问题,也不会出现速度被莫名削弱的情况。
内容的提问来源于stack exchange,提问作者Yeonari
相关产品推荐
相关产品推荐

