Unity角色移动方向与输入偏移90度问题求助
解决角色朝向偏移90度且反向移动的问题
看起来你的角色输入和旋转/移动的轴映射搞混了,这在Unity 3D角色控制里是很常见的问题,我帮你梳理下解决方案:
问题根源
核心问题出在输入轴与角色旋转计算的轴对应关系不匹配,再加上移动方向没有和修正后的朝向对齐,导致了偏移和反向的问题。具体来说:
- 你用
Mathf.Atan2(inputDir.x, inputDir.y)计算旋转角度的参数顺序,和Unity默认的角色前向(Z轴)不匹配,直接导致了90度偏移 - 移动时直接使用
transform.forward,在朝向没修正的情况下自然会反向
修改后的完整代码
public float walkSpeed = 2; public float runSpeed = 6; public float turnSmoothTime = 0.2f; float turnSmoothVelocity; public float speedSmoothTime = 0.1f; float speedSmoothVelocity; float currentSpeed; Animator animator; void Start () { animator = GetComponent<Animator> (); } void Update () { Vector2 input = new Vector2 (Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical")); Vector2 inputDir = input.normalized; if (inputDir != Vector2.zero) { // 修正旋转角度:适配Unity默认Z轴前向 float targetRotation = Mathf.Atan2(inputDir.x, inputDir.y) * Mathf.Rad2Deg - 90f; transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(transform.eulerAngles.y, targetRotation, ref turnSmoothVelocity, turnSmoothTime); } bool running = Input.GetKey (KeyCode.LeftShift); float targetSpeed = ((running) ? runSpeed : walkSpeed) * inputDir.magnitude; currentSpeed = Mathf.SmoothDamp (currentSpeed, targetSpeed, ref speedSmoothVelocity, speedSmoothTime); // 基于修正后的朝向移动 Vector3 moveDir = transform.forward * currentSpeed * Time.deltaTime; transform.Translate(moveDir, Space.World); float animationSpeedPercent = ((running) ? 1 : .5f) * inputDir.magnitude; animator.SetFloat ("speedPercent", animationSpeedPercent, speedSmoothTime, Time.deltaTime); }
关键修改说明
- 旋转角度适配:
给原来的旋转计算加上了- 90f的偏移。这是因为Unity默认角色的前向(transform.forward)是Z轴正方向,而Atan2(x,y)算出的角度对应的是X轴正方向,减去90度后就能让输入方向和角色朝向完全对齐。如果改完还是有偏移,试试把-90f换成+90f,这取决于你的模型局部轴的朝向。 - 移动方向验证:
确保移动时用的是修正后的transform.forward。如果还是反向移动,可以尝试把transform.forward改成-transform.forward,或者把Input.GetAxisRaw("Vertical")改成-Input.GetAxisRaw("Vertical")来反转输入轴。 - 模型轴额外检查:
即使你旋转过模型,也建议在Scene视图里选中角色,看看Transform组件的轴显示——蓝色轴(Z轴)应该指向你期望的"前方",如果不是,可能需要在建模软件里调整模型的根轴方向,而不是在Unity里旋转GameObject(那样会导致后续的轴混乱)。
内容的提问来源于stack exchange,提问作者Im Bulletproof
相关产品推荐
相关产品推荐

