简体   繁体   中英

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

As you can see in this video, the object moves in any direction, but its model does not rotate in the direction of movement. How to fix it??

Link to video

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");
    }
}

Don't use transform.forward and transform.right to make your move vector, just make it in world space. Then, you can set transform.forward to the move direction.

Also, as derHugo mentioned below in a comment, you should

  1. avoid using exact equality to compare floats. Instead use Mathf.Approximately or use your own threshold like below

  2. avoid setting triggers every frame. instead you can use a flag to determine if you're already idle or already running, and only set the trigger if you're not already doing the thing.

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM