统一。如何将玩家转向运动方向

Unity. How to turn the player in the direction of movement

正如您在该视频中所见,物体向任意方向移动,但其模型不沿移动方向旋转。如何解决??

Link 到视频

https://youtu.be/n4FDFDlsXK4

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveController : MonoBehaviour
{
    private CharacterController controller = null;
    private Animator animator = null;
    private float speed = 5f;


    void Start()
    {
        controller = gameObject.GetComponent<CharacterController>();
        animator = gameObject.GetComponent<Animator>();
    }

    void Update()
    {
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = (transform.right * x) + (transform.forward * z);
        controller.Move(move * speed * Time.deltaTime);

        var angle = Mathf.Atan2(move.z, move.x) * Mathf.Rad2Deg;

        if (x != 0 || z != 0) animator.SetTrigger("run");
        if (x == 0 && z == 0) animator.SetTrigger("idle");
    }
}

不要使用 transform.forwardtransform.right 来制作你的移动矢量,只需在世界 space 中制作即可。然后,您可以将transform.forward设置为移动方向。

此外,正如下面评论中提到的 derHugo,您应该

  1. 避免使用完全相等来比较浮点数。而是使用 Mathf.Approximately 或使用您自己的阈值,如下所示

  2. 避免设置每帧触发。相反,您可以使用一个标志来确定您是否已经空闲或已经 运行,并且只有在您还没有做这件事时才设置触发器。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveController : MonoBehaviour
{
    private CharacterController controller = null;
    private Animator animator = null;
    private float speed = 5f;
    bool isIdle;

    void Start()
    {
        controller = gameObject.GetComponent<CharacterController>();
        animator = gameObject.GetComponent<Animator>();
        isIdle = true;
    }

    void Update()
    {
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = new Vector3(x, 0f, z);
        controller.Move(move * speed * Time.deltaTime);

        var angle = Mathf.Atan2(move.z, move.x) * Mathf.Rad2Deg;

        if (move.magnitude > idleThreshold)
        {
            transform.forward = move;
            if (isIdle) 
            {
                animator.SetTrigger("run");
                isIdle = false;
            }
        } 
        else if (!isIdle)
        {
            animator.SetTrigger("idle");
            isIdle = true;
        }
    }
}