Unity中角色单方向Velocity无法停止及X轴自动减速问题求助
问题修复与解释
核心问题原因
上下键松开后角色持续移动:代码仅在按下上下键时设置Z轴速度,但松开按键后没有任何逻辑将Z轴速度重置为0。而左右键按下时会直接覆盖Velocity为X轴方向的速度(Z轴设为0),所以松开左右键后,X轴速度会被Rigidbody的阻力/地面摩擦减速到0;但Z轴速度在松开上下键后会一直保持,直到其他按键覆盖Velocity。
X轴方向自动减速:这是因为Rigidbody组件的
Drag(阻力)属性或地板的物理材质(Physics Material)设置了摩擦力。当松开左右键后,没有代码维持X轴速度,阻力/摩擦力会逐渐将X轴速度衰减至0。
修复代码(实现按键移动、松键停止)
修改移动逻辑,先计算输入方向,再统一设置Velocity,这样松开按键时对应轴的速度会自动归零,同时保留Y轴的原有速度(比如跳跃的速度):
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { Rigidbody rb; // 提前获取引用,避免每帧查找组件 Transform playerTransform; Transform mainCameraTransform; // 可调整的速度参数 public float moveSpeed = 5f; public float jumpForce = 5f; void Start() { rb = GetComponent<Rigidbody>(); playerTransform = transform; mainCameraTransform = GameObject.Find("Main Camera").transform; } void Update() { // 优化后的相机跟随 mainCameraTransform.position = new Vector3( playerTransform.position.x, playerTransform.position.y + 3.5f, playerTransform.position.z - 6f ); // 计算输入方向 float xInput = 0f; float zInput = 0f; if (Input.GetKey("up")) zInput = 1f; if (Input.GetKey("down")) zInput = -1f; if (Input.GetKey("left")) xInput = -1f; if (Input.GetKey("right")) xInput = 1f; // 设置移动速度,保留Y轴原有速度(不覆盖跳跃状态) rb.velocity = new Vector3(xInput * moveSpeed, rb.velocity.y, zInput * moveSpeed); // 跳跃逻辑 if (Input.GetKeyDown("space")) { rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z); } } }
额外优化建议
- 移除每帧
GameObject.Find调用:该方法性能开销高,在Start中一次性获取引用即可。 - 添加地面检测:当前跳跃逻辑允许空中多次跳跃,可通过
Physics.Raycast或OnCollisionStay判断是否在地面,优化跳跃体验。 - 改用
Input.GetAxis:Input.GetAxis("Horizontal")和Input.GetAxis("Vertical")支持游戏手柄,且自带平滑输入,代码更简洁通用。
内容的提问来源于stack exchange,提问作者mike
相关产品推荐
相关产品推荐

