How to change the direction of player movement and make turning smoother

I’m fairly new to Unity and C#, but I am willing to learn. I would appreciate any help!

I have a player with a camera which follows it, and can be controlled by the arrow keys. When the player changes directions, I would like for the new direction the player is facing to be “forward”, so the forward arrow key makes the player move in the direction it is facing. How could I go about that?

I would also like to make the turning of the character more smooth so that it’s not so disorienting. How could I do that also?
I’m using Unity version 2019.1.1f1.

Here’s my code:

using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
  
    public class PlayerController : MonoBehaviour
    {
        public float turnSpeed = 1f;
  
        Animator m_Animator;
        Rigidbody m_Rigidbody;
        Vector3 m_Movement;
        Quaternion m_Rotation = Quaternion.identity;
  
        void Start()
        {
            m_Animator = GetComponent<Animator>();
            m_Rigidbody = GetComponent<Rigidbody>();
        }
  
        void FixedUpdate()
        {
            float horizontal = Input.GetAxis("Horizontal");
            float vertical = Input.GetAxis("Vertical");
  
            m_Movement.Set(horizontal, 0f, vertical);
            m_Movement.Normalize();
  
            bool hasHorizontalInput = !Mathf.Approximately(horizontal, 0f);
            bool hasVerticalInput = !Mathf.Approximately(vertical, 0f);
            bool isWalking = hasHorizontalInput || hasVerticalInput;
            m_Animator.SetBool("IsWalking", isWalking);
  
            Vector3 desiredForward = Vector3.RotateTowards(transform.forward, m_Movement, turnSpeed * Time.deltaTime, 0f);
            m_Rotation = Quaternion.LookRotation(desiredForward);
        }
  
        void OnAnimatorMove()
        {
            m_Rigidbody.MovePosition(m_Rigidbody.position + m_Movement * m_Animator.deltaPosition.magnitude);
            m_Rigidbody.MoveRotation(m_Rotation);
        }
    }

Thanks in advance!

Hi girlinorbit,

Things I would suggest :

  • Change the FixedUpdate to Update (the latter is frame based, the former more for things like physics API calls).
  • Remove m_Movement and m_Rigidbody, and instead try using Transform.Translate. This will give you easy character relative movement. If you want to move to a physics based approach, you can always do so later.
  • For the rotation, have you tried simply transform.rotate(0f, turnSpeed * Time.deltaTime, 0f, Space.Self);?

For the camera, I presume that you are wanting to code this yourself to learn (rather than using something like cinemachine)?